@fetchbrain.com/sdk 0.11.0 → 0.12.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/dist/index.js CHANGED
@@ -1,9 +1,1095 @@
1
1
  'use strict';
2
2
 
3
+ var crypto = require('crypto');
4
+ var util = require('util');
5
+ var zlib = require('zlib');
3
6
  var async_hooks = require('async_hooks');
4
- var crypto$1 = require('crypto');
5
7
 
6
- // src/enhance.ts
8
+ var __defProp = Object.defineProperty;
9
+ var __getOwnPropNames = Object.getOwnPropertyNames;
10
+ var __esm = (fn, res) => function __init() {
11
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
12
+ };
13
+ var __export = (target, all) => {
14
+ for (var name in all)
15
+ __defProp(target, name, { get: all[name], enumerable: true });
16
+ };
17
+
18
+ // src/analytics/block.ts
19
+ function detectBlockType(statusCode, errorMessage) {
20
+ if (!errorMessage) return void 0;
21
+ const msg = errorMessage?.toLowerCase() || "";
22
+ if (msg.includes("captcha")) return "captcha";
23
+ if (msg.includes("timeout")) return "timeout";
24
+ if (msg.includes("blocked")) return "blocked";
25
+ if (msg.includes("rate limit")) return "429";
26
+ return void 0;
27
+ }
28
+ var init_block = __esm({
29
+ "src/analytics/block.ts"() {
30
+ }
31
+ });
32
+
33
+ // src/analytics/url.ts
34
+ function keepSegment(raw) {
35
+ if (raw === "") return true;
36
+ if (raw.includes("%")) return false;
37
+ if (WORD.test(raw) || FILE.test(raw)) return true;
38
+ return raw.length <= 24 && TWO_WORDS.test(raw);
39
+ }
40
+ function generalizeUrlPath(url) {
41
+ try {
42
+ const path = new URL(url).pathname;
43
+ return path.split("/").map((s) => keepSegment(s) ? s : "*").join("/");
44
+ } catch {
45
+ return "/*";
46
+ }
47
+ }
48
+ var WORD, TWO_WORDS, FILE;
49
+ var init_url = __esm({
50
+ "src/analytics/url.ts"() {
51
+ WORD = /^[A-Za-z]{1,19}$/;
52
+ TWO_WORDS = /^[A-Za-z]+[-_][A-Za-z]+$/;
53
+ FILE = /^[A-Za-z]{1,19}\.(?:html?|php|aspx?|jsp|xml|json|txt)$/i;
54
+ }
55
+ });
56
+ function isPlainObject(v) {
57
+ return typeof v === "object" && v !== null && !Array.isArray(v);
58
+ }
59
+ function sanitizeContext(raw) {
60
+ if (!isPlainObject(raw)) return void 0;
61
+ try {
62
+ const out = {};
63
+ let n = 0;
64
+ let scanned = 0;
65
+ for (const key of Object.keys(raw)) {
66
+ if (n >= MAX_CONTEXT_KEYS || scanned++ >= MAX_CONTEXT_SCAN) break;
67
+ if (!KEY_RE.test(key)) continue;
68
+ const v = raw[key];
69
+ if (typeof v === "string") out[key] = v.slice(0, MAX_CONTEXT_VALUE);
70
+ else if (typeof v === "number" && Number.isFinite(v)) out[key] = v;
71
+ else continue;
72
+ n++;
73
+ }
74
+ return n > 0 ? out : void 0;
75
+ } catch {
76
+ return void 0;
77
+ }
78
+ }
79
+ function cleanValue(v) {
80
+ if (typeof v === "string") return v.slice(0, MAX_CUSTOM_STRING);
81
+ if (typeof v === "number") return Number.isFinite(v) ? v : void 0;
82
+ if (typeof v === "boolean") return v;
83
+ return void 0;
84
+ }
85
+ function sanitizeCustom(name, props) {
86
+ if (typeof name !== "string" || name.length === 0 || name.length > MAX_NAME) return null;
87
+ if (name.startsWith("~") || FIXED_EVENTS.has(name)) return null;
88
+ try {
89
+ const src = isPlainObject(props) ? props : {};
90
+ const out = {};
91
+ if (name.startsWith("antibot.")) {
92
+ if (!Object.prototype.hasOwnProperty.call(RESERVED_EVENTS, name)) return null;
93
+ const schema = RESERVED_EVENTS[name];
94
+ for (const [key, spec] of Object.entries(schema)) {
95
+ const raw = src[key];
96
+ if (raw === void 0 || raw === null) {
97
+ if (spec.required) return null;
98
+ continue;
99
+ }
100
+ if (typeof raw !== spec.type) return null;
101
+ const v = cleanValue(raw);
102
+ if (v === void 0) return null;
103
+ out[key] = v;
104
+ }
105
+ return { name, props: out };
106
+ }
107
+ let n = 0;
108
+ for (const key of Object.keys(src)) {
109
+ if (n >= MAX_CUSTOM_PROPS) break;
110
+ if (!KEY_RE.test(key)) continue;
111
+ const v = cleanValue(src[key]);
112
+ if (v === void 0) continue;
113
+ out[key] = v;
114
+ n++;
115
+ }
116
+ return { name, props: out };
117
+ } catch {
118
+ return null;
119
+ }
120
+ }
121
+ function hashClient(apifyUserId, salt) {
122
+ return crypto.createHmac("sha256", salt).update(apifyUserId).digest("hex").slice(0, 16);
123
+ }
124
+ var MAX_CONTEXT_KEYS, MAX_CONTEXT_VALUE, MAX_CONTEXT_SCAN, MAX_CUSTOM_PROPS, MAX_CUSTOM_STRING, MAX_NAME, KEY_RE, OVERFLOW_KEY, FIXED_EVENTS, RESERVED_EVENTS;
125
+ var init_events = __esm({
126
+ "src/analytics/events.ts"() {
127
+ MAX_CONTEXT_KEYS = 3;
128
+ MAX_CONTEXT_VALUE = 64;
129
+ MAX_CONTEXT_SCAN = 32;
130
+ MAX_CUSTOM_PROPS = 10;
131
+ MAX_CUSTOM_STRING = 200;
132
+ MAX_NAME = 64;
133
+ KEY_RE = /^[A-Za-z0-9_.-]{1,40}$/;
134
+ OVERFLOW_KEY = "~other";
135
+ FIXED_EVENTS = /* @__PURE__ */ new Set([
136
+ "run_started",
137
+ "run_finished",
138
+ "request",
139
+ "enqueued",
140
+ "record_pushed",
141
+ "error",
142
+ "quota_reached"
143
+ ]);
144
+ RESERVED_EVENTS = {
145
+ "antibot.challenge": { protection: { type: "string", required: true }, kind: { type: "string" } },
146
+ "antibot.solve": {
147
+ provider: { type: "string", required: true },
148
+ type: { type: "string" },
149
+ ms: { type: "number", required: true },
150
+ cost: { type: "number" },
151
+ ok: { type: "boolean", required: true }
152
+ },
153
+ "antibot.token_end": { reason: { type: "string", required: true }, requests: { type: "number" } }
154
+ };
155
+ }
156
+ });
157
+ function isSecretRun(run) {
158
+ if (/[\d+=]/.test(run)) return true;
159
+ if (run.length >= 32) return true;
160
+ const uppers = run.match(UPPER_RE)?.length ?? 0;
161
+ return uppers >= 2 && uppers * 4 > run.length;
162
+ }
163
+ function scrubMessage(msg) {
164
+ return String(msg ?? "").slice(0, MAX_MESSAGE * 4).replace(AUTHORITY_RE, "<url>").replace(URL_RE, "<url>").replace(KEY_RE2, "<secret>").replace(JWT_RE, "<secret>").replace(KEYWORD_SECRET_RE, "<secret>").replace(EMAIL_RE, "<email>").replace(UUID_RE, "<uuid>").replace(IP_RE, "<ip>").replace(IP6_RE, "<ip>").replace(HOST_RE, (m, tld, path) => FILE_EXT.has(tld.toLowerCase()) ? m : path ? "<url>" : "<host>").replace(LONG_SECRET_RE, (m) => isSecretRun(m) ? "<secret>" : m).replace(STR_RE, "<str>").replace(PATH_RE, "<path>").replace(REL_PATH_RE, "<path>").replace(NUM_RE, "<n>").slice(0, MAX_MESSAGE);
165
+ }
166
+ function topProjectFrame(stack) {
167
+ if (!stack) return void 0;
168
+ for (const line of stack.split("\n")) {
169
+ const m = FRAME_RE.exec(line);
170
+ if (!m) continue;
171
+ const loc = m[2];
172
+ if (loc.includes("node_modules") || loc.startsWith("node:") || loc.startsWith("internal/")) continue;
173
+ const file = loc.split(/[\\/]/).pop() || loc;
174
+ const fn = (m[1] ?? "").replace(/^(?:async|new)\s+/, "").trim();
175
+ return `${file}:${fn || "<anonymous>"}`;
176
+ }
177
+ return void 0;
178
+ }
179
+ function fingerprint(errorClass, scrubbed, frame) {
180
+ return crypto.createHash("sha256").update(`${errorClass}
181
+ ${scrubbed}
182
+ ${frame ?? ""}`).digest("hex").slice(0, 16);
183
+ }
184
+ var MAX_MESSAGE, AUTHORITY_RE, URL_RE, KEY_RE2, KEYWORD_SECRET_RE, JWT_RE, LONG_SECRET_RE, UPPER_RE, EMAIL_RE, UUID_RE, IP_RE, IP6_RE, HOST_RE, FILE_EXT, STR_RE, PATH_RE, REL_PATH_RE, NUM_RE, FRAME_RE;
185
+ var init_scrub = __esm({
186
+ "src/analytics/scrub.ts"() {
187
+ MAX_MESSAGE = 500;
188
+ AUTHORITY_RE = /(?<![\w.])[\w.~%+-]+:[^\s"'<>]*@[\w.-]+(?::\d{1,5})?/g;
189
+ URL_RE = /\b[a-z][a-z0-9+.-]*:\/\/[^\s"'<>)]+/gi;
190
+ KEY_RE2 = /\b(?:apify_api_|sk_live_|sk_test_|gh[pousr]_|xox[baprs]-|fb_[A-Za-z]+_)[A-Za-z0-9_-]{8,}/g;
191
+ KEYWORD_SECRET_RE = /\b(?:(?:bearer|basic|token|api[-_]?key|authorization|auth|password|passwd|pwd|secret|set-cookie|cookie|sessionid|session)(?![A-Za-z])(?:\s*[:=]|\s)\s*)+\S+/gi;
192
+ JWT_RE = /\beyJ[\w-]*\.[\w-]+(?:\.[\w-]*)?/g;
193
+ LONG_SECRET_RE = /(?<![\w+/=-])[A-Za-z0-9_+/-]{20,}={0,2}(?![\w+/=-])/g;
194
+ UPPER_RE = /[A-Z]/g;
195
+ EMAIL_RE = /[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g;
196
+ UUID_RE = /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi;
197
+ IP_RE = /\b\d{1,3}(?:\.\d{1,3}){3}(?::\d{1,5})?(?!\d)/g;
198
+ IP6_RE = /(?<![\w:])(?:(?:[0-9a-f]{1,4}:){7}[0-9a-f]{1,4}|(?:[0-9a-f]{1,4}:){1,6}:[0-9a-f]{1,4}(?::[0-9a-f]{1,4}){0,5}|::[0-9a-f]{1,4})(?![\w:])/gi;
199
+ HOST_RE = /(?<![\w@.-])(?:[a-z0-9-]+\.)+([a-z]{2,24})(?::\d{1,5})?(?![\w-])(\/[^\s"'<>)]*)?/gi;
200
+ FILE_EXT = new Set(
201
+ "ts js mjs cjs json py md lock txt html css yml yaml map tsx jsx log sh toml env".split(" ")
202
+ );
203
+ STR_RE = /"[^"\n]*"|`[^`\n]*`|(?<![\w])'[^'\n]*'(?![\w])/g;
204
+ PATH_RE = /(?<![\w<>.])(?:[A-Za-z]:)?(?:[\\/][\w.@~+-]+){2,}[\\/]?/g;
205
+ REL_PATH_RE = /(?<![\w<>.:/\\-])(?:\.{1,2}[\\/][\w.@~+-]+(?:[\\/][\w.@~+-]+)*|[\w@~+-]+(?:[\\/][\w.@~+-]+){2,}|[\w@~+-]+[\\/][\w@~+-]+\.\w{1,5})/g;
206
+ NUM_RE = /(?<![A-Za-z_<])\d+(?:\.\d+)?/g;
207
+ FRAME_RE = /^\s*at\s+(?:(.*?)\s+\()?(.*?):\d+(?::\d+)?\)?\s*$/;
208
+ }
209
+ });
210
+
211
+ // src/analytics/aggregates.ts
212
+ function bucketOf(ms) {
213
+ if (!(ms > 1)) return 0;
214
+ const k = Math.ceil(Math.log(ms) / LOG_R);
215
+ return k >= BUCKETS ? BUCKETS - 1 : k;
216
+ }
217
+ function percentile(h, total, p) {
218
+ if (total === 0) return void 0;
219
+ const rank = Math.ceil(total * p);
220
+ let seen = 0;
221
+ for (let k = 0; k < BUCKETS; k++) {
222
+ seen += h[k];
223
+ if (seen >= rank) return k === 0 ? 1 : Math.round(Math.exp((k - 0.5) * LOG_R));
224
+ }
225
+ return MAX_MS;
226
+ }
227
+ function newPattern(label) {
228
+ return { label, requests: 0, scraped: 0, blocked: 0, failed: 0, nav: new Uint32Array(BUCKETS), navN: 0 };
229
+ }
230
+ function toStats(p) {
231
+ const out = {
232
+ label: p.label,
233
+ requests: p.requests,
234
+ scraped: p.scraped,
235
+ blocked: p.blocked,
236
+ failed: p.failed
237
+ };
238
+ const navP95 = percentile(p.nav, p.navN, 0.95);
239
+ if (navP95 !== void 0) out.navP95 = navP95;
240
+ return out;
241
+ }
242
+ function customReport(c) {
243
+ const props = {};
244
+ for (const [k, p] of c.props) {
245
+ if (p.kind === "s") props[k] = p.other > 0 ? { kind: "s", top: Object.fromEntries(p.top), other: p.other } : { kind: "s", top: Object.fromEntries(p.top) };
246
+ else if (p.kind === "n") props[k] = p.min > p.max ? { kind: "n", sum: 0, min: 0, max: 0 } : { ...p };
247
+ else props[k] = { ...p };
248
+ }
249
+ return { count: c.count, labels: Object.fromEntries(c.labels), props };
250
+ }
251
+ var BUCKETS, MAX_MS, LOG_R, REPORT_PATTERNS, MAX_LIVE_PATTERNS, MAX_NAMES, MAX_PROPS, MAX_TOP, MAX_LABELS_PER_NAME, newCustom, Aggregates;
252
+ var init_aggregates = __esm({
253
+ "src/analytics/aggregates.ts"() {
254
+ init_events();
255
+ BUCKETS = 32;
256
+ MAX_MS = 12e4;
257
+ LOG_R = Math.log(MAX_MS) / (BUCKETS - 1);
258
+ REPORT_PATTERNS = 50;
259
+ MAX_LIVE_PATTERNS = 300;
260
+ MAX_NAMES = 50;
261
+ MAX_PROPS = 10;
262
+ MAX_TOP = 20;
263
+ MAX_LABELS_PER_NAME = 50;
264
+ newCustom = () => ({ count: 0, labels: /* @__PURE__ */ new Map(), props: /* @__PURE__ */ new Map() });
265
+ Aggregates = class {
266
+ constructor() {
267
+ this.patterns = /* @__PURE__ */ new Map();
268
+ this.custom_ = /* @__PURE__ */ new Map();
269
+ }
270
+ /** One real request at its final outcome (weight 1). O(1). */
271
+ request(label, urlPattern, outcome, navMs) {
272
+ let p = this.patterns.get(urlPattern);
273
+ if (!p) {
274
+ if (this.patterns.size < MAX_LIVE_PATTERNS) {
275
+ p = newPattern(label);
276
+ this.patterns.set(urlPattern, p);
277
+ } else {
278
+ p = this.overflow ?? (this.overflow = newPattern(""));
279
+ }
280
+ }
281
+ p.requests++;
282
+ if (outcome === "scraped") p.scraped++;
283
+ else if (outcome === "blocked") p.blocked++;
284
+ else if (outcome === "failed") p.failed++;
285
+ if (typeof navMs === "number" && Number.isFinite(navMs)) {
286
+ p.nav[bucketOf(navMs)]++;
287
+ p.navN++;
288
+ }
289
+ }
290
+ /** A developer event (never antibot.*, never sampled). Props are already sanitized. */
291
+ custom(name, label, props, weight = 1) {
292
+ if (name.startsWith("antibot.")) return;
293
+ const w = typeof weight === "number" && Number.isFinite(weight) && weight > 0 ? weight : 1;
294
+ let c = this.custom_.get(name);
295
+ if (!c) {
296
+ if (this.custom_.size < MAX_NAMES) {
297
+ c = newCustom();
298
+ this.custom_.set(name, c);
299
+ } else {
300
+ c = this.otherName ?? (this.otherName = newCustom());
301
+ }
302
+ }
303
+ c.count += w;
304
+ const lk = c.labels.has(label) || c.labels.size < MAX_LABELS_PER_NAME ? label : OVERFLOW_KEY;
305
+ c.labels.set(lk, (c.labels.get(lk) ?? 0) + w);
306
+ for (const key of Object.keys(props)) {
307
+ const v = props[key];
308
+ let ps = c.props.get(key);
309
+ if (!ps) {
310
+ if (c.props.size >= MAX_PROPS) continue;
311
+ ps = typeof v === "string" ? { kind: "s", top: /* @__PURE__ */ new Map(), other: 0 } : typeof v === "number" ? { kind: "n", sum: 0, min: Infinity, max: -Infinity } : { kind: "b", true: 0, false: 0 };
312
+ c.props.set(key, ps);
313
+ }
314
+ if (ps.kind === "s" && typeof v === "string") {
315
+ if (ps.top.has(v) || ps.top.size < MAX_TOP) ps.top.set(v, (ps.top.get(v) ?? 0) + w);
316
+ else ps.other += w;
317
+ } else if (ps.kind === "n" && typeof v === "number" && Number.isFinite(v)) {
318
+ ps.sum += v * w;
319
+ if (v < ps.min) ps.min = v;
320
+ if (v > ps.max) ps.max = v;
321
+ } else if (ps.kind === "b" && typeof v === "boolean") {
322
+ if (v) ps.true += w;
323
+ else ps.false += w;
324
+ }
325
+ }
326
+ }
327
+ toReport() {
328
+ const patterns = {};
329
+ const ranked = [...this.patterns.entries()].sort((a, b) => b[1].requests - a[1].requests);
330
+ const keep = ranked.slice(0, REPORT_PATTERNS);
331
+ for (const [k, p] of keep) patterns[k] = toStats(p);
332
+ const rest = ranked.slice(REPORT_PATTERNS).map((e) => e[1]);
333
+ if (this.overflow) rest.push(this.overflow);
334
+ if (rest.length > 0) {
335
+ const o = newPattern("");
336
+ for (const p of rest) {
337
+ o.requests += p.requests;
338
+ o.scraped += p.scraped;
339
+ o.blocked += p.blocked;
340
+ o.failed += p.failed;
341
+ o.navN += p.navN;
342
+ for (let i = 0; i < BUCKETS; i++) o.nav[i] += p.nav[i];
343
+ }
344
+ patterns[OVERFLOW_KEY] = toStats(o);
345
+ }
346
+ const custom = {};
347
+ for (const [n, c] of this.custom_) custom[n] = customReport(c);
348
+ if (this.otherName) custom[OVERFLOW_KEY] = customReport(this.otherName);
349
+ return { patterns, custom };
350
+ }
351
+ };
352
+ }
353
+ });
354
+ function startSeqFromEnv(env = process.env, now = Date.now()) {
355
+ try {
356
+ const raw = env.APIFY_STARTED_AT || env.ACTOR_STARTED_AT;
357
+ if (!raw) return 0;
358
+ const startedAt = Date.parse(raw);
359
+ if (!Number.isFinite(startedAt)) return 0;
360
+ const seq = Math.max(0, Math.floor((now - startedAt) / 1e3)) * 1e3;
361
+ return Number.isSafeInteger(seq) && seq < MAX_SEQ ? seq : 0;
362
+ } catch {
363
+ return 0;
364
+ }
365
+ }
366
+ var gzipAsync, MAX_BATCH_BYTES, EVENTS_MARK, EVENTS_MARK_JSON, eventsPlaceholder, MAX_SEQ, MAX_RATE_LIMITED_RESENDS, MAX_PAUSE_MS, BACKOFF_BASE_MS, BACKOFF_MAX_MS, AnalyticsQueue;
367
+ var init_queue = __esm({
368
+ "src/analytics/queue.ts"() {
369
+ gzipAsync = util.promisify(zlib.gzip);
370
+ MAX_BATCH_BYTES = 200 * 1024;
371
+ EVENTS_MARK = "\0fetchbrain-events\0";
372
+ EVENTS_MARK_JSON = JSON.stringify(EVENTS_MARK);
373
+ eventsPlaceholder = { toJSON: () => EVENTS_MARK };
374
+ MAX_SEQ = 1e12;
375
+ MAX_RATE_LIMITED_RESENDS = 30;
376
+ MAX_PAUSE_MS = 24 * 60 * 60 * 1e3;
377
+ BACKOFF_BASE_MS = 5e3;
378
+ BACKOFF_MAX_MS = 6e4;
379
+ AnalyticsQueue = class {
380
+ constructor(send, opts = {}) {
381
+ this.send = send;
382
+ this.dropped = 0;
383
+ this.sampleRate = 1;
384
+ /** The last batch was cut by size: keep sending instead of waiting for a full batch. */
385
+ this.cut = false;
386
+ // Absolute indexes: the oldest event is `startIdx`, the next write is `endIdx`.
387
+ this.startIdx = 0;
388
+ this.endIdx = 0;
389
+ this.generation = 0;
390
+ this.failures = 0;
391
+ this.notBefore = 0;
392
+ // backoff gate
393
+ this.pausedUntil = 0;
394
+ /** Extras that did not fit the previous batch (pathological label counts); at most maxBatch. */
395
+ this.carry = [];
396
+ const startSeq = opts.startSeq;
397
+ this.nextSeq = typeof startSeq === "number" && Number.isSafeInteger(startSeq) && startSeq >= 0 && startSeq < MAX_SEQ ? startSeq : 0;
398
+ this.maxBatch = opts.maxBatch ?? 250;
399
+ this.flushMs = opts.flushMs ?? 3e4;
400
+ this.capacity = opts.capacity ?? 1e4;
401
+ this.finalFlushTimeoutMs = opts.finalFlushTimeoutMs ?? 1800;
402
+ this.maxBatchAttempts = opts.maxBatchAttempts ?? 5;
403
+ this.maxBatchAgeMs = opts.maxBatchAgeMs ?? 6e5;
404
+ this.maxBatchBytes = opts.maxBatchBytes ?? MAX_BATCH_BYTES;
405
+ this.compress = opts.compress ?? ((j) => gzipAsync(j));
406
+ this.wrap = opts.wrap ?? ((events) => events);
407
+ this.ring = new Array(this.capacity);
408
+ }
409
+ /** Events currently buffered. */
410
+ get size() {
411
+ return this.endIdx - this.startIdx;
412
+ }
413
+ /** Hold every send until `until` (epoch ms), clamped to ≤24 h ahead, like a server pause. NaN is ignored. */
414
+ pause(until) {
415
+ if (typeof until !== "number" || Number.isNaN(until)) return;
416
+ this.pausedUntil = Math.max(this.pausedUntil, Math.min(until, Date.now() + MAX_PAUSE_MS));
417
+ }
418
+ setBeforeFlush(fn) {
419
+ this.beforeFlush = fn;
420
+ }
421
+ push(e) {
422
+ if (this.endIdx - this.startIdx >= this.capacity) {
423
+ this.ring[this.startIdx % this.capacity] = void 0;
424
+ this.startIdx++;
425
+ this.dropped++;
426
+ }
427
+ this.ring[this.endIdx % this.capacity] = e;
428
+ this.endIdx++;
429
+ if (this.endIdx - this.startIdx >= this.maxBatch && this.canKick()) this.kick();
430
+ }
431
+ start() {
432
+ if (this.timer) clearInterval(this.timer);
433
+ this.timer = setInterval(() => this.kick(), this.flushMs);
434
+ this.timer.unref();
435
+ }
436
+ async stop() {
437
+ if (this.timer) clearInterval(this.timer);
438
+ this.timer = void 0;
439
+ if (this.retryTimer) clearTimeout(this.retryTimer);
440
+ this.retryTimer = void 0;
441
+ let deadline;
442
+ const timeout = new Promise((resolve) => {
443
+ deadline = setTimeout(resolve, this.finalFlushTimeoutMs);
444
+ deadline.unref();
445
+ });
446
+ try {
447
+ await Promise.race([this.drain(), timeout]);
448
+ } catch {
449
+ } finally {
450
+ if (deadline) clearTimeout(deadline);
451
+ if (this.inflight) {
452
+ this.generation++;
453
+ this.abort?.abort();
454
+ if (this.current && !this.pending) this.pending = this.current;
455
+ this.current = void 0;
456
+ this.inflight = void 0;
457
+ }
458
+ }
459
+ }
460
+ /** Synchronous gate so a gated push() allocates nothing. */
461
+ canKick() {
462
+ if (this.inflight || !this.timer) return false;
463
+ const now = Date.now();
464
+ return now >= this.notBefore && now >= this.pausedUntil;
465
+ }
466
+ kick() {
467
+ void this.flush(false).catch(() => {
468
+ });
469
+ }
470
+ async drain() {
471
+ const gen = this.generation;
472
+ if (this.inflight) await this.inflight.catch(() => false);
473
+ if (gen !== this.generation) return;
474
+ await this.flush(true);
475
+ }
476
+ /** Send batches until the ring has less than a full batch (or, when final, is empty). */
477
+ async flush(final) {
478
+ if (this.inflight) return;
479
+ const gen = this.generation;
480
+ const run = (async () => {
481
+ let ok2 = true;
482
+ for (; ; ) {
483
+ if (gen !== this.generation) return false;
484
+ const now = Date.now();
485
+ if (now < this.pausedUntil) return ok2;
486
+ if (!final && now < this.notBefore) return ok2;
487
+ ok2 = await this.sendOne(gen);
488
+ if (!ok2 || gen !== this.generation) return false;
489
+ const left = this.size;
490
+ if (left === 0 && this.carry.length === 0) return true;
491
+ if (!final && left < this.maxBatch && this.carry.length === 0 && !this.cut) return true;
492
+ }
493
+ })();
494
+ this.inflight = run;
495
+ let ok = false;
496
+ try {
497
+ ok = await run;
498
+ } catch {
499
+ ok = false;
500
+ }
501
+ if (gen !== this.generation) return;
502
+ this.inflight = void 0;
503
+ if (!ok) this.scheduleRetry();
504
+ }
505
+ scheduleRetry() {
506
+ if (this.retryTimer) clearTimeout(this.retryTimer);
507
+ if (!this.timer) return;
508
+ const wait = Math.max(0, this.notBefore - Date.now(), this.pausedUntil - Date.now());
509
+ this.retryTimer = setTimeout(() => this.kick(), wait);
510
+ this.retryTimer.unref();
511
+ }
512
+ /** Build and send one batch. True on success or when there was nothing to send. */
513
+ async sendOne(gen) {
514
+ let job = this.pending;
515
+ if (!job) {
516
+ let extras = [];
517
+ try {
518
+ extras = this.beforeFlush?.() ?? [];
519
+ } catch {
520
+ extras = [];
521
+ }
522
+ if (this.carry.length > 0) {
523
+ extras = this.carry.concat(extras);
524
+ this.carry = [];
525
+ }
526
+ if (extras.length > this.maxBatch) {
527
+ this.setCarry(extras.slice(this.maxBatch));
528
+ extras = extras.slice(0, this.maxBatch);
529
+ }
530
+ const n = Math.min(this.size, this.maxBatch - extras.length);
531
+ if (n === 0 && extras.length === 0) return true;
532
+ const b0 = this.startIdx;
533
+ const batch = [];
534
+ for (let i = 0; i < n; i++) batch.push(this.ring[(b0 + i) % this.capacity]);
535
+ for (const e of extras) batch.push(e);
536
+ const seq = this.nextSeq;
537
+ let built;
538
+ try {
539
+ built = this.serialize(batch, seq);
540
+ } catch {
541
+ this.dropped += batch.length;
542
+ this.consume(b0, n);
543
+ return true;
544
+ }
545
+ this.nextSeq++;
546
+ this.cut = built.k < batch.length;
547
+ if (built.k < n) {
548
+ this.setCarry(extras.concat(this.carry));
549
+ job = { seq, batch: batch.slice(0, built.k), b0, n: built.k, attempts: 0, limited: 0, firstAt: Date.now(), json: built.json };
550
+ } else {
551
+ if (built.k < batch.length) this.setCarry(extras.slice(built.k - n).concat(this.carry));
552
+ job = { seq, batch: batch.slice(0, built.k), b0, n, attempts: 0, limited: 0, firstAt: Date.now(), json: built.json };
553
+ }
554
+ }
555
+ this.current = job;
556
+ const ac = new AbortController();
557
+ this.abort = ac;
558
+ let gz;
559
+ try {
560
+ if (!job.gz) {
561
+ job.gz = await this.compress(job.json ?? JSON.stringify(this.wrap(job.batch, job.seq)));
562
+ job.json = void 0;
563
+ }
564
+ gz = job.gz;
565
+ } catch {
566
+ if (gen !== this.generation) return false;
567
+ this.dropped += job.batch.length;
568
+ this.current = void 0;
569
+ this.pending = void 0;
570
+ this.consume(job.b0, job.n);
571
+ return true;
572
+ }
573
+ if (gen !== this.generation) return false;
574
+ let result = null;
575
+ try {
576
+ result = await this.send(gz, ac.signal);
577
+ } catch {
578
+ result = null;
579
+ }
580
+ if (gen !== this.generation) return false;
581
+ this.current = void 0;
582
+ if (result === null) {
583
+ job.attempts++;
584
+ this.failures++;
585
+ const delay = Math.min(BACKOFF_BASE_MS * 2 ** (this.failures - 1), BACKOFF_MAX_MS);
586
+ this.notBefore = Date.now() + delay;
587
+ if (job.attempts >= this.maxBatchAttempts || Date.now() - job.firstAt >= this.maxBatchAgeMs) {
588
+ this.dropped += job.batch.length;
589
+ this.pending = void 0;
590
+ this.consume(job.b0, job.n);
591
+ } else {
592
+ this.pending = job;
593
+ }
594
+ return false;
595
+ }
596
+ if (result.retry) {
597
+ if (typeof result.pauseUntil === "number") this.pause(result.pauseUntil);
598
+ job.limited++;
599
+ if (job.limited >= MAX_RATE_LIMITED_RESENDS || Date.now() - job.firstAt >= this.maxBatchAgeMs) {
600
+ this.dropped += job.batch.length;
601
+ this.pending = void 0;
602
+ this.consume(job.b0, job.n);
603
+ } else {
604
+ this.pending = job;
605
+ }
606
+ return false;
607
+ }
608
+ this.failures = 0;
609
+ this.notBefore = 0;
610
+ if (typeof result.pauseUntil === "number") this.pause(result.pauseUntil);
611
+ if (result.drop) {
612
+ this.dropped += job.batch.length;
613
+ this.pending = void 0;
614
+ this.consume(job.b0, job.n);
615
+ return true;
616
+ }
617
+ if (typeof result.sampleRate === "number") this.sampleRate = result.sampleRate;
618
+ this.pending = void 0;
619
+ this.consume(job.b0, job.n);
620
+ return true;
621
+ }
622
+ /**
623
+ * The payload for the longest prefix of `batch` that fits maxBatchBytes (at least one event, so a
624
+ * lone oversized event can't stall the queue; the API refuses it and it is dropped). Each event is
625
+ * serialized once. Throws only if an event can't be serialized.
626
+ */
627
+ serialize(batch, seq) {
628
+ const envelope = JSON.stringify(this.wrap(eventsPlaceholder, seq));
629
+ const at = envelope.indexOf(EVENTS_MARK_JSON);
630
+ if (at < 0) return { json: JSON.stringify(this.wrap(batch, seq)), k: batch.length };
631
+ let bytes = Buffer.byteLength(envelope) - Buffer.byteLength(EVENTS_MARK_JSON) + 2;
632
+ const parts = [];
633
+ for (const e of batch) {
634
+ const part = JSON.stringify(e);
635
+ const b = Buffer.byteLength(part) + (parts.length > 0 ? 1 : 0);
636
+ if (parts.length > 0 && bytes + b > this.maxBatchBytes) break;
637
+ parts.push(part);
638
+ bytes += b;
639
+ }
640
+ const json = envelope.slice(0, at) + "[" + parts.join(",") + "]" + envelope.slice(at + EVENTS_MARK_JSON.length);
641
+ return { json, k: parts.length };
642
+ }
643
+ /** Extras waiting for a later batch, bounded to one batch (the oldest beyond it drop, counted). */
644
+ setCarry(events) {
645
+ const over = events.length - this.maxBatch;
646
+ if (over > 0) {
647
+ this.dropped += over;
648
+ events = events.slice(over);
649
+ }
650
+ this.carry = events;
651
+ }
652
+ consume(b0, n) {
653
+ const newStart = Math.max(this.startIdx, b0 + n);
654
+ for (let i = this.startIdx; i < newStart; i++) this.ring[i % this.capacity] = void 0;
655
+ this.startIdx = newStart;
656
+ }
657
+ };
658
+ }
659
+ });
660
+
661
+ // src/analytics/collector.ts
662
+ var collector_exports = {};
663
+ __export(collector_exports, {
664
+ AnalyticsQueue: () => AnalyticsQueue,
665
+ Collector: () => Collector,
666
+ SDK_VERSION: () => SDK_VERSION,
667
+ startSeqFromEnv: () => startSeqFromEnv
668
+ });
669
+ function errorClassOf(err) {
670
+ try {
671
+ if (err instanceof Error) {
672
+ const n = err.constructor?.name || err.name;
673
+ return typeof n === "string" && /^[\w$.]{1,64}$/.test(n) ? n : "Error";
674
+ }
675
+ return err === null ? "null" : typeof err;
676
+ } catch {
677
+ return "Error";
678
+ }
679
+ }
680
+ function rawMessageOf(err) {
681
+ try {
682
+ if (err instanceof Error) return typeof err.message === "string" ? err.message : String(err.message);
683
+ if (typeof err === "string") return err;
684
+ return String(err);
685
+ } catch {
686
+ return "";
687
+ }
688
+ }
689
+ function stackOf(err) {
690
+ try {
691
+ const s = err?.stack;
692
+ return typeof s === "string" ? s : void 0;
693
+ } catch {
694
+ return void 0;
695
+ }
696
+ }
697
+ function newLabelState() {
698
+ return {
699
+ stats: {
700
+ requests: 0,
701
+ scraped: 0,
702
+ recalled: 0,
703
+ skipped: 0,
704
+ bypassed: 0,
705
+ failed: 0,
706
+ blocked: 0,
707
+ blockedAttempts: 0,
708
+ retries: 0,
709
+ records: 0,
710
+ bytes: 0,
711
+ // Keyed by developer labels: no prototype, so "__proto__" is an ordinary key.
712
+ enqueued: /* @__PURE__ */ Object.create(null),
713
+ alreadyQueued: /* @__PURE__ */ Object.create(null),
714
+ status: {}
715
+ },
716
+ pendingRecords: 0,
717
+ nav: new Uint32Array(BUCKETS),
718
+ navN: 0,
719
+ handler: new Uint32Array(BUCKETS),
720
+ handlerN: 0
721
+ };
722
+ }
723
+ function domainOf(url) {
724
+ try {
725
+ return new URL(url).hostname;
726
+ } catch {
727
+ return "";
728
+ }
729
+ }
730
+ var SDK_VERSION, BLOCKED_STATUS, BLOCKED_MESSAGE_TYPES, MAX_LABELS, MAX_STATUS_CODES, MAX_CHILD_LABELS, SAMPLE_THRESHOLD, SLOTS, SLOT_MS, ROUTINE, MAX_FINGERPRINTS, MAX_RAW_KEYS, RAW_KEY_CHARS, OVERFLOW_FINGERPRINT, MAX_REJECTED_NAMES_LOGGED, hasOwn, isNum, RESERVED_PROPS, Collector;
731
+ var init_collector = __esm({
732
+ "src/analytics/collector.ts"() {
733
+ init_block();
734
+ init_url();
735
+ init_events();
736
+ init_scrub();
737
+ init_aggregates();
738
+ init_queue();
739
+ SDK_VERSION = "0.12.1" ;
740
+ BLOCKED_STATUS = /* @__PURE__ */ new Set([403, 429, 503]);
741
+ BLOCKED_MESSAGE_TYPES = /* @__PURE__ */ new Set(["captcha", "blocked", "429"]);
742
+ MAX_LABELS = 50;
743
+ MAX_STATUS_CODES = 20;
744
+ MAX_CHILD_LABELS = 50;
745
+ SAMPLE_THRESHOLD = 200;
746
+ SLOTS = 10;
747
+ SLOT_MS = 1e3;
748
+ ROUTINE = /* @__PURE__ */ new Set(["scraped", "recalled", "skipped"]);
749
+ MAX_FINGERPRINTS = 1e3;
750
+ MAX_RAW_KEYS = 2e3;
751
+ RAW_KEY_CHARS = 300;
752
+ OVERFLOW_FINGERPRINT = "overflow";
753
+ MAX_REJECTED_NAMES_LOGGED = 100;
754
+ hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
755
+ isNum = (v) => typeof v === "number" && Number.isFinite(v);
756
+ RESERVED_PROPS = /* @__PURE__ */ new Set([
757
+ "client",
758
+ "scraper",
759
+ "runId",
760
+ "seq",
761
+ "ts",
762
+ "label",
763
+ "crawlerType",
764
+ "sdkVersion",
765
+ "platform",
766
+ "weight",
767
+ "context"
768
+ ]);
769
+ Collector = class {
770
+ constructor(queue, base, opts = {}) {
771
+ this.queue = queue;
772
+ this.base = base;
773
+ this.seq = 0;
774
+ this.labels = /* @__PURE__ */ new Map();
775
+ this.aggregates = new Aggregates();
776
+ // Rate window state.
777
+ this.slots = new Uint32Array(SLOTS);
778
+ this.slotAbs = -1;
779
+ // absolute index (time / SLOT_MS) of the newest slot
780
+ this.windowSum = 0;
781
+ // Error grouping.
782
+ this.groups = /* @__PURE__ */ new Map();
783
+ this.rawKeys = /* @__PURE__ */ new Map();
784
+ // class+message+frame -> fingerprint
785
+ this.rejectedNames = /* @__PURE__ */ new Set();
786
+ const start = opts.startSeq;
787
+ if (typeof start === "number" && Number.isSafeInteger(start) && start > 0) this.seq = start;
788
+ this.now = opts.now ?? Date.now;
789
+ this.random = opts.random ?? Math.random;
790
+ this.debug = opts.debug ?? (() => {
791
+ });
792
+ queue.setBeforeFlush(() => this.drainRecords());
793
+ }
794
+ /** Validated `context` keys from the developer's callback result (≤3 keys, values ≤64 chars). */
795
+ sanitizeContext(raw) {
796
+ return sanitizeContext(raw);
797
+ }
798
+ /** Salted buyer hash; exposed here so enhance.ts never imports events.ts statically. */
799
+ static hashClient(apifyUserId, salt) {
800
+ return hashClient(apifyUserId, salt);
801
+ }
802
+ label(label) {
803
+ let s = this.labels.get(label);
804
+ if (s) return s;
805
+ const key = this.labels.size < MAX_LABELS ? label : OVERFLOW_KEY;
806
+ s = this.labels.get(key);
807
+ if (!s) {
808
+ s = newLabelState();
809
+ this.labels.set(key, s);
810
+ }
811
+ return s;
812
+ }
813
+ /** Base props, applied last so no caller field can overwrite them. */
814
+ props(label) {
815
+ return { ...this.base, seq: this.seq++, ts: Date.now(), label };
816
+ }
817
+ /**
818
+ * Block type of a failed attempt, or undefined when it was not blocked. Blocked =
819
+ * status 403/429/503 or a captcha/blocked/rate-limit message; 404, 500, timeouts
820
+ * and plain handler errors are failures, not blocks.
821
+ */
822
+ blockType(statusCode, message) {
823
+ if (statusCode !== void 0 && BLOCKED_STATUS.has(statusCode)) return String(statusCode);
824
+ const byMsg = message ? detectBlockType(void 0, message) : void 0;
825
+ return byMsg !== void 0 && BLOCKED_MESSAGE_TYPES.has(byMsg) ? byMsg : void 0;
826
+ }
827
+ request(p) {
828
+ const s = this.label(p.label);
829
+ const st = s.stats;
830
+ st.requests++;
831
+ st[p.outcome]++;
832
+ st.retries += p.retries;
833
+ const blockedAttempts = p.blockedAttempts ?? 0;
834
+ st.blockedAttempts += blockedAttempts;
835
+ if (isNum(p.bytes)) st.bytes += p.bytes;
836
+ if (isNum(p.navMs)) {
837
+ s.nav[bucketOf(p.navMs)]++;
838
+ s.navN++;
839
+ }
840
+ if (isNum(p.handlerMs)) {
841
+ s.handler[bucketOf(p.handlerMs)]++;
842
+ s.handlerN++;
843
+ }
844
+ if (isNum(p.statusCode)) {
845
+ const code = String(p.statusCode);
846
+ if (code in st.status || Object.keys(st.status).length < MAX_STATUS_CODES) {
847
+ st.status[code] = (st.status[code] ?? 0) + 1;
848
+ } else {
849
+ st.status.other = (st.status.other ?? 0) + 1;
850
+ }
851
+ }
852
+ const urlPattern = generalizeUrlPath(p.url);
853
+ this.aggregates.request(p.label, urlPattern, p.outcome, isNum(p.navMs) ? p.navMs : void 0);
854
+ const keep = this.sampleRequest(p.outcome);
855
+ if (keep === 0) return;
856
+ let context;
857
+ if (typeof p.context === "function") {
858
+ try {
859
+ context = p.context();
860
+ } catch {
861
+ context = void 0;
862
+ }
863
+ } else {
864
+ context = p.context;
865
+ }
866
+ const event = {
867
+ name: "request",
868
+ props: {
869
+ outcome: p.outcome,
870
+ retries: p.retries,
871
+ statusCode: p.statusCode,
872
+ domain: domainOf(p.url),
873
+ urlPattern,
874
+ navMs: p.navMs,
875
+ handlerMs: p.handlerMs,
876
+ recallMs: p.recallMs,
877
+ bytes: p.bytes,
878
+ blockType: p.blockType,
879
+ blockedAttempts,
880
+ context,
881
+ // Absent weight = 1 (every non-sampled event).
882
+ weight: keep === 1 ? void 0 : keep,
883
+ ...this.props(p.label)
884
+ }
885
+ };
886
+ this.queue.push(event);
887
+ }
888
+ /** Requests/s over the last 10 s; counts this request. O(1) amortized. */
889
+ tickRate() {
890
+ const t = this.now();
891
+ const abs = Math.floor(t / SLOT_MS);
892
+ if (this.slotAbs < 0) this.slotAbs = abs;
893
+ if (abs > this.slotAbs) {
894
+ const gap = Math.min(abs - this.slotAbs, SLOTS);
895
+ for (let i = 1; i <= gap; i++) {
896
+ const k = (this.slotAbs + i) % SLOTS;
897
+ this.windowSum -= this.slots[k];
898
+ this.slots[k] = 0;
899
+ }
900
+ this.slotAbs = abs;
901
+ }
902
+ this.slots[this.slotAbs % SLOTS]++;
903
+ this.windowSum++;
904
+ return this.windowSum / (SLOTS * SLOT_MS / 1e3);
905
+ }
906
+ /**
907
+ * 0 = drop, 1 = keep with weight 1, otherwise keep with this weight (1/p).
908
+ * Only routine scraped/recalled/skipped events are sampled, and only above
909
+ * 200 requests/s or when the server asked for a lower sampleRate.
910
+ */
911
+ sampleRequest(outcome) {
912
+ const rate = this.tickRate();
913
+ if (!ROUTINE.has(outcome)) return 1;
914
+ const sr = this.queue.sampleRate;
915
+ const serverRate = typeof sr === "number" && sr > 0 && sr <= 1 ? sr : 1;
916
+ const p = Math.min(1, SAMPLE_THRESHOLD / rate) * serverRate;
917
+ if (!(p > 0) || p >= 1) return 1;
918
+ return this.random() < p ? 1 / p : 0;
919
+ }
920
+ /** Records pushed (dataset items). Summed per label; sent as one record_pushed per label per batch. */
921
+ records(label, count) {
922
+ if (!isNum(count) || count <= 0) return;
923
+ const s = this.label(label);
924
+ s.stats.records += count;
925
+ s.pendingRecords += count;
926
+ }
927
+ drainRecords() {
928
+ const out = [];
929
+ for (const [label, s] of this.labels) {
930
+ if (s.pendingRecords <= 0) continue;
931
+ out.push({ name: "record_pushed", props: { count: s.pendingRecords, ...this.props(label) } });
932
+ s.pendingRecords = 0;
933
+ }
934
+ return out;
935
+ }
936
+ /** Children one handler call enqueued under one child label (count = newly added). */
937
+ enqueued(parentLabel, childLabel, count, alreadyQueued = 0) {
938
+ const added = isNum(count) && count > 0 ? count : 0;
939
+ const already = isNum(alreadyQueued) && alreadyQueued > 0 ? alreadyQueued : 0;
940
+ if (added + already === 0) return;
941
+ const st = this.label(parentLabel).stats;
942
+ const child = hasOwn(st.enqueued, childLabel) || hasOwn(st.alreadyQueued, childLabel) || Object.keys(st.enqueued).length < MAX_CHILD_LABELS ? childLabel : OVERFLOW_KEY;
943
+ st.enqueued[child] = (hasOwn(st.enqueued, child) ? st.enqueued[child] : 0) + added;
944
+ st.alreadyQueued[child] = (hasOwn(st.alreadyQueued, child) ? st.alreadyQueued[child] : 0) + already;
945
+ this.queue.push({
946
+ name: "enqueued",
947
+ props: { childLabel: child, count: added, alreadyQueued: already, ...this.props(parentLabel) }
948
+ });
949
+ }
950
+ /**
951
+ * A request's final failure. Grouped by fingerprint (class + scrubbed message +
952
+ * top project frame); the message is scrubbed once per new raw message and the
953
+ * result cached. Each event carries the cumulative per-run count for its
954
+ * fingerprint (the server sets it, never adds).
955
+ *
956
+ * Bounds: at most 1,000 fingerprints per run. Past that, a new fingerprint is
957
+ * counted under the single fingerprint "overflow" (class "Overflow", empty
958
+ * message). The raw-message cache holds ≤2,000 truncated keys; past that, new
959
+ * raw messages are scrubbed without caching.
960
+ */
961
+ error(label, err, context) {
962
+ const errorClass = errorClassOf(err);
963
+ const raw = rawMessageOf(err);
964
+ let frame;
965
+ try {
966
+ frame = topProjectFrame(stackOf(err));
967
+ } catch {
968
+ frame = void 0;
969
+ }
970
+ const rawKey = `${errorClass}
971
+ ${frame ?? ""}
972
+ ${raw.slice(0, RAW_KEY_CHARS)}`;
973
+ let fp = this.rawKeys.get(rawKey);
974
+ let message = "";
975
+ if (fp === void 0) {
976
+ try {
977
+ message = scrubMessage(raw);
978
+ } catch {
979
+ message = "";
980
+ }
981
+ fp = fingerprint(errorClass, message, frame);
982
+ if (this.rawKeys.size < MAX_RAW_KEYS) this.rawKeys.set(rawKey, fp);
983
+ }
984
+ let g = this.groups.get(fp);
985
+ if (!g) {
986
+ if (this.groups.size < MAX_FINGERPRINTS) {
987
+ g = { fingerprint: fp, errorClass, message, frame, count: 0 };
988
+ this.groups.set(fp, g);
989
+ } else {
990
+ g = this.groups.get(OVERFLOW_FINGERPRINT);
991
+ if (!g) {
992
+ g = { fingerprint: OVERFLOW_FINGERPRINT, errorClass: "Overflow", message: "", count: 0 };
993
+ this.groups.set(OVERFLOW_FINGERPRINT, g);
994
+ }
995
+ }
996
+ }
997
+ g.count++;
998
+ this.queue.push({
999
+ name: "error",
1000
+ props: {
1001
+ fingerprint: g.fingerprint,
1002
+ errorClass: g.errorClass,
1003
+ message: g.message,
1004
+ frame: g.frame,
1005
+ count: g.count,
1006
+ context,
1007
+ ...this.props(label)
1008
+ }
1009
+ });
1010
+ }
1011
+ runStarted(p) {
1012
+ this.queue.push({
1013
+ name: "run_started",
1014
+ props: {
1015
+ memoryMb: isNum(p.memoryMb) ? p.memoryMb : void 0,
1016
+ maxConcurrency: isNum(p.maxConcurrency) ? p.maxConcurrency : void 0,
1017
+ ...this.props("")
1018
+ }
1019
+ });
1020
+ }
1021
+ /** The account hit a monthly limit. The caller emits it at most once per run per cap. */
1022
+ quotaReached(cap) {
1023
+ this.queue.push({ name: "quota_reached", props: { cap, ...this.props("") } });
1024
+ }
1025
+ /** Exact run totals from the in-memory counters (failed = failed + blocked final outcomes). */
1026
+ runFinished(p) {
1027
+ let requests = 0;
1028
+ let records = 0;
1029
+ let failed = 0;
1030
+ for (const s of this.labels.values()) {
1031
+ requests += s.stats.requests;
1032
+ records += s.stats.records;
1033
+ failed += s.stats.failed + s.stats.blocked;
1034
+ }
1035
+ this.queue.push({
1036
+ name: "run_finished",
1037
+ props: { requests, records, failed, durationMs: isNum(p.durationMs) ? p.durationMs : 0, ...this.props("") }
1038
+ });
1039
+ }
1040
+ /**
1041
+ * A developer event. Never sampled. Invalid names/props are dropped; each rejected
1042
+ * name (reserved, fixed, or invalid) logs one debug line per run.
1043
+ */
1044
+ capture(name, props, label = "", context) {
1045
+ const clean = sanitizeCustom(name, props);
1046
+ if (!clean) {
1047
+ if (typeof name === "string" && name.length > 0) {
1048
+ const key = name.slice(0, 64);
1049
+ if (!this.rejectedNames.has(key) && this.rejectedNames.size < MAX_REJECTED_NAMES_LOGGED) {
1050
+ this.rejectedNames.add(key);
1051
+ this.debug(`Analytics: event "${key}" rejected (reserved or invalid name, or invalid props)`);
1052
+ }
1053
+ }
1054
+ return;
1055
+ }
1056
+ const custom = {};
1057
+ for (const k of Object.keys(clean.props)) if (!RESERVED_PROPS.has(k)) custom[k] = clean.props[k];
1058
+ if (!clean.name.startsWith("antibot.")) this.aggregates.custom(clean.name, label, custom);
1059
+ this.queue.push({
1060
+ name: clean.name,
1061
+ custom: true,
1062
+ // Base keys are reserved: a custom prop with those names is dropped, never overrides them.
1063
+ props: { ...custom, weight: void 0, context, ...this.props(label) }
1064
+ });
1065
+ }
1066
+ /** Exact per-run URL-pattern and custom-event aggregates for the run report. */
1067
+ aggregateReport() {
1068
+ return this.aggregates.toReport();
1069
+ }
1070
+ /** Exact counters per label (copies), with percentiles from the histograms. */
1071
+ labelStats() {
1072
+ const out = {};
1073
+ for (const [label, s] of this.labels) {
1074
+ const st = {
1075
+ ...s.stats,
1076
+ enqueued: { ...s.stats.enqueued },
1077
+ alreadyQueued: { ...s.stats.alreadyQueued },
1078
+ status: { ...s.stats.status }
1079
+ };
1080
+ const navP50 = percentile(s.nav, s.navN, 0.5);
1081
+ const navP95 = percentile(s.nav, s.navN, 0.95);
1082
+ const handlerP95 = percentile(s.handler, s.handlerN, 0.95);
1083
+ if (navP50 !== void 0) st.navP50 = navP50;
1084
+ if (navP95 !== void 0) st.navP95 = navP95;
1085
+ if (handlerP95 !== void 0) st.handlerP95 = handlerP95;
1086
+ out[label] = st;
1087
+ }
1088
+ return out;
1089
+ }
1090
+ };
1091
+ }
1092
+ });
7
1093
 
8
1094
  // src/circuit-breaker.ts
9
1095
  var DEFAULT_CONFIG = {
@@ -479,6 +1565,14 @@ var ApiError = class extends Error {
479
1565
  this.name = "ApiError";
480
1566
  }
481
1567
  };
1568
+ var TERMINAL_ANALYTICS_STATUSES = /* @__PURE__ */ new Set([400, 413, 415, 422]);
1569
+ var ANALYTICS_RATE_LIMIT_PAUSE_SEC = 10;
1570
+ var BadReplyError = class extends Error {
1571
+ constructor(message) {
1572
+ super(message);
1573
+ this.name = "BadReplyError";
1574
+ }
1575
+ };
482
1576
  function parseRetryAfter(header) {
483
1577
  if (!header) return void 0;
484
1578
  const secs = Number(header);
@@ -517,13 +1611,20 @@ var FetchBrainClient = class {
517
1611
  this.warnedOversizeLearn = false;
518
1612
  /** Warn about the learn cap once per pause, independent of the pause state. */
519
1613
  this.learnCapWarnedUntil = 0;
1614
+ /**
1615
+ * The monthly recall limit answered HARD_CAP_EXCEEDED. Recall (handler-time and
1616
+ * enqueue-time bulk) stops for the rest of the run. Per client instance; reset by
1617
+ * beginRun() so each new run() tries once more (a plan can reset between runs).
1618
+ */
1619
+ this.recallCapped = false;
520
1620
  /** Change counts, accumulated once per learn HTTP batch (never per learn() promise). */
521
- this.changeStats = { changed: 0, unchanged: 0, firstSeen: 0, drift: [] };
1621
+ this.changeStats = { changed: 0, unchanged: 0, firstSeen: 0, drift: [], known: 0 };
522
1622
  this.logger = createLogger(config.debug ? "debug" : "info", true);
523
1623
  this.config = {
524
1624
  apiKey: config.apiKey,
525
1625
  baseUrl: config.baseUrl || DEFAULT_BASE_URL,
526
1626
  memory: config.memory || "recent",
1627
+ recall: config.recall ?? true,
527
1628
  learning: config.learning ?? true,
528
1629
  alwaysRun: config.alwaysRun ?? false,
529
1630
  refreshOnRebuild: config.refreshOnRebuild ?? false,
@@ -532,8 +1633,6 @@ var FetchBrainClient = class {
532
1633
  debug: config.debug || false,
533
1634
  extractForLearning: config.extractForLearning,
534
1635
  learnUrlField: config.learnUrlField,
535
- telemetry: config.telemetry ?? { enabled: false },
536
- // opt-in
537
1636
  batch: config.batch,
538
1637
  circuitBreaker: config.circuitBreaker,
539
1638
  skipLabels: config.skipLabels,
@@ -546,6 +1645,8 @@ var FetchBrainClient = class {
546
1645
  // enhance-only; stored so getConfig() round-trips
547
1646
  scraper: config.scraper,
548
1647
  changeDetection: config.changeDetection,
1648
+ analytics: config.analytics,
1649
+ // enhance-only; stored so getConfig() round-trips
549
1650
  reportRuns: config.reportRuns ?? true
550
1651
  };
551
1652
  const scraper = resolveScraperName(config.scraper);
@@ -564,6 +1665,11 @@ var FetchBrainClient = class {
564
1665
  this.logger,
565
1666
  "Ask"
566
1667
  );
1668
+ this.analyticsCircuitBreaker = new CircuitBreaker(
1669
+ this.config.circuitBreaker,
1670
+ this.logger,
1671
+ "Analytics"
1672
+ );
567
1673
  this.batcher = new RequestBatcher(
568
1674
  (items) => this.executeBatchQuery(items),
569
1675
  clampBatch(this.config.batch, MAX_BULK_ITEMS),
@@ -577,11 +1683,45 @@ var FetchBrainClient = class {
577
1683
  }
578
1684
  /** True when recalls must not reach the API right now (crawl continues without). */
579
1685
  recallBlocked() {
580
- return this.isKeyRejected() || this.circuitBreaker.isOpen();
1686
+ return this.recallCapped || this.isKeyRejected() || this.circuitBreaker.isOpen();
1687
+ }
1688
+ /** Where the account stands against its limits: recall cap wins over learn cap. */
1689
+ quotaState() {
1690
+ if (this.recallCapped) return "recall_cap";
1691
+ if (Date.now() < this.learnCapWarnedUntil) return "learn_cap";
1692
+ return "ok";
1693
+ }
1694
+ /**
1695
+ * Start of a run(): the recall limit is retried once (plans can reset between
1696
+ * runs); if the API still answers HARD_CAP_EXCEEDED, recall stops again for
1697
+ * that run. The learn cap is month-bound and keeps its own pause.
1698
+ */
1699
+ beginRun() {
1700
+ this.recallCapped = false;
1701
+ }
1702
+ /** Called (never throws into the caller) when a limit is first seen. Pass undefined to clear. */
1703
+ onQuotaReached(listener) {
1704
+ this.quotaListener = listener;
1705
+ }
1706
+ notifyQuota(cap) {
1707
+ try {
1708
+ this.quotaListener?.(cap);
1709
+ } catch (err) {
1710
+ this.logger.debug("Quota listener failed:", err);
1711
+ }
581
1712
  }
582
1713
  isKeyRejected() {
583
1714
  return Date.now() < this.keyRejectedUntil;
584
1715
  }
1716
+ /** A 403 HARD_CAP_EXCEEDED on recall: warn once, pause recall for the run, tell the listener. */
1717
+ noteRecallCap(error) {
1718
+ if (!(error instanceof ApiError) || error.status !== 403 || error.code !== "HARD_CAP_EXCEEDED" && error.serverError !== "HARD_CAP_EXCEEDED" || this.recallCapped) {
1719
+ return;
1720
+ }
1721
+ this.recallCapped = true;
1722
+ this.logger.warn("Monthly recall limit reached \u2014 recall is paused until your plan resets; pages are fetched normally.");
1723
+ this.notifyQuota("recall");
1724
+ }
585
1725
  /**
586
1726
  * React to a 4xx the API returned. These are not outages (they don't open the
587
1727
  * shared breaker). A 401 means the next calls would fail the same way, so all
@@ -716,10 +1856,14 @@ var FetchBrainClient = class {
716
1856
  query: question,
717
1857
  answer: opts?.answer,
718
1858
  limit: opts?.limit,
719
- model: opts?.model
1859
+ model: opts?.model,
1860
+ memory: opts?.memory,
1861
+ versions: opts?.versions
720
1862
  };
721
1863
  const platformBuildId = getPlatformBuildId();
722
- if (this.config.refreshOnRebuild && platformBuildId) {
1864
+ if (opts?.build !== void 0) {
1865
+ askBody.build = opts.build;
1866
+ } else if (this.config.refreshOnRebuild && platformBuildId) {
723
1867
  askBody.build = platformBuildId;
724
1868
  }
725
1869
  try {
@@ -779,8 +1923,10 @@ var FetchBrainClient = class {
779
1923
  }
780
1924
  return results;
781
1925
  } catch (error) {
782
- if (!isOutage(error)) this.noteRefusal(error);
783
- else if (outcome) outcome.outage = true;
1926
+ if (!isOutage(error)) {
1927
+ this.noteRefusal(error);
1928
+ this.noteRecallCap(error);
1929
+ } else if (outcome) outcome.outage = true;
784
1930
  else this.circuitBreaker.recordFailure();
785
1931
  throw error;
786
1932
  }
@@ -799,6 +1945,10 @@ var FetchBrainClient = class {
799
1945
  const request = { entries };
800
1946
  const ignore = this.config.changeDetection?.ignoreFields;
801
1947
  if (ignore && ignore.length > 0) request.ignore = ignore;
1948
+ if (this.config.recall === false) {
1949
+ request.observe = true;
1950
+ request.memory = this.config.memory;
1951
+ }
802
1952
  const platformBuildId = getPlatformBuildId();
803
1953
  if (this.config.refreshOnRebuild && platformBuildId) {
804
1954
  request.build = platformBuildId;
@@ -819,6 +1969,7 @@ var FetchBrainClient = class {
819
1969
  const now = /* @__PURE__ */ new Date();
820
1970
  const monthStart = Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1);
821
1971
  this.learnPausedUntil = Math.max(this.learnPausedUntil, monthStart);
1972
+ this.notifyQuota("learn");
822
1973
  if (this.learnCapWarnedUntil < monthStart) {
823
1974
  this.learnCapWarnedUntil = monthStart;
824
1975
  this.logger.warn(
@@ -865,6 +2016,7 @@ var FetchBrainClient = class {
865
2016
  stats.changed += num(response.changed);
866
2017
  stats.unchanged += num(response.unchanged);
867
2018
  stats.firstSeen += num(response.firstSeen);
2019
+ stats.known = (stats.known ?? 0) + num(response.known);
868
2020
  const drift = Array.isArray(response.drift) ? response.drift : [];
869
2021
  for (const item of drift) {
870
2022
  if (!item || typeof item !== "object" || typeof item.label !== "string" || typeof item.field !== "string" || !DRIFT_KINDS.has(item.kind)) {
@@ -891,7 +2043,7 @@ var FetchBrainClient = class {
891
2043
  * failure or timeout it returns no flags.
892
2044
  */
893
2045
  async reportRun(report, timeoutMs = REPORT_RUN_TIMEOUT) {
894
- if (this.config.reportRuns === false || this.recallBlocked()) return [];
2046
+ if (this.config.reportRuns === false || this.isKeyRejected() || this.circuitBreaker.isOpen()) return [];
895
2047
  try {
896
2048
  const response = await this.makeRequest(
897
2049
  "/v1/runs",
@@ -906,12 +2058,95 @@ var FetchBrainClient = class {
906
2058
  return [];
907
2059
  }
908
2060
  }
2061
+ /**
2062
+ * Ship one gzipped analytics batch. Never throws. null = retry later (outage,
2063
+ * breaker open, key rejected, other 4xx, 429 without Retry-After, bad 2xx body);
2064
+ * `{ drop: true }` = the server permanently refused this batch (400/413/415/422),
2065
+ * so discard it.
2066
+ */
2067
+ async postAnalyticsEvents(body, _runId, signal) {
2068
+ if (this.isKeyRejected() || this.analyticsCircuitBreaker.isOpen()) return null;
2069
+ try {
2070
+ const response = await this.makeRequest(
2071
+ "/v1/analytics/events",
2072
+ {
2073
+ method: "POST",
2074
+ body,
2075
+ headers: {
2076
+ "Content-Type": "application/json",
2077
+ "Content-Encoding": "gzip"
2078
+ }
2079
+ },
2080
+ DEFAULT_LEARN_TIMEOUT,
2081
+ { signal, lenientBody: true }
2082
+ );
2083
+ this.analyticsCircuitBreaker.recordSuccess();
2084
+ const out = {};
2085
+ if (response && typeof response.sampleRate === "number") out.sampleRate = response.sampleRate;
2086
+ if (response && typeof response.pauseUntil === "number") out.pauseUntil = response.pauseUntil;
2087
+ return out;
2088
+ } catch (error) {
2089
+ this.noteRefusal(error);
2090
+ if (signal?.aborted) {
2091
+ return null;
2092
+ } else if (error instanceof BadReplyError) {
2093
+ this.analyticsCircuitBreaker.recordFailure();
2094
+ this.logger.debug("Analytics reply was not JSON:", error);
2095
+ return null;
2096
+ } else if (isOutage(error)) {
2097
+ this.analyticsCircuitBreaker.recordFailure();
2098
+ } else if (error instanceof ApiError) {
2099
+ if (error.status === 429) {
2100
+ const hinted = error.retryAfterSec;
2101
+ const waitSec = typeof hinted === "number" && Number.isFinite(hinted) && hinted > 0 ? Math.min(Math.max(hinted, 1), 3600) : ANALYTICS_RATE_LIMIT_PAUSE_SEC;
2102
+ return { pauseUntil: Date.now() + waitSec * 1e3, retry: true };
2103
+ } else if (TERMINAL_ANALYTICS_STATUSES.has(error.status)) {
2104
+ this.logger.debug("Analytics batch refused:", error);
2105
+ return { drop: true };
2106
+ }
2107
+ }
2108
+ this.logger.debug("Analytics events post failed:", error);
2109
+ return null;
2110
+ }
2111
+ }
2112
+ /** The resolved scraper name (valid option, else env var); undefined = default memory. */
2113
+ getScraperName() {
2114
+ return this.scraperName;
2115
+ }
2116
+ /** Fetch the analytics config for this key. Never throws: failure returns null. */
2117
+ async getAnalyticsConfig() {
2118
+ if (this.isKeyRejected() || this.analyticsCircuitBreaker.isOpen()) return null;
2119
+ try {
2120
+ const r = await this.makeRequest("/v1/analytics/config", { method: "GET" });
2121
+ this.analyticsCircuitBreaker.recordSuccess();
2122
+ if (!r || typeof r.enabled !== "boolean") return null;
2123
+ const salt = typeof r.salt === "string" ? r.salt : "";
2124
+ if (!r.enabled) return { enabled: false, salt, sampleRate: 1 };
2125
+ return {
2126
+ salt,
2127
+ sampleRate: typeof r.sampleRate === "number" ? r.sampleRate : 1,
2128
+ ...typeof r.pauseUntil === "number" ? { pauseUntil: r.pauseUntil } : {},
2129
+ enabled: true
2130
+ };
2131
+ } catch (error) {
2132
+ this.noteRefusal(error);
2133
+ if (isOutage(error)) this.analyticsCircuitBreaker.recordFailure();
2134
+ this.logger.debug("Analytics config fetch failed:", error);
2135
+ return null;
2136
+ }
2137
+ }
909
2138
  /**
910
2139
  * Make an HTTP request to the API
911
2140
  */
912
- async makeRequest(path, options, timeout) {
2141
+ async makeRequest(path, options, timeout, extra) {
913
2142
  const url = `${this.config.baseUrl}${path}`;
914
2143
  const controller = new AbortController();
2144
+ const external = extra?.signal;
2145
+ const onExternalAbort = () => controller.abort();
2146
+ if (external) {
2147
+ if (external.aborted) controller.abort();
2148
+ else external.addEventListener("abort", onExternalAbort, { once: true });
2149
+ }
915
2150
  const timeoutId = setTimeout(
916
2151
  () => controller.abort(),
917
2152
  timeout ?? this.config.timeout
@@ -975,9 +2210,24 @@ var FetchBrainClient = class {
975
2210
  parseRetryAfter(response.headers.get("Retry-After"))
976
2211
  );
977
2212
  }
2213
+ if (extra?.lenientBody) {
2214
+ const text = await readBody(response, (r) => r.text());
2215
+ if (response.status === 204 || text.length === 0) return {};
2216
+ let parsed;
2217
+ try {
2218
+ parsed = JSON.parse(text);
2219
+ } catch {
2220
+ throw new BadReplyError("Unexpected non-JSON reply");
2221
+ }
2222
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
2223
+ throw new BadReplyError("Unexpected reply shape");
2224
+ }
2225
+ return parsed;
2226
+ }
978
2227
  return await readBody(response, (r) => r.json());
979
2228
  } finally {
980
2229
  clearTimeout(timeoutId);
2230
+ external?.removeEventListener("abort", onExternalAbort);
981
2231
  }
982
2232
  }
983
2233
  /**
@@ -1019,181 +2269,42 @@ var FetchBrainClient = class {
1019
2269
  async flushLearnBatch() {
1020
2270
  await this.learnBatcher.forceFlush();
1021
2271
  }
1022
- /**
1023
- * Send telemetry data to the API
1024
- * This is fire-and-forget - failures are silently ignored
1025
- */
1026
- async sendTelemetry(entries) {
1027
- if (!this.config.telemetry?.enabled || entries.length === 0) {
1028
- return;
1029
- }
1030
- try {
1031
- await this.makeRequest("/v1/telemetry", {
1032
- method: "POST",
1033
- body: JSON.stringify({ entries })
1034
- });
1035
- } catch {
1036
- }
1037
- }
1038
- /**
1039
- * Check if telemetry is enabled
1040
- */
1041
- isTelemetryEnabled() {
1042
- return this.config.telemetry?.enabled ?? false;
1043
- }
1044
- /**
1045
- * Get telemetry config
1046
- */
1047
- getTelemetryConfig() {
1048
- return this.config.telemetry;
1049
- }
1050
2272
  };
1051
2273
 
1052
- // src/telemetry.ts
1053
- async function hashString(str) {
1054
- const encoder = new TextEncoder();
1055
- const data = encoder.encode(str);
1056
- const hashBuffer = await crypto.subtle.digest("SHA-256", data);
1057
- const hashArray = Array.from(new Uint8Array(hashBuffer));
1058
- return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
2274
+ // src/enhance.ts
2275
+ var collectorModule;
2276
+ function loadCollector() {
2277
+ return collectorModule ?? (collectorModule = Promise.resolve().then(() => (init_collector(), collector_exports)).catch(() => {
2278
+ collectorModule = void 0;
2279
+ return void 0;
2280
+ }));
1059
2281
  }
1060
- function extractDomain(url) {
1061
- try {
1062
- return new URL(url).hostname;
1063
- } catch {
1064
- return "unknown";
2282
+ var MAX_TALLY_LABELS = 50;
2283
+ var DEFAULT_CHILD_LABEL = "_nolabel";
2284
+ var ANALYTICS_CONFIG_TIMEOUT_MS = 500;
2285
+ var MAX_BLOCKED_TRACKED = 1e4;
2286
+ var msSince = (t0) => Math.round(performance.now() - t0);
2287
+ function statusFrom(response) {
2288
+ const r = response;
2289
+ if (!r) return void 0;
2290
+ if (typeof r.statusCode === "number") return r.statusCode;
2291
+ if (typeof r.status === "function") {
2292
+ const s = r.status.call(r);
2293
+ return typeof s === "number" ? s : void 0;
1065
2294
  }
1066
- }
1067
- function generalizeUrlPath(url) {
1068
- try {
1069
- const parsed = new URL(url);
1070
- const path = parsed.pathname;
1071
- return path.replace(/\/\d+/g, "/*").replace(/\/[a-f0-9-]{36}/gi, "/*").replace(/\/[a-zA-Z0-9]{20,}/g, "/*").replace(/\?.*$/, "");
1072
- } catch {
1073
- return "/*";
1074
- }
1075
- }
1076
- function detectBlockType(statusCode, errorMessage) {
1077
- if (!statusCode && !errorMessage) return void 0;
1078
- if (statusCode === 403) return "403";
1079
- if (statusCode === 429) return "429";
1080
- if (statusCode === 503) return "503";
1081
- if (statusCode && statusCode >= 400) return `${statusCode}`;
1082
- const msg = errorMessage?.toLowerCase() || "";
1083
- if (msg.includes("captcha")) return "captcha";
1084
- if (msg.includes("timeout")) return "timeout";
1085
- if (msg.includes("blocked")) return "blocked";
1086
- if (msg.includes("rate limit")) return "429";
1087
2295
  return void 0;
1088
2296
  }
1089
- function extractProxyType(proxyUrl) {
1090
- if (!proxyUrl) return void 0;
1091
- const url = proxyUrl.toLowerCase();
1092
- if (url.includes("residential")) return "residential";
1093
- if (url.includes("mobile")) return "mobile";
1094
- if (url.includes("datacenter") || url.includes("dc")) return "datacenter";
1095
- if (url.includes("bright") || url.includes("oxylabs") || url.includes("smartproxy")) {
1096
- return "residential";
1097
- }
1098
- return "datacenter";
2297
+ function bodyBytes(context) {
2298
+ const body = context.body;
2299
+ if (Buffer.isBuffer(body)) return body.length;
2300
+ if (typeof body === "string") return Buffer.byteLength(body);
2301
+ return void 0;
1099
2302
  }
1100
- async function collectTelemetry(context, timing, config, error) {
1101
- if (!config?.enabled) {
1102
- return null;
1103
- }
1104
- const url = context.request.url;
1105
- const statusCode = context.response?.status || context.response?.statusCode;
1106
- const telemetry = {
1107
- domain: extractDomain(url),
1108
- urlHash: await hashString(url),
1109
- urlPattern: generalizeUrlPath(url),
1110
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
1111
- };
1112
- if (config.sharePerformance !== false) {
1113
- telemetry.statusCode = statusCode;
1114
- telemetry.retryCount = context.request.retryCount;
1115
- if (timing) {
1116
- telemetry.responseTimeMs = timing.responseTime;
1117
- telemetry.totalTimeMs = timing.endTime && timing.startTime ? timing.endTime - timing.startTime : void 0;
1118
- telemetry.contentSize = timing.contentSize;
1119
- }
1120
- }
1121
- if (config.shareProxyInfo !== false && context.proxyInfo) {
1122
- telemetry.proxyCountry = context.proxyInfo.countryCode;
1123
- telemetry.proxyType = extractProxyType(context.proxyInfo.url);
1124
- telemetry.proxySuccess = statusCode ? statusCode < 400 : void 0;
1125
- }
1126
- if (config.shareSitePatterns !== false) {
1127
- const isBlocked = statusCode && (statusCode === 403 || statusCode === 429 || statusCode >= 500);
1128
- telemetry.blocked = isBlocked || !!error;
1129
- telemetry.blockType = detectBlockType(statusCode, error?.message);
1130
- }
1131
- if (context.session) {
1132
- telemetry.sessionAge = context.session.usageCount;
1133
- telemetry.sessionErrorScore = context.session.errorScore;
1134
- }
1135
- telemetry.crawlerType = context.crawler?.constructor?.name?.replace("Crawler", "").toLowerCase();
1136
- telemetry.requestLabel = context.request.label;
1137
- return telemetry;
2303
+ function headerBytes(response) {
2304
+ const headers = response?.headers;
2305
+ const len = headers && typeof headers === "object" ? Number(headers["content-length"]) : NaN;
2306
+ return Number.isFinite(len) && len >= 0 ? len : void 0;
1138
2307
  }
1139
- var TelemetryBuffer = class {
1140
- constructor(options = {}) {
1141
- this.buffer = [];
1142
- this.maxSize = options.maxSize ?? 50;
1143
- this.flushInterval = options.flushInterval ?? 3e4;
1144
- this.flushCallback = options.onFlush;
1145
- this.startFlushTimer();
1146
- }
1147
- /**
1148
- * Add telemetry entry to buffer
1149
- */
1150
- add(entry) {
1151
- if (!entry) return;
1152
- this.buffer.push(entry);
1153
- if (this.buffer.length >= this.maxSize) {
1154
- this.flush();
1155
- }
1156
- }
1157
- /**
1158
- * Flush buffer and send telemetry
1159
- */
1160
- async flush() {
1161
- if (this.buffer.length === 0) return [];
1162
- const entries = [...this.buffer];
1163
- this.buffer = [];
1164
- if (this.flushCallback) {
1165
- try {
1166
- await this.flushCallback(entries);
1167
- } catch (err) {
1168
- console.debug("Telemetry flush failed:", err);
1169
- }
1170
- }
1171
- return entries;
1172
- }
1173
- /**
1174
- * Get current buffer size
1175
- */
1176
- get size() {
1177
- return this.buffer.length;
1178
- }
1179
- startFlushTimer() {
1180
- this.flushTimer = setInterval(() => {
1181
- this.flush();
1182
- }, this.flushInterval);
1183
- this.flushTimer.unref?.();
1184
- }
1185
- /**
1186
- * Stop the flush timer and flush remaining entries
1187
- */
1188
- async stop() {
1189
- if (this.flushTimer) {
1190
- clearInterval(this.flushTimer);
1191
- }
1192
- await this.flush();
1193
- }
1194
- };
1195
-
1196
- // src/enhance.ts
1197
2308
  var REPORT_MAX_LABELS = 50;
1198
2309
  var REPORT_LABEL_MAX_CHARS = 64;
1199
2310
  var RUN_ID_MAX_CHARS = 128;
@@ -1201,7 +2312,7 @@ var NO_LABEL = "_nolabel";
1201
2312
  var platformRunSeq = /* @__PURE__ */ new Map();
1202
2313
  function nextRunId() {
1203
2314
  const platform = process.env.APIFY_ACTOR_RUN_ID;
1204
- if (!platform) return crypto$1.randomUUID();
2315
+ if (!platform) return crypto.randomUUID();
1205
2316
  const id = platform.slice(0, RUN_ID_MAX_CHARS - 8);
1206
2317
  const n = (platformRunSeq.get(id) ?? 0) + 1;
1207
2318
  platformRunSeq.set(id, n);
@@ -1216,11 +2327,36 @@ function reportLabel(label) {
1216
2327
  const trimmed = (labelText(label) ?? "").trim().slice(0, REPORT_LABEL_MAX_CHARS);
1217
2328
  return trimmed || NO_LABEL;
1218
2329
  }
2330
+ function analyticsLabelText(label) {
2331
+ return (labelText(label) ?? "").replace(/^[\s~]+/, "").trim().slice(0, REPORT_LABEL_MAX_CHARS);
2332
+ }
2333
+ function analyticsLabel(label) {
2334
+ return analyticsLabelText(label) || NO_LABEL;
2335
+ }
1219
2336
  var pct = (rate) => `${Math.round(rate * 100)}%`;
1220
2337
  function describeDrift(d) {
1221
2338
  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))}`;
1222
2339
  return `\u26A0\uFE0F drift [${clipText(d.label, 64)}] ${clipText(d.field, 64)}: ${detail}`;
1223
2340
  }
2341
+ function safeBeginRun(client) {
2342
+ try {
2343
+ client.beginRun();
2344
+ } catch {
2345
+ }
2346
+ }
2347
+ function safeQuotaState(client) {
2348
+ try {
2349
+ return client.quotaState();
2350
+ } catch {
2351
+ return "ok";
2352
+ }
2353
+ }
2354
+ function safeOnQuotaReached(client, listener) {
2355
+ try {
2356
+ client.onQuotaReached(listener);
2357
+ } catch {
2358
+ }
2359
+ }
1224
2360
  function safeChangeStats(client) {
1225
2361
  try {
1226
2362
  return client.getChangeStats();
@@ -1302,9 +2438,52 @@ function warnDefaultUniqueKey(request, logger, warned, shownUrl) {
1302
2438
  }
1303
2439
  }
1304
2440
  var asyncContext = new async_hooks.AsyncLocalStorage();
2441
+ var noopCapture = () => {
2442
+ };
2443
+ var recordCount = (data) => Array.isArray(data) ? data.length : 1;
2444
+ function childLabelOf(r) {
2445
+ if (!r || typeof r !== "object") return DEFAULT_CHILD_LABEL;
2446
+ try {
2447
+ const o = r;
2448
+ return analyticsLabelText(o.label ?? o.userData?.label) || DEFAULT_CHILD_LABEL;
2449
+ } catch {
2450
+ return DEFAULT_CHILD_LABEL;
2451
+ }
2452
+ }
2453
+ function tallyAdd(t, label, added, already) {
2454
+ const key = t.has(label) || t.size < MAX_TALLY_LABELS ? label : "~other";
2455
+ const cur = t.get(key);
2456
+ if (cur) {
2457
+ cur[0] += added;
2458
+ cur[1] += already;
2459
+ } else {
2460
+ t.set(key, [added, already]);
2461
+ }
2462
+ }
2463
+ function userDataForCallback(userData) {
2464
+ if (!userData) return {};
2465
+ let hasSdkKey = false;
2466
+ for (const k of SDK_USERDATA_KEYS) if (k in userData) hasSdkKey = true;
2467
+ if (!hasSdkKey) return userData;
2468
+ const out = {};
2469
+ for (const [k, v] of Object.entries(userData)) if (!SDK_USERDATA_KEYS.has(k)) out[k] = v;
2470
+ return out;
2471
+ }
1305
2472
  function getCurrentContext() {
1306
2473
  return asyncContext.getStore();
1307
2474
  }
2475
+ async function fetchAnalyticsConfig(client) {
2476
+ let timer;
2477
+ const timeout = new Promise((resolve) => {
2478
+ timer = setTimeout(() => resolve(null), ANALYTICS_CONFIG_TIMEOUT_MS);
2479
+ timer.unref?.();
2480
+ });
2481
+ try {
2482
+ return await Promise.race([client.getAnalyticsConfig().catch(() => null), timeout]);
2483
+ } finally {
2484
+ if (timer) clearTimeout(timer);
2485
+ }
2486
+ }
1308
2487
  function shouldRunHandler(alwaysRun, label) {
1309
2488
  if (alwaysRun === void 0 || alwaysRun === false) {
1310
2489
  return false;
@@ -1355,19 +2534,9 @@ var FetchBrain = class {
1355
2534
  * @returns Enhanced crawler with same interface
1356
2535
  */
1357
2536
  static enhance(crawler, config) {
1358
- const client = new FetchBrainClient(config);
2537
+ const client = Object.assign(new FetchBrainClient(config), { capture: noopCapture });
1359
2538
  const logger = createLogger(config.debug ? "debug" : "info", true);
1360
- const telemetryConfig = config.telemetry ?? { enabled: false };
1361
- const telemetryBuffer = new TelemetryBuffer({
1362
- maxSize: 50,
1363
- flushInterval: 3e4,
1364
- onFlush: async (entries) => {
1365
- if (telemetryConfig.enabled) {
1366
- await client.sendTelemetry(entries);
1367
- logger.debug(`Telemetry: sent ${entries.length} entries`);
1368
- }
1369
- }
1370
- });
2539
+ const observe = config.recall === false;
1371
2540
  const runStats = {
1372
2541
  totalRequests: 0,
1373
2542
  recalled: 0,
@@ -1446,19 +2615,302 @@ var FetchBrain = class {
1446
2615
  return void 0;
1447
2616
  };
1448
2617
  const skipLabels = config.skipLabels && config.skipLabels.length ? new Set(config.skipLabels) : void 0;
2618
+ const analyticsOn = config.analytics?.enabled === true;
2619
+ if (analyticsOn) void loadCollector();
2620
+ let collector;
2621
+ const attempts = /* @__PURE__ */ new WeakMap();
2622
+ const blockedByRequest = /* @__PURE__ */ new Map();
2623
+ const emittedThenFailed = /* @__PURE__ */ new Set();
2624
+ const attemptOf = (ctx) => {
2625
+ let a = attempts.get(ctx);
2626
+ if (!a) {
2627
+ a = {};
2628
+ attempts.set(ctx, a);
2629
+ }
2630
+ return a;
2631
+ };
2632
+ const requestKey = (r) => String(r.id ?? r.uniqueKey ?? r.url);
2633
+ const emitRequest = (c, ctx, a, outcome, blockType) => {
2634
+ if (a.emitted) return;
2635
+ a.emitted = true;
2636
+ const request = ctx.request;
2637
+ const key = requestKey(request);
2638
+ if (emittedThenFailed.size > 0 && emittedThenFailed.has(key)) return;
2639
+ const blockedAttempts = blockedByRequest.get(key) ?? 0;
2640
+ if (blockedAttempts) blockedByRequest.delete(key);
2641
+ c.request({
2642
+ label: analyticsLabel(request.label),
2643
+ outcome,
2644
+ retries: typeof request.retryCount === "number" ? request.retryCount : 0,
2645
+ url: request.url,
2646
+ statusCode: a.statusCode,
2647
+ navMs: a.navMs,
2648
+ handlerMs: a.handlerMs,
2649
+ recallMs: a.recallMs,
2650
+ bytes: a.bytes,
2651
+ blockType,
2652
+ blockedAttempts,
2653
+ // Evaluated only if the event survives sampling.
2654
+ context: () => contextFor(c, a, request)
2655
+ });
2656
+ };
2657
+ const recordSuccess = (context, outcome, handlerMs, recallMs) => {
2658
+ const c = collector;
2659
+ if (!c) return;
2660
+ try {
2661
+ const a = attemptOf(context);
2662
+ if (a.failed) return;
2663
+ a.handlerMs = handlerMs;
2664
+ a.recallMs = recallMs;
2665
+ a.bytes = bodyBytes(context) ?? a.bytes;
2666
+ emitRequest(c, context, a, outcome);
2667
+ } catch (analyticsErr) {
2668
+ logger.debug(`Analytics skipped: ${analyticsErr}`);
2669
+ }
2670
+ };
2671
+ const noteFailure = (c, ctx, err) => {
2672
+ const a = attemptOf(ctx);
2673
+ a.failed = true;
2674
+ if (a.emitted && emittedThenFailed.size < MAX_BLOCKED_TRACKED) {
2675
+ emittedThenFailed.add(requestKey(ctx.request));
2676
+ }
2677
+ a.statusCode ?? (a.statusCode = statusFrom(ctx.response));
2678
+ const message = err instanceof Error ? err.message : typeof err === "string" ? err : void 0;
2679
+ const blockType = c.blockType(a.statusCode, message);
2680
+ if (blockType && !a.blockCounted) {
2681
+ a.blockCounted = true;
2682
+ const key = requestKey(ctx.request);
2683
+ const n = blockedByRequest.get(key);
2684
+ if (n !== void 0 || blockedByRequest.size < MAX_BLOCKED_TRACKED) blockedByRequest.set(key, (n ?? 0) + 1);
2685
+ }
2686
+ return { a, blockType };
2687
+ };
2688
+ const contextFn = config.analytics?.context;
2689
+ const contextFor = (c, a, request) => {
2690
+ if (!contextFn) return void 0;
2691
+ if (a.ctxDone) return a.ctx;
2692
+ a.ctxDone = true;
2693
+ try {
2694
+ const raw = contextFn({
2695
+ url: request.url,
2696
+ label: labelText(request.label),
2697
+ userData: userDataForCallback(request.userData)
2698
+ });
2699
+ if (raw && typeof raw.then === "function") {
2700
+ Promise.resolve(raw).catch(() => {
2701
+ });
2702
+ return void 0;
2703
+ }
2704
+ a.ctx = c.sanitizeContext(raw);
2705
+ } catch {
2706
+ a.ctx = void 0;
2707
+ }
2708
+ return a.ctx;
2709
+ };
2710
+ const noteRecords = (label, n) => {
2711
+ const c = collector;
2712
+ if (!c) return;
2713
+ try {
2714
+ c.records(label, n);
2715
+ } catch (analyticsErr) {
2716
+ logger.debug(`Analytics skipped: ${analyticsErr}`);
2717
+ }
2718
+ };
2719
+ const captureFor = (context, request, label) => (name, props) => {
2720
+ const c = collector;
2721
+ if (!c) return;
2722
+ try {
2723
+ c.capture(name, props, label, contextFor(c, attemptOf(context), request));
2724
+ } catch (analyticsErr) {
2725
+ logger.debug(`Analytics skipped: ${analyticsErr}`);
2726
+ }
2727
+ };
2728
+ const emitTally = (parentLabel, t) => {
2729
+ const c = collector;
2730
+ if (!c) return;
2731
+ for (const [child, [added, already]] of t) c.enqueued(parentLabel, child, added, already);
2732
+ };
2733
+ const wrapFanOut = (context, parentLabel) => {
2734
+ const handlerTally = /* @__PURE__ */ new Map();
2735
+ let late;
2736
+ let flushed = false;
2737
+ const merge = (t) => {
2738
+ const into = flushed ? late ?? (late = /* @__PURE__ */ new Map()) : handlerTally;
2739
+ for (const [label, [added, already]] of t) tallyAdd(into, label, added, already);
2740
+ };
2741
+ const settle = () => {
2742
+ if (flushed && late && late.size > 0) {
2743
+ const t = late;
2744
+ late = void 0;
2745
+ emitTally(parentLabel, t);
2746
+ }
2747
+ };
2748
+ const flush = () => {
2749
+ if (flushed) return;
2750
+ flushed = true;
2751
+ try {
2752
+ emitTally(parentLabel, handlerTally);
2753
+ } catch (analyticsErr) {
2754
+ logger.debug(`Analytics skipped: ${analyticsErr}`);
2755
+ }
2756
+ };
2757
+ const origLinks = context.enqueueLinks;
2758
+ if (typeof origLinks === "function") {
2759
+ context.enqueueLinks = async function(options) {
2760
+ const tally = /* @__PURE__ */ new Map();
2761
+ let viewUsed = false;
2762
+ let opts = options;
2763
+ if (collector) {
2764
+ try {
2765
+ const crawlerRef = context.crawler;
2766
+ const rq = options?.requestQueue ?? (typeof crawlerRef?.getRequestQueue === "function" ? await crawlerRef.getRequestQueue() : void 0);
2767
+ const addBatched = rq?.addRequestsBatched;
2768
+ if (rq && typeof addBatched === "function") {
2769
+ const view = Object.create(rq);
2770
+ view.addRequestsBatched = async (reqs, o) => {
2771
+ const res2 = await addBatched.call(rq, reqs, o);
2772
+ try {
2773
+ viewUsed = true;
2774
+ if (Array.isArray(reqs)) {
2775
+ const present = /* @__PURE__ */ new Set();
2776
+ const added = res2?.addedRequests;
2777
+ if (Array.isArray(added)) {
2778
+ for (const pr of added) {
2779
+ if (pr && pr.wasAlreadyPresent === true) present.add(pr.uniqueKey);
2780
+ }
2781
+ }
2782
+ for (const r of reqs) {
2783
+ const already = present.has(r?.uniqueKey);
2784
+ tallyAdd(tally, childLabelOf(r), already ? 0 : 1, already ? 1 : 0);
2785
+ }
2786
+ }
2787
+ } catch {
2788
+ }
2789
+ return res2;
2790
+ };
2791
+ opts = { ...options ?? {}, requestQueue: view };
2792
+ }
2793
+ } catch {
2794
+ opts = options;
2795
+ }
2796
+ }
2797
+ const res = await origLinks.call(this, opts);
2798
+ try {
2799
+ if (collector) {
2800
+ if (!viewUsed) {
2801
+ const label = childLabelOf(options);
2802
+ const processed = res?.processedRequests;
2803
+ if (Array.isArray(processed)) {
2804
+ for (const pr of processed) {
2805
+ const already = pr?.wasAlreadyPresent === true;
2806
+ tallyAdd(tally, label, already ? 0 : 1, already ? 1 : 0);
2807
+ }
2808
+ }
2809
+ }
2810
+ merge(tally);
2811
+ settle();
2812
+ }
2813
+ } catch (analyticsErr) {
2814
+ logger.debug(`Analytics skipped: ${analyticsErr}`);
2815
+ }
2816
+ return res;
2817
+ };
2818
+ }
2819
+ const origAdd = context.addRequests;
2820
+ if (typeof origAdd === "function") {
2821
+ context.addRequests = async function(requests, options) {
2822
+ if (!collector) return origAdd.call(this, requests, options);
2823
+ if (Array.isArray(requests)) {
2824
+ const res = await origAdd.call(this, requests, options);
2825
+ try {
2826
+ const tally = /* @__PURE__ */ new Map();
2827
+ for (const r of requests) tallyAdd(tally, childLabelOf(r), 1, 0);
2828
+ merge(tally);
2829
+ settle();
2830
+ } catch (analyticsErr) {
2831
+ logger.debug(`Analytics skipped: ${analyticsErr}`);
2832
+ }
2833
+ return res;
2834
+ }
2835
+ const iterable = requests;
2836
+ if (!iterable || typeof iterable !== "object" || typeof iterable[Symbol.iterator] !== "function" && typeof iterable[Symbol.asyncIterator] !== "function") {
2837
+ return origAdd.call(this, requests, options);
2838
+ }
2839
+ async function* counted() {
2840
+ try {
2841
+ for await (const r of requests) {
2842
+ try {
2843
+ tallyAdd(flushed ? late ?? (late = /* @__PURE__ */ new Map()) : handlerTally, childLabelOf(r), 1, 0);
2844
+ } catch {
2845
+ }
2846
+ yield r;
2847
+ }
2848
+ } finally {
2849
+ try {
2850
+ settle();
2851
+ } catch {
2852
+ }
2853
+ }
2854
+ }
2855
+ return origAdd.call(this, counted(), options);
2856
+ };
2857
+ }
2858
+ return flush;
2859
+ };
2860
+ const clientCapture = (name, props) => {
2861
+ try {
2862
+ const store = asyncContext.getStore();
2863
+ if (store?.capture && store.client === client) return store.capture(name, props);
2864
+ collector?.capture(name, props, NO_LABEL);
2865
+ } catch (analyticsErr) {
2866
+ logger.debug(`Analytics skipped: ${analyticsErr}`);
2867
+ }
2868
+ };
2869
+ client.capture = clientCapture;
1449
2870
  const wrappedHandler = async (context) => {
1450
2871
  crawlStarted = true;
1451
2872
  const { request } = context;
1452
2873
  const url = request.url;
1453
2874
  const label = request.label;
1454
- const startTime = Date.now();
1455
2875
  runStats.totalRequests++;
2876
+ const aLabel = collector ? analyticsLabel(label) : NO_LABEL;
1456
2877
  if (skipLabels && skipLabels.has(label || "default")) {
1457
2878
  runStats.bypassed++;
1458
2879
  if (config.debug) {
1459
2880
  logger.debug(`Bypassing FetchBrain for [${label || "default"}]${urlSuffix(logUrlFor(buildRawRequest(request), config.logUrl))}`);
1460
2881
  }
1461
- await originalHandler.call(crawler, context);
2882
+ const b0 = analyticsOn ? performance.now() : 0;
2883
+ if (collector) {
2884
+ const bypassPush = context.pushData;
2885
+ if (bypassPush) {
2886
+ context.pushData = async (data) => {
2887
+ const res = await bypassPush.call(context, data);
2888
+ noteRecords(aLabel, recordCount(data));
2889
+ return res;
2890
+ };
2891
+ }
2892
+ const flushFanOut = wrapFanOut(context, aLabel);
2893
+ const bypassContext = {
2894
+ request: buildRawRequest(request),
2895
+ client,
2896
+ learning: false,
2897
+ aiKnown: false,
2898
+ relearn: false,
2899
+ items: [],
2900
+ capture: captureFor(context, request, aLabel),
2901
+ records: (n) => noteRecords(aLabel, n)
2902
+ };
2903
+ try {
2904
+ await asyncContext.run(bypassContext, async () => {
2905
+ await originalHandler.call(crawler, context);
2906
+ });
2907
+ } finally {
2908
+ flushFanOut();
2909
+ }
2910
+ } else {
2911
+ await originalHandler.call(crawler, context);
2912
+ }
2913
+ if (analyticsOn) recordSuccess(context, "bypassed", msSince(b0), void 0);
1462
2914
  return;
1463
2915
  }
1464
2916
  setScrapeContext({
@@ -1471,6 +2923,8 @@ var FetchBrain = class {
1471
2923
  const shownUrl = () => (shown ?? (shown = { text: logUrlFor(rawRequest, config.logUrl) })).text;
1472
2924
  warnDefaultUniqueKey(rawRequest, logger, warnedKeys, shownUrl);
1473
2925
  let consumedStash;
2926
+ let recallMs;
2927
+ let handlerMs;
1474
2928
  try {
1475
2929
  const preRecalled = request.userData?.__fetchBrainResult;
1476
2930
  let aiResult;
@@ -1480,12 +2934,18 @@ var FetchBrain = class {
1480
2934
  consumedStash = stashedData;
1481
2935
  aiResult = { known: true, data: stashedData };
1482
2936
  } else {
2937
+ const r0 = analyticsOn ? performance.now() : 0;
1483
2938
  aiResult = await client.recall(rawRequest);
2939
+ if (analyticsOn) recallMs = msSince(r0);
1484
2940
  }
1485
2941
  } else if (preRecalled) {
1486
2942
  aiResult = preRecalled;
2943
+ } else if (observe) {
2944
+ aiResult = { known: false };
1487
2945
  } else {
2946
+ const r0 = analyticsOn ? performance.now() : 0;
1488
2947
  aiResult = await client.recall(rawRequest);
2948
+ if (analyticsOn) recallMs = msSince(r0);
1489
2949
  }
1490
2950
  if (preRecalled?.known && request.skipNavigation && !(aiResult.known && aiResult.data)) {
1491
2951
  if (aiResult.fallback) {
@@ -1522,10 +2982,13 @@ var FetchBrain = class {
1522
2982
  if (aiResult.known && aiResult.data && originalPushData) {
1523
2983
  usedAIData = true;
1524
2984
  await originalPushData.call(context, aiResult.data);
2985
+ noteRecords(aLabel, recordCount(aiResult.data));
1525
2986
  if (config.debug) logger.debug(`Used brain data${urlSuffix(shownUrl())}`);
1526
2987
  await fireOnRecalled(aiResult.data);
1527
2988
  }
1528
- }
2989
+ },
2990
+ // Custom analytics event for this request; a no-op when analytics is off. Never throws.
2991
+ capture: clientCapture
1529
2992
  };
1530
2993
  request.userData = {
1531
2994
  ...request.userData,
@@ -1538,6 +3001,7 @@ var FetchBrain = class {
1538
3001
  if (config.debug) logger.debug(`Recalled${urlSuffix(shownUrl())} [${handlerLabel || "default"}]`);
1539
3002
  if (originalPushData) {
1540
3003
  await originalPushData.call(context, aiResult.data);
3004
+ noteRecords(aLabel, recordCount(aiResult.data));
1541
3005
  }
1542
3006
  try {
1543
3007
  if (!request.userData?.__fetchBrainCounted) {
@@ -1555,6 +3019,10 @@ var FetchBrain = class {
1555
3019
  logger.debug(`Run stats skipped: ${countErr}`);
1556
3020
  }
1557
3021
  await fireOnRecalled(aiResult.data);
3022
+ if (analyticsOn) {
3023
+ const fetchSkipped = request.skipNavigation === true;
3024
+ recordSuccess(context, fetchSkipped ? "skipped" : "recalled", void 0, recallMs);
3025
+ }
1558
3026
  return;
1559
3027
  }
1560
3028
  const counts = labelCounts(request.label);
@@ -1567,22 +3035,27 @@ var FetchBrain = class {
1567
3035
  logger.debug(`Learning${urlSuffix(shownUrl())}`);
1568
3036
  }
1569
3037
  const learnItems = [];
1570
- if (originalPushData && config.learning !== false) {
3038
+ if (originalPushData && (config.learning !== false || collector)) {
1571
3039
  context.pushData = async (data) => {
1572
- if (!usedAIData && (!aiResult.known || relearn)) {
3040
+ if (config.learning !== false && !usedAIData && (!aiResult.known || relearn)) {
1573
3041
  learnItems.push(...Array.isArray(data) ? data : [data]);
1574
3042
  }
1575
- return originalPushData.call(context, data);
3043
+ const res = await originalPushData.call(context, data);
3044
+ noteRecords(aLabel, recordCount(data));
3045
+ return res;
1576
3046
  };
1577
3047
  }
3048
+ const flushFanOut = collector ? wrapFanOut(context, aLabel) : void 0;
1578
3049
  const requestContext = {
1579
3050
  request: rawRequest,
1580
3051
  client,
1581
3052
  learning: config.learning !== false,
1582
3053
  aiKnown: aiResult.known,
1583
3054
  relearn,
1584
- items: learnItems
3055
+ items: learnItems,
3056
+ ...collector ? { capture: captureFor(context, request, aLabel), records: (n) => noteRecords(aLabel, n) } : {}
1585
3057
  };
3058
+ const h0 = analyticsOn ? performance.now() : 0;
1586
3059
  try {
1587
3060
  await asyncContext.run(requestContext, async () => {
1588
3061
  await originalHandler.call(crawler, context);
@@ -1590,6 +3063,9 @@ var FetchBrain = class {
1590
3063
  } catch (handlerErr) {
1591
3064
  if (counts) counts.failed++;
1592
3065
  throw handlerErr;
3066
+ } finally {
3067
+ if (analyticsOn) handlerMs = msSince(h0);
3068
+ flushFanOut?.();
1593
3069
  }
1594
3070
  try {
1595
3071
  if (!request.userData?.__fetchBrainCounted) {
@@ -1611,75 +3087,16 @@ var FetchBrain = class {
1611
3087
  pendingLearns.add(pending);
1612
3088
  void pending.finally(() => pendingLearns.delete(pending));
1613
3089
  }
1614
- if (telemetryConfig.enabled) {
1615
- try {
1616
- const telemetry = await collectTelemetry(
1617
- {
1618
- request: {
1619
- url,
1620
- retryCount: request.retryCount,
1621
- label,
1622
- userData: request.userData
1623
- },
1624
- response: {
1625
- statusCode: context.response?.statusCode || context.response?.status
1626
- },
1627
- proxyInfo: context.proxyInfo ? {
1628
- url: context.proxyInfo.url,
1629
- hostname: context.proxyInfo.hostname,
1630
- countryCode: context.proxyInfo.countryCode
1631
- } : void 0,
1632
- session: context.session ? {
1633
- errorScore: context.session.errorScore,
1634
- usageCount: context.session.usageCount
1635
- } : void 0,
1636
- crawler: {
1637
- constructor: { name: crawlerType }
1638
- }
1639
- },
1640
- {
1641
- startTime,
1642
- endTime: Date.now(),
1643
- responseTime: Date.now() - startTime,
1644
- contentSize: context.response?.body?.length
1645
- },
1646
- telemetryConfig
1647
- );
1648
- if (telemetry) {
1649
- telemetryBuffer.add(telemetry);
1650
- }
1651
- } catch (err) {
1652
- logger.debug(`Telemetry collection error: ${err}`);
1653
- }
1654
- }
3090
+ if (analyticsOn) recordSuccess(context, "scraped", handlerMs, recallMs);
1655
3091
  } catch (err) {
1656
3092
  if (consumedStash) {
1657
3093
  stashSet(stashKey(rawRequest), consumedStash);
1658
3094
  }
1659
- if (telemetryConfig.enabled) {
3095
+ if (analyticsOn && collector) {
1660
3096
  try {
1661
- const telemetry = await collectTelemetry(
1662
- {
1663
- request: {
1664
- url,
1665
- retryCount: request.retryCount,
1666
- label
1667
- },
1668
- crawler: {
1669
- constructor: { name: crawlerType }
1670
- }
1671
- },
1672
- {
1673
- startTime,
1674
- endTime: Date.now(),
1675
- responseTime: Date.now() - startTime
1676
- },
1677
- telemetryConfig,
1678
- err instanceof Error ? err : new Error(String(err))
1679
- );
1680
- if (telemetry) {
1681
- telemetryBuffer.add(telemetry);
1682
- }
3097
+ const a = attemptOf(context);
3098
+ a.handlerMs = handlerMs;
3099
+ a.recallMs = recallMs;
1683
3100
  } catch {
1684
3101
  }
1685
3102
  }
@@ -1691,10 +3108,64 @@ var FetchBrain = class {
1691
3108
  const crawlerAny = crawler;
1692
3109
  crawlerAny[handlerKey] = wrappedHandler;
1693
3110
  logger.debug(`Wrapped ${handlerKey}`);
3111
+ if (analyticsOn) {
3112
+ const preNav = (ctx) => {
3113
+ if (!collector) return;
3114
+ try {
3115
+ attemptOf(ctx).navStart = performance.now();
3116
+ } catch {
3117
+ }
3118
+ };
3119
+ const postNav = (ctx) => {
3120
+ if (!collector) return;
3121
+ try {
3122
+ const a = attemptOf(ctx);
3123
+ if (a.navStart !== void 0) a.navMs = msSince(a.navStart);
3124
+ a.statusCode = statusFrom(ctx.response);
3125
+ a.bytes = headerBytes(ctx.response);
3126
+ } catch {
3127
+ }
3128
+ };
3129
+ if (Array.isArray(crawlerAny.preNavigationHooks)) {
3130
+ crawlerAny.preNavigationHooks = [...crawlerAny.preNavigationHooks, preNav];
3131
+ }
3132
+ if (Array.isArray(crawlerAny.postNavigationHooks)) {
3133
+ crawlerAny.postNavigationHooks = [postNav, ...crawlerAny.postNavigationHooks];
3134
+ }
3135
+ const userErrorHandler = crawlerAny.errorHandler;
3136
+ crawlerAny.errorHandler = function(...args) {
3137
+ const c = collector;
3138
+ if (c) {
3139
+ try {
3140
+ noteFailure(c, args[0], args[1]);
3141
+ } catch (analyticsErr) {
3142
+ logger.debug(`Analytics skipped: ${analyticsErr}`);
3143
+ }
3144
+ }
3145
+ return typeof userErrorHandler === "function" ? userErrorHandler.apply(this, args) : void 0;
3146
+ };
3147
+ const userFailedHandler = crawlerAny.failedRequestHandler;
3148
+ crawlerAny.failedRequestHandler = function(...args) {
3149
+ const c = collector;
3150
+ if (c) {
3151
+ try {
3152
+ const ctx = args[0];
3153
+ const { a, blockType } = noteFailure(c, ctx, args[1]);
3154
+ const req = ctx.request;
3155
+ c.error(analyticsLabel(req.label), args[1], contextFor(c, a, req));
3156
+ emitRequest(c, ctx, a, blockType ? "blocked" : "failed", blockType);
3157
+ } catch (analyticsErr) {
3158
+ logger.debug(`Analytics skipped: ${analyticsErr}`);
3159
+ }
3160
+ }
3161
+ return typeof userFailedHandler === "function" ? userFailedHandler.apply(this, args) : void 0;
3162
+ };
3163
+ }
1694
3164
  if (typeof crawlerAny.run === "function") {
1695
3165
  const originalRun = crawlerAny.run.bind(crawlerAny);
1696
3166
  crawlerAny.run = async (...args) => {
1697
3167
  runStats.startTime = Date.now();
3168
+ safeBeginRun(client);
1698
3169
  const runStartedAt = new Date(runStats.startTime).toISOString();
1699
3170
  labelStats.clear();
1700
3171
  const runBase = {
@@ -1710,94 +3181,190 @@ var FetchBrain = class {
1710
3181
  };
1711
3182
  const changeBase = safeChangeStats(client);
1712
3183
  const runId = nextRunId();
3184
+ let analyticsQueue;
3185
+ let reportClient;
3186
+ let reportAnalytics;
3187
+ if (analyticsOn) {
3188
+ try {
3189
+ const [mod, cfg] = await Promise.all([loadCollector(), fetchAnalyticsConfig(client)]);
3190
+ if (mod && cfg?.enabled !== false) {
3191
+ const analyticsRunId = runId;
3192
+ const scraper = client.getScraperName();
3193
+ const batchStartSeq = mod.startSeqFromEnv();
3194
+ analyticsQueue = new mod.AnalyticsQueue(
3195
+ (gz, signal) => client.postAnalyticsEvents(gz, analyticsRunId, signal),
3196
+ {
3197
+ wrap: (events, seq) => ({ runId: analyticsRunId, scraper, seq, events }),
3198
+ // Unique across Apify migrations: a restarted process must not reuse the earlier seqs.
3199
+ startSeq: batchStartSeq
3200
+ }
3201
+ );
3202
+ if (cfg) {
3203
+ if (Number.isFinite(cfg.sampleRate) && cfg.sampleRate > 0 && cfg.sampleRate <= 1) {
3204
+ analyticsQueue.sampleRate = cfg.sampleRate;
3205
+ }
3206
+ if (typeof cfg.pauseUntil === "number") analyticsQueue.pause(cfg.pauseUntil);
3207
+ }
3208
+ const apifyUserId = process.env.APIFY_USER_ID;
3209
+ const clientHash = apifyUserId && cfg?.salt ? mod.Collector.hashClient(apifyUserId, cfg.salt) : void 0;
3210
+ collector = new mod.Collector(
3211
+ analyticsQueue,
3212
+ {
3213
+ runId: analyticsRunId,
3214
+ scraper,
3215
+ ...clientHash ? { client: clientHash } : {},
3216
+ crawlerType,
3217
+ sdkVersion: mod.SDK_VERSION,
3218
+ platform: process.env.APIFY_IS_AT_HOME || process.env.APIFY_ACTOR_ID ? "apify" : "other"
3219
+ },
3220
+ {
3221
+ debug: (msg) => logger.debug(msg),
3222
+ // Event seqs after a migration start above the earlier process's (batch seq
3223
+ // is whole seconds x 1000, so x 1000 again leaves 1e6 events per second of run).
3224
+ startSeq: batchStartSeq * 1e3
3225
+ }
3226
+ );
3227
+ reportClient = clientHash;
3228
+ const quotaSeen = /* @__PURE__ */ new Set();
3229
+ safeOnQuotaReached(client, (cap) => {
3230
+ if (quotaSeen.has(cap)) return;
3231
+ quotaSeen.add(cap);
3232
+ collector?.quotaReached(cap);
3233
+ });
3234
+ blockedByRequest.clear();
3235
+ emittedThenFailed.clear();
3236
+ const memoryMb = Number(process.env.APIFY_MEMORY_MBYTES);
3237
+ const maxConcurrency = crawlerAny.autoscaledPoolOptions?.maxConcurrency;
3238
+ collector.runStarted({
3239
+ memoryMb: Number.isFinite(memoryMb) && memoryMb > 0 ? memoryMb : void 0,
3240
+ maxConcurrency: typeof maxConcurrency === "number" ? maxConcurrency : void 0
3241
+ });
3242
+ analyticsQueue.start();
3243
+ }
3244
+ } catch (analyticsErr) {
3245
+ collector = void 0;
3246
+ analyticsQueue = void 0;
3247
+ reportClient = void 0;
3248
+ safeOnQuotaReached(client, void 0);
3249
+ logger.debug(`Analytics off for this run: ${analyticsErr}`);
3250
+ }
3251
+ }
1713
3252
  try {
1714
3253
  const result = await originalRun(...args);
1715
3254
  return result;
1716
3255
  } finally {
1717
- logger.debug("Flushing pending learn requests on crawl complete");
1718
- await client.flushLearnBatch();
1719
- await Promise.allSettled([...pendingLearns]);
1720
- if (telemetryConfig.enabled) {
1721
- logger.debug("Telemetry: flushing on crawl complete");
1722
- await telemetryBuffer.stop();
3256
+ let analyticsStop;
3257
+ if (analyticsQueue) {
3258
+ try {
3259
+ collector?.runFinished({ durationMs: Date.now() - runStats.startTime });
3260
+ if (collector) reportAnalytics = { labels: collector.labelStats(), ...collector.aggregateReport() };
3261
+ } catch (analyticsErr) {
3262
+ logger.debug(`Analytics skipped: ${analyticsErr}`);
3263
+ }
3264
+ analyticsStop = analyticsQueue.stop().catch((analyticsErr) => {
3265
+ logger.debug(`Analytics flush skipped: ${analyticsErr}`);
3266
+ });
3267
+ collector = void 0;
1723
3268
  }
1724
- const duration = ((Date.now() - runStats.startTime) / 1e3).toFixed(
1725
- 1
1726
- );
1727
- const run = {
1728
- totalRequests: runStats.totalRequests - runBase.totalRequests,
1729
- bypassed: runStats.bypassed - runBase.bypassed,
1730
- dropped: runStats.dropped - runBase.dropped,
1731
- scraped: runStats.scraped - runBase.scraped,
1732
- learned: runStats.learned - runBase.learned,
1733
- recalled: runStats.recalled - runBase.recalled,
1734
- aiSkipped: runStats.aiSkipped - runBase.aiSkipped,
1735
- requestsSkipped: runStats.requestsSkipped - runBase.requestsSkipped,
1736
- lateRecalls: runStats.lateRecalls - runBase.lateRecalls
1737
- };
1738
- const managedRequests = run.totalRequests - run.bypassed;
1739
- const savingsPercent = managedRequests > 0 ? (run.aiSkipped / managedRequests * 100).toFixed(1) : "0";
1740
- let changes = { changed: 0, drift: [] };
1741
3269
  try {
1742
- const now = safeChangeStats(client);
1743
- const key = (d) => `${d.label}\0${d.field}\0${d.kind}`;
1744
- const seen = new Set(changeBase.drift.map(key));
1745
- changes = {
1746
- changed: Math.max(0, now.changed - changeBase.changed) || 0,
1747
- drift: now.drift.filter((d) => !seen.has(key(d)))
1748
- };
1749
- } catch (diffErr) {
1750
- logger.debug(`Change summary skipped: ${diffErr}`);
1751
- }
1752
- const showChanged = config.changeDetection?.enabled === true || changes.changed > 0;
1753
- logger.info(
1754
- `\u{1F9E0} Finished! recalled: ${run.recalled}/${managedRequests} (${savingsPercent}%), requests skipped: ${run.requestsSkipped}, learned: ${run.learned}, scraped: ${run.scraped}` + (skipLabels ? `, bypassed: ${run.bypassed}` : "") + (run.dropped ? `, dropped: ${run.dropped}` : "") + (showChanged ? `, changed: ${changes.changed}` : "") + `, duration: ${duration}s`
1755
- );
1756
- if (run.lateRecalls > 0 && !crawlerAny.retryOnBlocked && config.preRecall !== false) {
1757
- logger.info(
1758
- `${run.lateRecalls} ${run.lateRecalls === 1 ? "page was" : "pages were"} recalled after ${run.lateRecalls === 1 ? "it was" : "they were"} fetched; enqueue them with context.crawler.addRequests([...]) to skip the fetch (non-GET requests also need an explicit uniqueKey).`
3270
+ safeOnQuotaReached(client, void 0);
3271
+ logger.debug("Flushing pending learn requests on crawl complete");
3272
+ await client.flushLearnBatch();
3273
+ await Promise.allSettled([...pendingLearns]);
3274
+ const duration = ((Date.now() - runStats.startTime) / 1e3).toFixed(
3275
+ 1
1759
3276
  );
1760
- }
1761
- for (const item of changes.drift) {
3277
+ const run = {
3278
+ totalRequests: runStats.totalRequests - runBase.totalRequests,
3279
+ bypassed: runStats.bypassed - runBase.bypassed,
3280
+ dropped: runStats.dropped - runBase.dropped,
3281
+ scraped: runStats.scraped - runBase.scraped,
3282
+ learned: runStats.learned - runBase.learned,
3283
+ recalled: runStats.recalled - runBase.recalled,
3284
+ aiSkipped: runStats.aiSkipped - runBase.aiSkipped,
3285
+ requestsSkipped: runStats.requestsSkipped - runBase.requestsSkipped,
3286
+ lateRecalls: runStats.lateRecalls - runBase.lateRecalls
3287
+ };
3288
+ const managedRequests = run.totalRequests - run.bypassed;
3289
+ const savingsPercent = managedRequests > 0 ? (run.aiSkipped / managedRequests * 100).toFixed(1) : "0";
3290
+ let changes = { changed: 0, drift: [], known: 0 };
1762
3291
  try {
1763
- logger.warn(describeDrift(item));
1764
- } catch (warnErr) {
1765
- logger.debug(`Drift warning skipped: ${warnErr}`);
3292
+ const now = safeChangeStats(client);
3293
+ const key = (d) => `${d.label}\0${d.field}\0${d.kind}`;
3294
+ const seen = new Set(changeBase.drift.map(key));
3295
+ changes = {
3296
+ changed: Math.max(0, now.changed - changeBase.changed) || 0,
3297
+ drift: now.drift.filter((d) => !seen.has(key(d))),
3298
+ known: Math.max(0, (now.known ?? 0) - (changeBase.known ?? 0)) || 0
3299
+ };
3300
+ } catch (diffErr) {
3301
+ logger.debug(`Change summary skipped: ${diffErr}`);
1766
3302
  }
1767
- }
1768
- if (config.reportRuns !== false) {
1769
- try {
1770
- const labels = Object.fromEntries(labelStats);
1771
- const flags = await client.reportRun({
1772
- runId,
1773
- build: config.refreshOnRebuild ? getPlatformBuildId() : void 0,
1774
- startedAt: runStartedAt,
1775
- endedAt: (/* @__PURE__ */ new Date()).toISOString(),
1776
- scraped: run.scraped,
1777
- learned: run.learned,
1778
- recalled: run.recalled,
1779
- requestsSkipped: run.requestsSkipped,
1780
- lateRecalls: run.lateRecalls,
1781
- bypassed: run.bypassed,
1782
- labels
1783
- });
1784
- for (const flag of Array.isArray(flags) ? flags : []) {
1785
- if (!flag || flag.kind !== "failed_pages" && flag.kind !== "empty_pages" || typeof flag.rate !== "number" || !Number.isFinite(flag.rate)) {
1786
- continue;
1787
- }
1788
- const label = clipText(flag.label, 64);
1789
- logger.warn(
1790
- flag.kind === "failed_pages" ? `\u26A0\uFE0F ${pct(flag.rate)} of ${label} pages failed` : `\u26A0\uFE0F ${pct(flag.rate)} of ${label} pages pushed no data`
3303
+ const showChanged = observe || config.changeDetection?.enabled === true || changes.changed > 0;
3304
+ if (observe) {
3305
+ logger.info(
3306
+ `\u{1F440} Observe run finished: learned: ${run.learned}, scraped: ${run.scraped}, changed: ${changes.changed}` + (skipLabels ? `, bypassed: ${run.bypassed}` : "") + `, duration: ${duration}s`
3307
+ );
3308
+ if (changes.known > 0) {
3309
+ logger.info(
3310
+ `${changes.known} ${changes.known === 1 ? "page was" : "pages were"} already known \u2014 recall (the default) would have skipped ${changes.known === 1 ? "that fetch" : "those fetches"}.`
1791
3311
  );
1792
3312
  }
1793
- } catch (reportErr) {
1794
- logger.debug(`Run report skipped: ${reportErr}`);
3313
+ } else logger.info(
3314
+ `\u{1F9E0} Finished! recalled: ${run.recalled}/${managedRequests} ` + (safeQuotaState(client) === "recall_cap" ? "(monthly recall limit reached)" : `(${savingsPercent}%)`) + `, requests skipped: ${run.requestsSkipped}, learned: ${run.learned}, scraped: ${run.scraped}` + (skipLabels ? `, bypassed: ${run.bypassed}` : "") + (run.dropped ? `, dropped: ${run.dropped}` : "") + (showChanged ? `, changed: ${changes.changed}` : "") + `, duration: ${duration}s`
3315
+ );
3316
+ if (!observe && run.lateRecalls > 0 && !crawlerAny.retryOnBlocked && config.preRecall !== false) {
3317
+ logger.info(
3318
+ `${run.lateRecalls} ${run.lateRecalls === 1 ? "page was" : "pages were"} recalled after ${run.lateRecalls === 1 ? "it was" : "they were"} fetched; enqueue them with context.crawler.addRequests([...]) to skip the fetch (non-GET requests also need an explicit uniqueKey).`
3319
+ );
3320
+ }
3321
+ for (const item of changes.drift) {
3322
+ try {
3323
+ logger.warn(describeDrift(item));
3324
+ } catch (warnErr) {
3325
+ logger.debug(`Drift warning skipped: ${warnErr}`);
3326
+ }
3327
+ }
3328
+ if (config.reportRuns !== false) {
3329
+ try {
3330
+ const labels = Object.fromEntries(labelStats);
3331
+ const flags = await client.reportRun({
3332
+ runId,
3333
+ build: config.refreshOnRebuild ? getPlatformBuildId() : void 0,
3334
+ startedAt: runStartedAt,
3335
+ endedAt: (/* @__PURE__ */ new Date()).toISOString(),
3336
+ scraped: run.scraped,
3337
+ learned: run.learned,
3338
+ recalled: run.recalled,
3339
+ requestsSkipped: run.requestsSkipped,
3340
+ // recall:false: pages memory already knew were fetched anyway —
3341
+ // the same untapped savings late recalls report.
3342
+ lateRecalls: observe ? changes.known : run.lateRecalls,
3343
+ bypassed: run.bypassed,
3344
+ labels,
3345
+ ...reportClient ? { client: reportClient } : {},
3346
+ ...reportAnalytics ? { analytics: reportAnalytics } : {}
3347
+ });
3348
+ for (const flag of Array.isArray(flags) ? flags : []) {
3349
+ if (!flag || flag.kind !== "failed_pages" && flag.kind !== "empty_pages" || typeof flag.rate !== "number" || !Number.isFinite(flag.rate)) {
3350
+ continue;
3351
+ }
3352
+ const label = clipText(flag.label, 64);
3353
+ logger.warn(
3354
+ flag.kind === "failed_pages" ? `\u26A0\uFE0F ${pct(flag.rate)} of ${label} pages failed` : `\u26A0\uFE0F ${pct(flag.rate)} of ${label} pages pushed no data`
3355
+ );
3356
+ }
3357
+ } catch (reportErr) {
3358
+ logger.debug(`Run report skipped: ${reportErr}`);
3359
+ }
1795
3360
  }
3361
+ } finally {
3362
+ await analyticsStop;
1796
3363
  }
1797
3364
  }
1798
3365
  };
1799
3366
  }
1800
- if (config.preRecall !== false && typeof crawlerAny.addRequests === "function") {
3367
+ if (!observe && config.preRecall !== false && typeof crawlerAny.addRequests === "function") {
1801
3368
  const originalAddRequests = crawlerAny.addRequests.bind(crawlerAny);
1802
3369
  if (crawlerAny.retryOnBlocked) {
1803
3370
  logger.info(
@@ -1926,14 +3493,23 @@ async function pushData(data, dataset, datasetName) {
1926
3493
  } else {
1927
3494
  await dataset.pushData(data);
1928
3495
  }
3496
+ try {
3497
+ ctx?.records?.(Array.isArray(data) ? data.length : 1);
3498
+ } catch {
3499
+ }
3500
+ }
3501
+ function capture(name, props) {
3502
+ try {
3503
+ asyncContext.getStore()?.capture?.(name, props);
3504
+ } catch {
3505
+ }
1929
3506
  }
1930
3507
 
1931
3508
  exports.CircuitBreaker = CircuitBreaker;
1932
3509
  exports.FetchBrain = FetchBrain;
1933
3510
  exports.FetchBrainClient = FetchBrainClient;
1934
3511
  exports.RequestBatcher = RequestBatcher;
1935
- exports.TelemetryBuffer = TelemetryBuffer;
1936
- exports.collectTelemetry = collectTelemetry;
3512
+ exports.capture = capture;
1937
3513
  exports.createFetchBrain = createFetchBrain;
1938
3514
  exports.createLogger = createLogger;
1939
3515
  exports.getCurrentContext = getCurrentContext;