@fetchbrain.com/sdk 0.7.0 → 0.8.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 CHANGED
@@ -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
 
@@ -261,6 +261,8 @@ interface FetchBrainConfig {
261
261
  successThreshold?: number; // Successes to close it again (default: 1)
262
262
  };
263
263
  telemetry?: TelemetryConfig; // Opt-in telemetry (default: { enabled: false })
264
+ changeDetection?: { enabled?: boolean; ignoreFields?: string[] }; // Relearn known alwaysRun pages and report changes (default: off)
265
+ reportRuns?: boolean; // Send the end-of-run report: run id, timestamps, counts per label (default: true)
264
266
  learnUrlField?: string; // Accepted but not currently applied
265
267
  debug?: boolean; // Enable debug logging (default: false)
266
268
  }
@@ -524,9 +526,72 @@ exception is [expired memory](#recall-at-enqueue-time-prerecall): a request
524
526
  that skipped its fetch at enqueue and whose remembered data is gone fails
525
527
  into your `failedRequestHandler` rather than disappearing silently.
526
528
 
529
+ ## Change detection & drift
530
+
531
+ FetchBrain can tell you when the pages you scrape change, and when your own
532
+ scraper quietly stops extracting something.
533
+
534
+ **What is detected**
535
+
536
+ - **Changed pages**: a page you re-scrape whose data differs from what the
537
+ brain last learned. Each run summary shows a `changed: N` count.
538
+ - **Drift**: a field that used to be filled on most pages of a label and now
539
+ isn't (for example `price` going from 95% filled to 0%), a field that went
540
+ missing, or a field whose type changed. Each finding prints a warning at the
541
+ end of the run, such as `drift [DETAIL] price: filled 95% → 0%`. The same warning (label, field and kind) is shown once per process even if it recurs in a later `run()`; the email and dashboard still reflect it.
542
+ - **Unhealthy runs**: a large share of a label's pages pushed no data or
543
+ failed, such as `40% of DETAIL pages pushed no data`.
544
+
545
+ **Turn on change detection**
546
+
547
+ Pages the brain already knows are normally recalled, not re-scraped. Change
548
+ detection applies to known pages you choose to re-scrape with
549
+ [`alwaysRun`](#choosing-which-handlers-run): with it on, their fresh data is
550
+ learned again and compared with the previous version.
551
+
552
+ ```ts
553
+ FetchBrain.enhance(crawler, {
554
+ apiKey: process.env.FETCHBRAIN_API_KEY,
555
+ alwaysRun: ["DETAIL"],
556
+ changeDetection: {
557
+ enabled: true,
558
+ ignoreFields: ["scrapedAt", "sessionId"], // fields that always differ; not compared
559
+ },
560
+ });
561
+ ```
562
+
563
+ | Option | Default | Meaning |
564
+ | --- | --- | --- |
565
+ | `changeDetection.enabled` | `false` | Relearn known `alwaysRun` pages so changes can be detected |
566
+ | `changeDetection.ignoreFields` | none | Field names to leave out of the comparison |
567
+
568
+ **Cost note:** relearning a known `alwaysRun` page counts toward your learn
569
+ usage, like any other learn. Pages recalled without running your handler are
570
+ never relearned.
571
+
572
+ **Run report**
573
+
574
+ <a id="run-report"></a>
575
+
576
+ When a run finishes, the SDK sends a small report containing exactly: the run
577
+ id, start and end timestamps, totals for scraped, learned and recalled pages,
578
+ per request label how many pages were scraped, came back empty or failed, and
579
+ your build id only when `refreshOnRebuild` is on. It contains no URLs and no
580
+ scraped data. A page counts as "pushed no data" when your handler pushed nothing
581
+ through `context.pushData` or the SDK's `pushData` export (pages written
582
+ straight to Crawlee's static `Dataset.pushData` are counted that way too), and
583
+ retries count once per attempt. The report is sent with the same standard
584
+ headers as every other call (see [What leaves your process](#what-leaves-your-process)). It is what powers the unhealthy-run warnings above. It is not
585
+ [telemetry](#telemetry-opt-in) and is on by default; set `reportRuns: false` to
586
+ turn it off. It is bounded to a few seconds at the end of a run and can never
587
+ fail your crawl.
588
+
589
+ You can browse what changed in the FetchBrain dashboard, or fetch it from
590
+ `GET /v1/changes`.
591
+
527
592
  ## What leaves your process
528
593
 
529
- Every API call (recall, learn, ask, stats, telemetry) sends these headers:
594
+ Every API call (recall, learn, ask, stats, telemetry, run report) sends these headers:
530
595
 
531
596
  | Header | Value |
532
597
  | --- | --- |
@@ -556,7 +621,7 @@ query string), method, `uniqueKey`, label, string POST body, your
556
621
  `Authorization`, `Cookie` and `Set-Cookie`. Recall also sends your `memory`
557
622
  depth; learn also sends the record you pushed (after `extractForLearning`).
558
623
 
559
- With `refreshOnRebuild`, recall, learn and `ask()` also send a build ID: the
624
+ With `refreshOnRebuild`, recall, learn, the run report and `ask()` also send a build ID: the
560
625
  value of the first environment variable whose name ends in `BUILD_ID`. This
561
626
  value is sent as-is — it does **not** go through the name, credential or
562
627
  length filters `X-FB-Context` uses.
@@ -567,7 +632,10 @@ forwarded as-is — keep secrets out of them on requests FetchBrain handles,
567
632
  or route those requests through `skipLabels`, which sends nothing for them.
568
633
 
569
634
  `ask()` sends your question and options. Telemetry sends nothing unless you
570
- [opt in](#telemetry-opt-in).
635
+ [opt in](#telemetry-opt-in). At the end of a run the SDK also sends a small
636
+ [run report](#run-report): run id, start/end timestamps, scraped/learned/recalled
637
+ counts, per-label page counts, and a build id only with `refreshOnRebuild`
638
+ (`reportRuns: false` turns it off).
571
639
 
572
640
  ## Telemetry (opt-in)
573
641
 
@@ -702,6 +770,10 @@ Nothing. Learning is never billed — you pay only for known recalls.
702
770
  That's what memory depth is for: pick `fresh` (1h) for volatile data, or
703
771
  set `refreshOnRebuild` to re-learn whenever you ship a new scraper build.
704
772
 
773
+ **Can I call `enhance()` twice on the same crawler?**
774
+ Don't — each call wraps the crawler again, so recalls and learns run twice.
775
+ Enhance a crawler once, right after you create it.
776
+
705
777
  ## Contributing
706
778
 
707
779
  Issues and PRs welcome — see [open issues](https://github.com/fetchbrain-com/sdk/issues).
package/dist/index.d.mts CHANGED
@@ -1,14 +1,6 @@
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';
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 ChangeStats, c as RunReport, d as RunFlag, e as CircuitState, T as TelemetryData, f as TelemetryConfig, g as CircuitBreakerConfig, h as Logger, B as BatchConfig, i as LogLevel } from './types-B579TMo9.mjs';
2
+ export { o as ChangeDetectionConfig, D as DriftItem, m as LearnRequest, M as MemoryDepth, j as RecallRequest, k as RecallResponse, l as RecallResultItem, n as RecalledEvent, p as TelemetryRequest, q as TelemetryResponse } from './types-B579TMo9.mjs';
3
3
 
4
- /**
5
- * FetchBrain API Client
6
- *
7
- * Handles all communication with the FetchBrain API including:
8
- * - Request batching for high concurrency
9
- * - Circuit breaker for graceful degradation
10
- * - Automatic retries and timeouts
11
- */
12
4
  declare class FetchBrainClient {
13
5
  private config;
14
6
  private circuitBreaker;
@@ -34,6 +26,8 @@ declare class FetchBrainClient {
34
26
  private learnCapWarnedUntil;
35
27
  /** Valid, normalized scraper name (option, else env var); undefined = default memory. */
36
28
  private scraperName;
29
+ /** Change counts, accumulated once per learn HTTP batch (never per learn() promise). */
30
+ private changeStats;
37
31
  constructor(config: FetchBrainConfig);
38
32
  /** True when recalls must not reach the API right now (crawl continues without). */
39
33
  private recallBlocked;
@@ -87,6 +81,15 @@ declare class FetchBrainClient {
87
81
  * Execute a batch learn against the API
88
82
  */
89
83
  private executeBatchLearn;
84
+ /** Fold one batch response into the change totals (called once per HTTP batch). */
85
+ private accumulateChanges;
86
+ /** Change counts so far (a copy). */
87
+ getChangeStats(): ChangeStats;
88
+ /**
89
+ * Send the end-of-run report. Counts and labels only. Never throws: on
90
+ * failure or timeout it returns no flags.
91
+ */
92
+ reportRun(report: RunReport, timeoutMs?: number): Promise<RunFlag[]>;
90
93
  /**
91
94
  * Make an HTTP request to the API
92
95
  */
@@ -144,6 +147,8 @@ interface RequestContext {
144
147
  client: FetchBrainClient;
145
148
  learning: boolean;
146
149
  aiKnown: boolean;
150
+ /** Known page re-scraped with change detection on: its items are relearned. */
151
+ relearn: boolean;
147
152
  /** Items this request pushed; learned together once the handler succeeds. */
148
153
  items: Record<string, unknown>[];
149
154
  }
@@ -417,4 +422,4 @@ declare class TelemetryBuffer {
417
422
  stop(): Promise<void>;
418
423
  }
419
424
 
420
- export { AskResponse, BatchConfig, CircuitBreaker, CircuitBreakerConfig, CircuitState, type CrawleeContext, FetchBrain, FetchBrainClient, FetchBrainConfig, type FetchBrainContext, LearnResponse, LogLevel, Logger, RawRequest, RecallResult, RequestBatcher, type RequestTiming, StatsResponse, TelemetryBuffer, TelemetryConfig, TelemetryData, collectTelemetry, createFetchBrain, createLogger, getCurrentContext, pushData };
425
+ export { AskResponse, BatchConfig, ChangeStats, CircuitBreaker, CircuitBreakerConfig, CircuitState, type CrawleeContext, FetchBrain, FetchBrainClient, FetchBrainConfig, type FetchBrainContext, LearnResponse, LogLevel, Logger, RawRequest, RecallResult, RequestBatcher, type RequestTiming, RunFlag, RunReport, StatsResponse, TelemetryBuffer, TelemetryConfig, TelemetryData, collectTelemetry, createFetchBrain, createLogger, getCurrentContext, pushData };
package/dist/index.d.ts CHANGED
@@ -1,14 +1,6 @@
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';
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 ChangeStats, c as RunReport, d as RunFlag, e as CircuitState, T as TelemetryData, f as TelemetryConfig, g as CircuitBreakerConfig, h as Logger, B as BatchConfig, i as LogLevel } from './types-B579TMo9.js';
2
+ export { o as ChangeDetectionConfig, D as DriftItem, m as LearnRequest, M as MemoryDepth, j as RecallRequest, k as RecallResponse, l as RecallResultItem, n as RecalledEvent, p as TelemetryRequest, q as TelemetryResponse } from './types-B579TMo9.js';
3
3
 
4
- /**
5
- * FetchBrain API Client
6
- *
7
- * Handles all communication with the FetchBrain API including:
8
- * - Request batching for high concurrency
9
- * - Circuit breaker for graceful degradation
10
- * - Automatic retries and timeouts
11
- */
12
4
  declare class FetchBrainClient {
13
5
  private config;
14
6
  private circuitBreaker;
@@ -34,6 +26,8 @@ declare class FetchBrainClient {
34
26
  private learnCapWarnedUntil;
35
27
  /** Valid, normalized scraper name (option, else env var); undefined = default memory. */
36
28
  private scraperName;
29
+ /** Change counts, accumulated once per learn HTTP batch (never per learn() promise). */
30
+ private changeStats;
37
31
  constructor(config: FetchBrainConfig);
38
32
  /** True when recalls must not reach the API right now (crawl continues without). */
39
33
  private recallBlocked;
@@ -87,6 +81,15 @@ declare class FetchBrainClient {
87
81
  * Execute a batch learn against the API
88
82
  */
89
83
  private executeBatchLearn;
84
+ /** Fold one batch response into the change totals (called once per HTTP batch). */
85
+ private accumulateChanges;
86
+ /** Change counts so far (a copy). */
87
+ getChangeStats(): ChangeStats;
88
+ /**
89
+ * Send the end-of-run report. Counts and labels only. Never throws: on
90
+ * failure or timeout it returns no flags.
91
+ */
92
+ reportRun(report: RunReport, timeoutMs?: number): Promise<RunFlag[]>;
90
93
  /**
91
94
  * Make an HTTP request to the API
92
95
  */
@@ -144,6 +147,8 @@ interface RequestContext {
144
147
  client: FetchBrainClient;
145
148
  learning: boolean;
146
149
  aiKnown: boolean;
150
+ /** Known page re-scraped with change detection on: its items are relearned. */
151
+ relearn: boolean;
147
152
  /** Items this request pushed; learned together once the handler succeeds. */
148
153
  items: Record<string, unknown>[];
149
154
  }
@@ -417,4 +422,4 @@ declare class TelemetryBuffer {
417
422
  stop(): Promise<void>;
418
423
  }
419
424
 
420
- export { AskResponse, BatchConfig, CircuitBreaker, CircuitBreakerConfig, CircuitState, type CrawleeContext, FetchBrain, FetchBrainClient, FetchBrainConfig, type FetchBrainContext, LearnResponse, LogLevel, Logger, RawRequest, RecallResult, RequestBatcher, type RequestTiming, StatsResponse, TelemetryBuffer, TelemetryConfig, TelemetryData, collectTelemetry, createFetchBrain, createLogger, getCurrentContext, pushData };
425
+ export { AskResponse, BatchConfig, ChangeStats, CircuitBreaker, CircuitBreakerConfig, CircuitState, type CrawleeContext, FetchBrain, FetchBrainClient, FetchBrainConfig, type FetchBrainContext, LearnResponse, LogLevel, Logger, RawRequest, RecallResult, RequestBatcher, type RequestTiming, RunFlag, RunReport, StatsResponse, TelemetryBuffer, TelemetryConfig, TelemetryData, collectTelemetry, createFetchBrain, createLogger, getCurrentContext, pushData };
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  var async_hooks = require('async_hooks');
4
+ var crypto$1 = require('crypto');
4
5
 
5
6
  // src/enhance.ts
6
7
 
@@ -429,6 +430,7 @@ function getPlatformBuildId(env = process.env) {
429
430
  // src/client.ts
430
431
  var DEFAULT_BASE_URL = "https://api.fetchbrain.com";
431
432
  var DEFAULT_TIMEOUT = 1500;
433
+ var REPORT_RUN_TIMEOUT = 3e3;
432
434
  var DEFAULT_LEARN_TIMEOUT = 5e3;
433
435
  var BULK_RECALL_TIMEOUT = 3e3;
434
436
  var MAX_BULK_ITEMS = 90;
@@ -469,6 +471,9 @@ function setScrapeContext(ctx) {
469
471
  function clearScrapeContext() {
470
472
  currentContext = {};
471
473
  }
474
+ var MAX_DRIFT_ITEMS = 100;
475
+ var DRIFT_KINDS = /* @__PURE__ */ new Set(["fill_drop", "missing", "type_changed"]);
476
+ var clipText = (v, max = 128) => String(v).replace(/[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028-\u202e\u2060-\u2069\ufeff]/g, " ").slice(0, max);
472
477
  var FetchBrainClient = class {
473
478
  constructor(config) {
474
479
  /**
@@ -488,6 +493,8 @@ var FetchBrainClient = class {
488
493
  this.warnedOversizeLearn = false;
489
494
  /** Warn about the learn cap once per pause, independent of the pause state. */
490
495
  this.learnCapWarnedUntil = 0;
496
+ /** Change counts, accumulated once per learn HTTP batch (never per learn() promise). */
497
+ this.changeStats = { changed: 0, unchanged: 0, firstSeen: 0, drift: [] };
491
498
  this.config = {
492
499
  apiKey: config.apiKey,
493
500
  baseUrl: config.baseUrl || DEFAULT_BASE_URL,
@@ -509,7 +516,9 @@ var FetchBrainClient = class {
509
516
  // enhance-only; stored so getConfig() round-trips
510
517
  onRecalled: config.onRecalled,
511
518
  // enhance-only; stored so getConfig() round-trips
512
- scraper: config.scraper
519
+ scraper: config.scraper,
520
+ changeDetection: config.changeDetection,
521
+ reportRuns: config.reportRuns ?? true
513
522
  };
514
523
  this.logger = createLogger(this.config.debug ? "debug" : "info", true);
515
524
  const scraper = resolveScraperName(config.scraper);
@@ -748,6 +757,8 @@ var FetchBrainClient = class {
748
757
  async executeBatchLearn(entries) {
749
758
  if (entries.length === 0) return { status: "rejected", learned: 0 };
750
759
  const request = { entries };
760
+ const ignore = this.config.changeDetection?.ignoreFields;
761
+ if (ignore && ignore.length > 0) request.ignore = ignore;
751
762
  const platformBuildId = getPlatformBuildId();
752
763
  if (this.config.refreshOnRebuild && platformBuildId) {
753
764
  request.build = platformBuildId;
@@ -762,6 +773,11 @@ var FetchBrainClient = class {
762
773
  DEFAULT_LEARN_TIMEOUT
763
774
  );
764
775
  this.circuitBreaker.recordSuccess();
776
+ try {
777
+ this.accumulateChanges(response);
778
+ } catch (statsErr) {
779
+ this.logger.debug("Change stats skipped:", statsErr);
780
+ }
765
781
  return response;
766
782
  } catch (error) {
767
783
  if (error instanceof ApiError && error.status >= 400 && error.status < 500) {
@@ -787,6 +803,54 @@ var FetchBrainClient = class {
787
803
  throw error;
788
804
  }
789
805
  }
806
+ /** Fold one batch response into the change totals (called once per HTTP batch). */
807
+ accumulateChanges(response) {
808
+ const stats = this.changeStats;
809
+ const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : 0;
810
+ stats.changed += num(response.changed);
811
+ stats.unchanged += num(response.unchanged);
812
+ stats.firstSeen += num(response.firstSeen);
813
+ const drift = Array.isArray(response.drift) ? response.drift : [];
814
+ for (const item of drift) {
815
+ if (!item || typeof item !== "object" || typeof item.label !== "string" || typeof item.field !== "string" || !DRIFT_KINDS.has(item.kind)) {
816
+ continue;
817
+ }
818
+ if (stats.drift.length >= MAX_DRIFT_ITEMS) break;
819
+ const clean = {
820
+ ...item,
821
+ label: clipText(item.label),
822
+ field: clipText(item.field)
823
+ };
824
+ const exists = stats.drift.some(
825
+ (d) => d.label === clean.label && d.field === clean.field && d.kind === clean.kind
826
+ );
827
+ if (!exists) stats.drift.push(clean);
828
+ }
829
+ }
830
+ /** Change counts so far (a copy). */
831
+ getChangeStats() {
832
+ return { ...this.changeStats, drift: [...this.changeStats.drift] };
833
+ }
834
+ /**
835
+ * Send the end-of-run report. Counts and labels only. Never throws: on
836
+ * failure or timeout it returns no flags.
837
+ */
838
+ async reportRun(report, timeoutMs = REPORT_RUN_TIMEOUT) {
839
+ if (this.config.reportRuns === false || this.recallBlocked()) return [];
840
+ try {
841
+ const response = await this.makeRequest(
842
+ "/v1/runs",
843
+ { method: "POST", body: JSON.stringify(report) },
844
+ Math.min(timeoutMs, REPORT_RUN_TIMEOUT)
845
+ );
846
+ this.circuitBreaker.recordSuccess();
847
+ return Array.isArray(response?.flags) ? response.flags : [];
848
+ } catch (error) {
849
+ if (isOutage(error)) this.circuitBreaker.recordFailure();
850
+ this.logger.debug("Run report failed:", error);
851
+ return [];
852
+ }
853
+ }
790
854
  /**
791
855
  * Make an HTTP request to the API
792
856
  */
@@ -1062,6 +1126,40 @@ var TelemetryBuffer = class {
1062
1126
  };
1063
1127
 
1064
1128
  // src/enhance.ts
1129
+ var REPORT_MAX_LABELS = 50;
1130
+ var REPORT_LABEL_MAX_CHARS = 64;
1131
+ var RUN_ID_MAX_CHARS = 128;
1132
+ var NO_LABEL = "_nolabel";
1133
+ var platformRunSeq = /* @__PURE__ */ new Map();
1134
+ function nextRunId() {
1135
+ const platform = process.env.APIFY_ACTOR_RUN_ID;
1136
+ if (!platform) return crypto$1.randomUUID();
1137
+ const id = platform.slice(0, RUN_ID_MAX_CHARS - 8);
1138
+ const n = (platformRunSeq.get(id) ?? 0) + 1;
1139
+ platformRunSeq.set(id, n);
1140
+ return n === 1 ? id : `${id}-${n}`;
1141
+ }
1142
+ function labelText(label) {
1143
+ if (typeof label === "string") return label;
1144
+ if (typeof label === "number" || typeof label === "boolean") return String(label);
1145
+ return void 0;
1146
+ }
1147
+ function reportLabel(label) {
1148
+ const trimmed = (labelText(label) ?? "").trim().slice(0, REPORT_LABEL_MAX_CHARS);
1149
+ return trimmed || NO_LABEL;
1150
+ }
1151
+ var pct = (rate) => `${Math.round(rate * 100)}%`;
1152
+ function describeDrift(d) {
1153
+ const detail = d.kind === "type_changed" ? `type ${clipText(d.from, 32)} \u2192 ${clipText(d.to, 32)}` : `filled ${pct(Number(d.from))} \u2192 ${pct(Number(d.to))}`;
1154
+ return `\u26A0\uFE0F drift [${clipText(d.label, 64)}] ${clipText(d.field, 64)}: ${detail}`;
1155
+ }
1156
+ function safeChangeStats(client) {
1157
+ try {
1158
+ return client.getChangeStats();
1159
+ } catch {
1160
+ return { changed: 0, unchanged: 0, firstSeen: 0, drift: [] };
1161
+ }
1162
+ }
1065
1163
  var STRIP_HEADERS = /* @__PURE__ */ new Set(["authorization", "cookie", "set-cookie"]);
1066
1164
  var SDK_USERDATA_KEYS = /* @__PURE__ */ new Set(["fetchBrainRecalled", "fetchBrainData", "__fetchBrainResult"]);
1067
1165
  var MAX_STASH_ENTRIES = 5e3;
@@ -1075,6 +1173,13 @@ function isIterableInputRejection(err) {
1075
1173
  const message = err instanceof Error ? err.message : String(err);
1076
1174
  return /iterable|\barray\b/i.test(message);
1077
1175
  }
1176
+ function resolveHandlerKey(crawler) {
1177
+ const c = crawler;
1178
+ for (const key of ["userProvidedRequestHandler", "requestHandler", "userDefinedRequestHandler"]) {
1179
+ if (typeof c[key] === "function") return key;
1180
+ }
1181
+ return null;
1182
+ }
1078
1183
  function buildRawRequest(request) {
1079
1184
  const r = request;
1080
1185
  let headers;
@@ -1093,7 +1198,7 @@ function buildRawRequest(request) {
1093
1198
  }
1094
1199
  let body;
1095
1200
  if (typeof r.payload === "string") body = r.payload;
1096
- return { url: r.url, method: r.method, uniqueKey: r.uniqueKey, body, headers, userData, label: r.label };
1201
+ return { url: r.url, method: r.method, uniqueKey: r.uniqueKey, body, headers, userData, label: labelText(r.label) };
1097
1202
  }
1098
1203
  function warnDefaultUniqueKey(request, logger, warned) {
1099
1204
  const method = (request.method ?? "GET").toUpperCase();
@@ -1184,8 +1289,27 @@ var FetchBrain = class {
1184
1289
  // enqueue-time fetch skipped, but remembered data gone by execution
1185
1290
  startTime: 0
1186
1291
  };
1292
+ const labelStats = /* @__PURE__ */ new Map();
1293
+ const labelCounts = (label) => {
1294
+ const key = reportLabel(label);
1295
+ let counts = labelStats.get(key);
1296
+ if (!counts && labelStats.size < REPORT_MAX_LABELS) {
1297
+ counts = { scraped: 0, empty: 0, failed: 0 };
1298
+ labelStats.set(key, counts);
1299
+ } else if (!counts) {
1300
+ logger.debug(`Run report: more than ${REPORT_MAX_LABELS} labels; not tracking "${key}"`);
1301
+ }
1302
+ return counts;
1303
+ };
1187
1304
  const pendingLearns = /* @__PURE__ */ new Set();
1188
- const originalHandler = crawler.requestHandler || crawler.userDefinedRequestHandler;
1305
+ if ("adaptiveRequestHandler" in crawler) {
1306
+ logger.warn(
1307
+ "AdaptivePlaywrightCrawler is not supported yet \u2014 FetchBrain left this crawler unmodified"
1308
+ );
1309
+ return Object.assign(crawler, { fetchBrain: client });
1310
+ }
1311
+ const handlerKey = resolveHandlerKey(crawler);
1312
+ const originalHandler = handlerKey ? crawler[handlerKey] : void 0;
1189
1313
  if (!originalHandler) {
1190
1314
  logger.warn("No request handler found on crawler, returning unmodified");
1191
1315
  return Object.assign(crawler, { fetchBrain: client });
@@ -1275,6 +1399,7 @@ var FetchBrain = class {
1275
1399
  );
1276
1400
  }
1277
1401
  let usedAIData = false;
1402
+ const relearn = aiResult.known && config.changeDetection?.enabled === true;
1278
1403
  const originalPushData = context.pushData;
1279
1404
  const fireOnRecalled = async (data) => {
1280
1405
  if (!config.onRecalled) return;
@@ -1319,6 +1444,8 @@ var FetchBrain = class {
1319
1444
  return;
1320
1445
  }
1321
1446
  runStats.scraped++;
1447
+ const counts = labelCounts(request.label);
1448
+ if (counts) counts.scraped++;
1322
1449
  if (aiResult.known) {
1323
1450
  runStats.recalled++;
1324
1451
  logger.info(
@@ -1330,7 +1457,7 @@ var FetchBrain = class {
1330
1457
  const learnItems = [];
1331
1458
  if (originalPushData && config.learning !== false) {
1332
1459
  context.pushData = async (data) => {
1333
- if (!usedAIData && !aiResult.known) {
1460
+ if (!usedAIData && (!aiResult.known || relearn)) {
1334
1461
  learnItems.push(...Array.isArray(data) ? data : [data]);
1335
1462
  }
1336
1463
  return originalPushData.call(context, data);
@@ -1341,12 +1468,21 @@ var FetchBrain = class {
1341
1468
  client,
1342
1469
  learning: config.learning !== false,
1343
1470
  aiKnown: aiResult.known,
1471
+ relearn,
1344
1472
  items: learnItems
1345
1473
  };
1346
- await asyncContext.run(requestContext, async () => {
1347
- await originalHandler.call(crawler, context);
1348
- });
1349
- if (learnItems.length > 0 && !usedAIData && !aiResult.known) {
1474
+ try {
1475
+ await asyncContext.run(requestContext, async () => {
1476
+ await originalHandler.call(crawler, context);
1477
+ });
1478
+ } catch (handlerErr) {
1479
+ if (counts) counts.failed++;
1480
+ throw handlerErr;
1481
+ }
1482
+ if (counts && learnItems.length === 0 && originalPushData && config.learning !== false && !usedAIData && (!aiResult.known || relearn)) {
1483
+ counts.empty++;
1484
+ }
1485
+ if (learnItems.length > 0 && !usedAIData && (!aiResult.known || relearn)) {
1350
1486
  await client.waitForLearnRoom(LEARN_ROOM_WAIT_MS);
1351
1487
  const pending = client.learn(rawRequest, learnItems.length === 1 ? learnItems[0] : learnItems).then((res) => {
1352
1488
  if (res.status !== "rejected") runStats.learned += learnItems.length;
@@ -1432,16 +1568,17 @@ var FetchBrain = class {
1432
1568
  }
1433
1569
  };
1434
1570
  const crawlerAny = crawler;
1435
- if ("requestHandler" in crawlerAny) {
1436
- crawlerAny.requestHandler = wrappedHandler;
1437
- }
1438
- if ("userDefinedRequestHandler" in crawlerAny) {
1439
- crawlerAny.userDefinedRequestHandler = wrappedHandler;
1440
- }
1571
+ crawlerAny[handlerKey] = wrappedHandler;
1572
+ logger.debug(`Wrapped ${handlerKey}`);
1441
1573
  if (typeof crawlerAny.run === "function") {
1442
1574
  const originalRun = crawlerAny.run.bind(crawlerAny);
1443
1575
  crawlerAny.run = async (...args) => {
1444
1576
  runStats.startTime = Date.now();
1577
+ const runStartedAt = new Date(runStats.startTime).toISOString();
1578
+ labelStats.clear();
1579
+ const runBase = { scraped: runStats.scraped, learned: runStats.learned, recalled: runStats.recalled };
1580
+ const changeBase = safeChangeStats(client);
1581
+ const runId = nextRunId();
1445
1582
  try {
1446
1583
  const result = await originalRun(...args);
1447
1584
  return result;
@@ -1458,9 +1595,55 @@ var FetchBrain = class {
1458
1595
  );
1459
1596
  const managedRequests = runStats.totalRequests - runStats.bypassed;
1460
1597
  const savingsPercent = managedRequests > 0 ? (runStats.aiSkipped / managedRequests * 100).toFixed(1) : "0";
1598
+ let changes = { changed: 0, drift: [] };
1599
+ try {
1600
+ const now = safeChangeStats(client);
1601
+ const key = (d) => `${d.label}\0${d.field}\0${d.kind}`;
1602
+ const seen = new Set(changeBase.drift.map(key));
1603
+ changes = {
1604
+ changed: Math.max(0, now.changed - changeBase.changed) || 0,
1605
+ drift: now.drift.filter((d) => !seen.has(key(d)))
1606
+ };
1607
+ } catch (diffErr) {
1608
+ logger.debug(`Change summary skipped: ${diffErr}`);
1609
+ }
1610
+ const showChanged = config.changeDetection?.enabled === true || changes.changed > 0;
1461
1611
  logger.info(
1462
- `\u{1F9E0} Finished! recalled: ${runStats.recalled}/${managedRequests} (${savingsPercent}%), learned: ${runStats.learned}, scraped: ${runStats.scraped}` + (skipLabels ? `, bypassed: ${runStats.bypassed}` : "") + (runStats.dropped ? `, dropped: ${runStats.dropped}` : "") + `, duration: ${duration}s`
1612
+ `\u{1F9E0} Finished! recalled: ${runStats.recalled}/${managedRequests} (${savingsPercent}%), learned: ${runStats.learned}, scraped: ${runStats.scraped}` + (skipLabels ? `, bypassed: ${runStats.bypassed}` : "") + (runStats.dropped ? `, dropped: ${runStats.dropped}` : "") + (showChanged ? `, changed: ${changes.changed}` : "") + `, duration: ${duration}s`
1463
1613
  );
1614
+ for (const item of changes.drift) {
1615
+ try {
1616
+ logger.warn(describeDrift(item));
1617
+ } catch (warnErr) {
1618
+ logger.debug(`Drift warning skipped: ${warnErr}`);
1619
+ }
1620
+ }
1621
+ if (config.reportRuns !== false) {
1622
+ try {
1623
+ const labels = Object.fromEntries(labelStats);
1624
+ const flags = await client.reportRun({
1625
+ runId,
1626
+ build: config.refreshOnRebuild ? getPlatformBuildId() : void 0,
1627
+ startedAt: runStartedAt,
1628
+ endedAt: (/* @__PURE__ */ new Date()).toISOString(),
1629
+ scraped: runStats.scraped - runBase.scraped,
1630
+ learned: runStats.learned - runBase.learned,
1631
+ recalled: runStats.recalled - runBase.recalled,
1632
+ labels
1633
+ });
1634
+ for (const flag of Array.isArray(flags) ? flags : []) {
1635
+ if (!flag || flag.kind !== "failed_pages" && flag.kind !== "empty_pages" || typeof flag.rate !== "number" || !Number.isFinite(flag.rate)) {
1636
+ continue;
1637
+ }
1638
+ const label = clipText(flag.label, 64);
1639
+ logger.warn(
1640
+ flag.kind === "failed_pages" ? `\u26A0\uFE0F ${pct(flag.rate)} of ${label} pages failed` : `\u26A0\uFE0F ${pct(flag.rate)} of ${label} pages pushed no data`
1641
+ );
1642
+ }
1643
+ } catch (reportErr) {
1644
+ logger.debug(`Run report skipped: ${reportErr}`);
1645
+ }
1646
+ }
1464
1647
  }
1465
1648
  };
1466
1649
  }
@@ -1583,7 +1766,7 @@ function createFetchBrain(config) {
1583
1766
  }
1584
1767
  async function pushData(data, dataset, datasetName) {
1585
1768
  const ctx = getCurrentContext();
1586
- if (ctx && ctx.learning && !ctx.aiKnown) {
1769
+ if (ctx && ctx.learning && (!ctx.aiKnown || ctx.relearn)) {
1587
1770
  ctx.items.push(...Array.isArray(data) ? data : [data]);
1588
1771
  }
1589
1772
  if (datasetName && dataset.open) {