@fetchbrain.com/sdk 0.6.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,9 +5,9 @@
5
5
  <img src="logo/fetchbrain-logo-primary.svg" alt="FetchBrain" width="340">
6
6
  </picture>
7
7
 
8
- **Make your scrapers smarter with every run.**
8
+ **Never pay twice for the same page.**
9
9
 
10
- *Your crawler teaches it once. It recalls it on every run after.*
10
+ *Your scraper learns a page once; within your memory depth, later runs recall it — and known pages you add with `crawler.addRequests()` skip the fetch.*
11
11
 
12
12
  [![CI](https://github.com/fetchbrain-com/sdk/actions/workflows/ci.yml/badge.svg)](https://github.com/fetchbrain-com/sdk/actions/workflows/ci.yml) [![npm version](https://badge.fury.io/js/@fetchbrain.com%2Fsdk.svg)](https://www.npmjs.com/package/@fetchbrain.com/sdk) [![TypeScript](https://img.shields.io/badge/TypeScript-first-3178C6.svg)](https://www.typescriptlang.org/) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
13
13
 
@@ -21,12 +21,12 @@ Every scraping run re-fetches thousands of pages you already scraped last
21
21
  time — paying for proxies, browsers, retries, and CAPTCHAs to learn things
22
22
  you already know.
23
23
 
24
- FetchBrain gives each of your scrapers a **memory**. Before each request, a
24
+ FetchBrain gives your scrapers a **memory**, private to your account. Before each request, a
25
25
  crawler asks *"do I already know this request?"* — known requests come back
26
- **in milliseconds** without your scraper fetching the page; unknown ones run
26
+ **from memory** (those you add with `crawler.addRequests()` skip the fetch entirely); unknown ones run
27
27
  normally and are learned. Memory grows run after run, and `ask()` answers
28
28
  plain-English questions from what you've learned — a data asset that
29
- compounds instead of costs. **Learning is always free.**
29
+ compounds instead of costs. **Learning is never billed.**
30
30
 
31
31
  ```text
32
32
  $ node scraper.js # first run — the brain learns
@@ -56,7 +56,7 @@ FetchBrain.enhance(crawler, { apiKey: process.env.FETCHBRAIN_API_KEY });
56
56
 
57
57
  await crawler.run(["https://example.com/"]);
58
58
  // Run 1: your scraper fetches the page and teaches your brain
59
- // Run 2: recalled from memory in milliseconds, no HTTP request to example.com
59
+ // Run 2: recalled from memory, no HTTP request to example.com
60
60
  ```
61
61
 
62
62
  ## One line to adopt
@@ -85,10 +85,10 @@ That's it. Your handler only runs when there's something new to learn.
85
85
 
86
86
  | | Without | With FetchBrain |
87
87
  | --- | --- | --- |
88
- | **Repeat requests** | Full fetch, every run | Recalled in milliseconds |
88
+ | **Repeat requests** | Full fetch, every run | Recalled from memory |
89
89
  | **Proxy & compute spend** | Pay per fetch, every run | Pay only for what it knows |
90
90
  | **Blocks & CAPTCHAs** | Every run risks them | Pre-recalled known requests skip the fetch |
91
- | **When the service is down** | — | Your crawl runs normally (circuit breaker, 500ms timeout) |
91
+ | **When the service is down** | — | Your crawl runs normally (circuit breaker, 1.5s timeout) |
92
92
  | **Testing** | Mock it yourself | `MockFetchBrain` ships in the box |
93
93
 
94
94
  - **Recall before you fetch** — known requests are answered from memory; when they're recalled at enqueue time, the page is never fetched ([caveats](#recall-at-enqueue-time-prerecall))
@@ -96,7 +96,7 @@ That's it. Your handler only runs when there's something new to learn.
96
96
  - **Auto-learning** — every successful scrape teaches the brain, free
97
97
  - **Never breaks your crawl** — the circuit breaker degrades gracefully; an outage costs you optimization, not your crawl (one deliberate exception: [expired memory](#recall-at-enqueue-time-prerecall))
98
98
  - **Built for scale** — request batching and deduping for high-concurrency crawlers
99
- - **Crawlee-native** — CheerioCrawler, PlaywrightCrawler, and friends
99
+ - **Crawlee-native** — CheerioCrawler, PlaywrightCrawler, and friends (browser crawlers — Playwright, Puppeteer — from 0.7.1; earlier versions did not apply FetchBrain to them. `AdaptivePlaywrightCrawler` is not supported yet)
100
100
  - **Transparent** — see exactly [what leaves your process](#what-leaves-your-process). Telemetry is **opt-in** and pseudonymous ([details](#telemetry-opt-in))
101
101
  - **TypeScript-first** — full types, ESM + CJS; an API key is the only required option
102
102
 
@@ -109,13 +109,13 @@ freshness-critical monitoring where you always need the live value.
109
109
  Everywhere else, it compounds:
110
110
 
111
111
  **Data-service teams & aggregators** — each scraper fetches an expensive
112
- request once and recalls it on every run after, so per-run proxy and compute
112
+ request once and recalls it on later runs within your memory depth, so per-run proxy and compute
113
113
  cost falls as coverage grows — and `ask()` turns what they've collected into
114
114
  memory you can ask questions of, with no warehouse to run.
115
115
 
116
116
  **Product teams & AI agents** — apps and browsing agents that re-hit the same
117
- requests get them back in milliseconds, straight from memory: no fetch, no
118
- proxy, no block. The more often a scraper revisits the same requests, the more
117
+ requests get them back straight from memory: known pages you add with
118
+ `crawler.addRequests()` skip the fetch, so they cost no proxy traffic. The more often a scraper revisits the same requests, the more
119
119
  its memory pays off.
120
120
 
121
121
  **Recurring crawls of stable data** — catalogs, specs, listings, company and
@@ -123,7 +123,7 @@ reference data barely change between runs, so recall skips the fetch and each
123
123
  scheduled run costs less. Keep volatile fields on `memory: "fresh"` so you
124
124
  never trade accuracy for speed.
125
125
 
126
- **Solo scraper developers** — start free: learning never costs anything, and
126
+ **Solo scraper developers** — start free: learning is never billed, and
127
127
  the requests you've already made come back from memory instead of getting
128
128
  blocked or throttled. One line to add, one brain that grows with everything
129
129
  you scrape.
@@ -160,7 +160,7 @@ await crawler.run(urls);
160
160
  ## How it works
161
161
 
162
162
  ```
163
- Your crawler ──▶ FetchBrain ──▶ knows this request? ──▶ YES ──▶ data in milliseconds, no fetch
163
+ Your crawler ──▶ FetchBrain ──▶ knows this request? ──▶ YES ──▶ data from memory (pre-recalled requests skip the fetch)
164
164
  │
165
165
  └──▶ NO ──▶ your handler runs ──▶ brain learns, free
166
166
  ```
@@ -253,7 +253,7 @@ interface FetchBrainConfig {
253
253
  onRecalled?: (event: RecalledEvent) => void | Promise<void>; // Per-record hook when recalled data is delivered
254
254
  extractForLearning?: (data: unknown) => Record<string, unknown>; // Transform each record before it is learned
255
255
  refreshOnRebuild?: boolean; // Scope learn, recall and ask to the current build (*_BUILD_ID env var) (default: false)
256
- timeout?: number; // Handler-time recall, stats and telemetry timeout in ms (default: 500)
256
+ timeout?: number; // Handler-time recall, stats and telemetry timeout in ms (default: 1500)
257
257
  batch?: { maxSize?: number; maxWait?: number }; // Request batching (default: 50 items / 50ms)
258
258
  circuitBreaker?: {
259
259
  failureThreshold?: number; // Failures before the circuit opens (default: 3)
@@ -300,7 +300,7 @@ your request handler runs — so a recall inside the handler is too late to
300
300
  save the fetch. With `preRecall` (on by default), the SDK checks the brain
301
301
  the moment requests enter the queue: each `crawler.addRequests()` array
302
302
  becomes a single bulk recall, known requests are enqueued with Crawlee's
303
- `skipNavigation` so their fetch never happens, and unknown requests carry
303
+ `skipNavigation` so they're skipped before they're fetched, and unknown requests carry
304
304
  their recall result with them so the handler doesn't ask twice. Enqueue in
305
305
  batches (one `addRequests` call per page of discovered items) to get the
306
306
  most out of it. If the brain is unreachable, requests are enqueued unchanged
@@ -427,6 +427,25 @@ paid plan, `"byok"` with no linked provider — the response comes back with
427
427
  `status: "unavailable"`, which means the API itself is degraded or
428
428
  unreachable.
429
429
 
430
+ ## What gets learned from a page
431
+
432
+ - Everything a request's handler pushes is learned **together, once the handler
433
+ succeeds**. A listing page that pushes 20 products is remembered as those 20
434
+ products and recalled as all 20, in order.
435
+ - A handler that throws (even after pushing) teaches nothing for that request,
436
+ so a half-parsed page is never remembered; the retry learns it.
437
+ - Learning happens in the background: `pushData` never waits for it, and
438
+ `crawler.run()` delivers every pending learn before it resolves. If the API
439
+ falls behind, a handler waits briefly (at most 5s, counted toward Crawlee's
440
+ `requestHandlerTimeoutSecs`) for learns to catch up;
441
+ past that the page is not learned, and the crawl carries on.
442
+ - A page's data is learned whole or not at all, up to **100KB** (after
443
+ `extractForLearning`). A page over the limit is not learned and is fetched
444
+ again on later runs; the SDK warns the first time. A listing of many records
445
+ can pass 100KB even when each record is small — use `extractForLearning` to
446
+ keep only the fields you need.
447
+ - The run summary's `learned` counts only records from learns the API accepted.
448
+
430
449
  ## Learning with `Dataset.pushData`
431
450
 
432
451
  > **Important:** the brain learns only from `context.pushData()` or the
@@ -493,11 +512,11 @@ Timeouts per call type:
493
512
 
494
513
  | Call | Timeout |
495
514
  | --- | --- |
496
- | Recall in the handler (batched) | `timeout` option, default 500ms |
515
+ | Recall in the handler (batched) | `timeout` option, default 1.5s |
497
516
  | Recall at enqueue (`preRecall`, bulk) | 3s per chunk of up to 100 requests |
498
517
  | Learn (batched, sent in the background) | 5s |
499
518
  | `ask()` | 10s |
500
- | `stats()` and telemetry | `timeout` option, default 500ms |
519
+ | `stats()` and telemetry | `timeout` option, default 1.5s |
501
520
 
502
521
  A FetchBrain outage costs you *optimization*, not your crawl: SDK calls
503
522
  degrade gracefully instead of throwing into it. The one deliberate
@@ -677,12 +696,16 @@ headers including platform identifiers (env vars ending in `_ID`, plus
677
696
  telemetry, the fields in [Telemetry](#telemetry-opt-in) too.
678
697
 
679
698
  **What does learning cost?**
680
- Nothing. Learning is always free — you pay only for known recalls.
699
+ Nothing. Learning is never billed — you pay only for known recalls.
681
700
 
682
701
  **What if the data changed since the brain learned it?**
683
702
  That's what memory depth is for: pick `fresh` (1h) for volatile data, or
684
703
  set `refreshOnRebuild` to re-learn whenever you ship a new scraper build.
685
704
 
705
+ **Can I call `enhance()` twice on the same crawler?**
706
+ Don't — each call wraps the crawler again, so recalls and learns run twice.
707
+ Enhance a crawler once, right after you create it.
708
+
686
709
  ## Contributing
687
710
 
688
711
  Issues and PRs welcome — see [open issues](https://github.com/fetchbrain-com/sdk/issues).
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnResponse, S as StatsResponse, A as AskResponse, C as CircuitState, T as TelemetryData, b as TelemetryConfig, c as CircuitBreakerConfig, d as Logger, B as BatchConfig, e as LogLevel } from './types-B1MFygnZ.mjs';
2
- export { i as LearnRequest, M as MemoryDepth, f as RecallRequest, g as RecallResponse, h as RecallResultItem, j as RecalledEvent, k as TelemetryRequest, l as TelemetryResponse } from './types-B1MFygnZ.mjs';
1
+ import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnedData, b as LearnResponse, S as StatsResponse, A as AskResponse, C as CircuitState, T as TelemetryData, c as TelemetryConfig, d as CircuitBreakerConfig, e as Logger, B as BatchConfig, f as LogLevel } from './types-CSG4BekA.mjs';
2
+ export { j as LearnRequest, M as MemoryDepth, g as RecallRequest, h as RecallResponse, i as RecallResultItem, k as RecalledEvent, l as TelemetryRequest, m as TelemetryResponse } from './types-CSG4BekA.mjs';
3
3
 
4
4
  /**
5
5
  * FetchBrain API Client
@@ -20,25 +20,46 @@ declare class FetchBrainClient {
20
20
  * learn cap — the start of the next UTC month, when the cap resets. 0 = not paused.
21
21
  */
22
22
  private learnPausedUntil;
23
+ /**
24
+ * Set by a 401 (key invalid or revoked): calls answer locally until then
25
+ * instead of each paying a failing round-trip. A pause, not a permanent stop:
26
+ * a key used right after it is created can see a brief 401 while the key
27
+ * propagates, and that must not switch FetchBrain off for a whole run.
28
+ */
29
+ private keyRejectedUntil;
30
+ private keyRejectedWarned;
31
+ /** The oversized-page warning is shown once per client, then logged at debug. */
32
+ private warnedOversizeLearn;
23
33
  /** Warn about the learn cap once per pause, independent of the pause state. */
24
34
  private learnCapWarnedUntil;
25
35
  /** Valid, normalized scraper name (option, else env var); undefined = default memory. */
26
36
  private scraperName;
27
37
  constructor(config: FetchBrainConfig);
38
+ /** True when recalls must not reach the API right now (crawl continues without). */
39
+ private recallBlocked;
40
+ private isKeyRejected;
41
+ /**
42
+ * React to a 4xx the API returned. These are not outages (they don't open the
43
+ * shared breaker). A 401 means the next calls would fail the same way, so all
44
+ * calls pause for KEY_REJECTED_PAUSE_MS. (429 on recall deliberately does NOT
45
+ * pause recalls locally: a locally refused handler-time recall fails a
46
+ * fetch-skipped request, whereas the API's own answer can still succeed.)
47
+ */
48
+ private noteRefusal;
28
49
  /**
29
50
  * Recall if FetchBrain "knows" a request
30
51
  */
31
52
  recall(request: RawRequest): Promise<RecallResult>;
32
53
  /**
33
54
  * Recall multiple requests at once — returns ordered array matching input order.
34
- * Chunks to the API's 100-item cap and runs chunks with bounded concurrency; a
55
+ * Chunks to MAX_BULK_ITEMS (under the API's 100-item cap) and runs chunks with bounded concurrency; a
35
56
  * failed chunk degrades to fallback results for its own items only.
36
57
  */
37
58
  recallBulk(requests: RawRequest[]): Promise<RecallResult[]>;
38
59
  /**
39
60
  * "Teach" FetchBrain new data (batched for high-concurrency)
40
61
  */
41
- learn(request: RawRequest, data: Record<string, unknown>): Promise<LearnResponse>;
62
+ learn(request: RawRequest, data: LearnedData): Promise<LearnResponse>;
42
63
  /**
43
64
  * Get usage statistics
44
65
  */
@@ -60,6 +81,8 @@ declare class FetchBrainClient {
60
81
  * Execute a batch query against the API
61
82
  */
62
83
  private executeBatchQuery;
84
+ /** Apply the user's extractForLearning hook to each learned record. */
85
+ private extractForLearning;
63
86
  /**
64
87
  * Execute a batch learn against the API
65
88
  */
@@ -91,6 +114,11 @@ declare class FetchBrainClient {
91
114
  /**
92
115
  * Flush pending learn requests (call before shutdown)
93
116
  */
117
+ /**
118
+ * Wait (at most `timeoutMs`) until the background learn backlog has room.
119
+ * Lets the crawler slow to the API's pace instead of queueing without limit.
120
+ */
121
+ waitForLearnRoom(timeoutMs: number): Promise<boolean>;
94
122
  flushLearnBatch(): Promise<void>;
95
123
  /**
96
124
  * Send telemetry data to the API
@@ -116,6 +144,8 @@ interface RequestContext {
116
144
  client: FetchBrainClient;
117
145
  learning: boolean;
118
146
  aiKnown: boolean;
147
+ /** Items this request pushed; learned together once the handler succeeds. */
148
+ items: Record<string, unknown>[];
119
149
  }
120
150
  /**
121
151
  * Get the current request context (used by pushData wrapper)
@@ -128,7 +158,7 @@ interface FetchBrainContext {
128
158
  /** Whether the brain knows this URL */
129
159
  known: boolean;
130
160
  /** Brain data if known */
131
- data?: Record<string, unknown>;
161
+ data?: LearnedData;
132
162
  /** Use brain data and skip scraping (call in handler to early return) */
133
163
  use: () => Promise<void>;
134
164
  }
@@ -150,7 +180,7 @@ declare class FetchBrain {
150
180
  memory?: string;
151
181
  }): Promise<{
152
182
  known: boolean;
153
- data: Record<string, unknown> | undefined;
183
+ data: LearnedData | undefined;
154
184
  }>;
155
185
  /**
156
186
  * "Teach" FetchBrain new data
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnResponse, S as StatsResponse, A as AskResponse, C as CircuitState, T as TelemetryData, b as TelemetryConfig, c as CircuitBreakerConfig, d as Logger, B as BatchConfig, e as LogLevel } from './types-B1MFygnZ.js';
2
- export { i as LearnRequest, M as MemoryDepth, f as RecallRequest, g as RecallResponse, h as RecallResultItem, j as RecalledEvent, k as TelemetryRequest, l as TelemetryResponse } from './types-B1MFygnZ.js';
1
+ import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnedData, b as LearnResponse, S as StatsResponse, A as AskResponse, C as CircuitState, T as TelemetryData, c as TelemetryConfig, d as CircuitBreakerConfig, e as Logger, B as BatchConfig, f as LogLevel } from './types-CSG4BekA.js';
2
+ export { j as LearnRequest, M as MemoryDepth, g as RecallRequest, h as RecallResponse, i as RecallResultItem, k as RecalledEvent, l as TelemetryRequest, m as TelemetryResponse } from './types-CSG4BekA.js';
3
3
 
4
4
  /**
5
5
  * FetchBrain API Client
@@ -20,25 +20,46 @@ declare class FetchBrainClient {
20
20
  * learn cap — the start of the next UTC month, when the cap resets. 0 = not paused.
21
21
  */
22
22
  private learnPausedUntil;
23
+ /**
24
+ * Set by a 401 (key invalid or revoked): calls answer locally until then
25
+ * instead of each paying a failing round-trip. A pause, not a permanent stop:
26
+ * a key used right after it is created can see a brief 401 while the key
27
+ * propagates, and that must not switch FetchBrain off for a whole run.
28
+ */
29
+ private keyRejectedUntil;
30
+ private keyRejectedWarned;
31
+ /** The oversized-page warning is shown once per client, then logged at debug. */
32
+ private warnedOversizeLearn;
23
33
  /** Warn about the learn cap once per pause, independent of the pause state. */
24
34
  private learnCapWarnedUntil;
25
35
  /** Valid, normalized scraper name (option, else env var); undefined = default memory. */
26
36
  private scraperName;
27
37
  constructor(config: FetchBrainConfig);
38
+ /** True when recalls must not reach the API right now (crawl continues without). */
39
+ private recallBlocked;
40
+ private isKeyRejected;
41
+ /**
42
+ * React to a 4xx the API returned. These are not outages (they don't open the
43
+ * shared breaker). A 401 means the next calls would fail the same way, so all
44
+ * calls pause for KEY_REJECTED_PAUSE_MS. (429 on recall deliberately does NOT
45
+ * pause recalls locally: a locally refused handler-time recall fails a
46
+ * fetch-skipped request, whereas the API's own answer can still succeed.)
47
+ */
48
+ private noteRefusal;
28
49
  /**
29
50
  * Recall if FetchBrain "knows" a request
30
51
  */
31
52
  recall(request: RawRequest): Promise<RecallResult>;
32
53
  /**
33
54
  * Recall multiple requests at once — returns ordered array matching input order.
34
- * Chunks to the API's 100-item cap and runs chunks with bounded concurrency; a
55
+ * Chunks to MAX_BULK_ITEMS (under the API's 100-item cap) and runs chunks with bounded concurrency; a
35
56
  * failed chunk degrades to fallback results for its own items only.
36
57
  */
37
58
  recallBulk(requests: RawRequest[]): Promise<RecallResult[]>;
38
59
  /**
39
60
  * "Teach" FetchBrain new data (batched for high-concurrency)
40
61
  */
41
- learn(request: RawRequest, data: Record<string, unknown>): Promise<LearnResponse>;
62
+ learn(request: RawRequest, data: LearnedData): Promise<LearnResponse>;
42
63
  /**
43
64
  * Get usage statistics
44
65
  */
@@ -60,6 +81,8 @@ declare class FetchBrainClient {
60
81
  * Execute a batch query against the API
61
82
  */
62
83
  private executeBatchQuery;
84
+ /** Apply the user's extractForLearning hook to each learned record. */
85
+ private extractForLearning;
63
86
  /**
64
87
  * Execute a batch learn against the API
65
88
  */
@@ -91,6 +114,11 @@ declare class FetchBrainClient {
91
114
  /**
92
115
  * Flush pending learn requests (call before shutdown)
93
116
  */
117
+ /**
118
+ * Wait (at most `timeoutMs`) until the background learn backlog has room.
119
+ * Lets the crawler slow to the API's pace instead of queueing without limit.
120
+ */
121
+ waitForLearnRoom(timeoutMs: number): Promise<boolean>;
94
122
  flushLearnBatch(): Promise<void>;
95
123
  /**
96
124
  * Send telemetry data to the API
@@ -116,6 +144,8 @@ interface RequestContext {
116
144
  client: FetchBrainClient;
117
145
  learning: boolean;
118
146
  aiKnown: boolean;
147
+ /** Items this request pushed; learned together once the handler succeeds. */
148
+ items: Record<string, unknown>[];
119
149
  }
120
150
  /**
121
151
  * Get the current request context (used by pushData wrapper)
@@ -128,7 +158,7 @@ interface FetchBrainContext {
128
158
  /** Whether the brain knows this URL */
129
159
  known: boolean;
130
160
  /** Brain data if known */
131
- data?: Record<string, unknown>;
161
+ data?: LearnedData;
132
162
  /** Use brain data and skip scraping (call in handler to early return) */
133
163
  use: () => Promise<void>;
134
164
  }
@@ -150,7 +180,7 @@ declare class FetchBrain {
150
180
  memory?: string;
151
181
  }): Promise<{
152
182
  known: boolean;
153
- data: Record<string, unknown> | undefined;
183
+ data: LearnedData | undefined;
154
184
  }>;
155
185
  /**
156
186
  * "Teach" FetchBrain new data