@fetchbrain.com/sdk 0.1.7 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -108,24 +108,23 @@ var RequestBatcher = class {
108
108
  constructor(executor, config = {}, logger) {
109
109
  this.queue = [];
110
110
  this.flushTimeout = null;
111
+ this.refSeq = 0;
111
112
  this.executor = executor;
112
113
  this.config = { ...DEFAULT_CONFIG2, ...config };
113
114
  this.logger = logger;
114
115
  }
115
116
  /**
116
- * Add a URL to the batch queue
117
+ * Add a request to the batch queue
117
118
  */
118
- async query(url) {
119
+ async query(request) {
119
120
  return new Promise((resolve, reject) => {
120
- this.queue.push({ url, resolve, reject });
121
+ this.queue.push({ ref: String(this.refSeq++), request, resolve, reject });
121
122
  if (this.queue.length >= this.config.maxSize) {
122
123
  this.flush();
123
124
  return;
124
125
  }
125
126
  if (!this.flushTimeout) {
126
- this.flushTimeout = setTimeout(() => {
127
- this.flush();
128
- }, this.config.maxWait);
127
+ this.flushTimeout = setTimeout(() => this.flush(), this.config.maxWait);
129
128
  }
130
129
  });
131
130
  }
@@ -141,27 +140,20 @@ var RequestBatcher = class {
141
140
  return;
142
141
  }
143
142
  const batch = this.queue.splice(0, this.config.maxSize);
144
- const urls = batch.map((r) => r.url);
145
- this.logger.debug(`Flushing batch of ${urls.length} URLs`);
143
+ const items = batch.map((r) => ({ ref: r.ref, request: r.request }));
144
+ this.logger.debug(`Flushing batch of ${items.length} requests`);
146
145
  try {
147
- const results = await this.executor(urls);
148
- for (const request of batch) {
149
- const result = results.get(request.url);
150
- if (result) {
151
- request.resolve(result);
152
- } else {
153
- request.resolve({ known: false });
154
- }
146
+ const results = await this.executor(items);
147
+ for (const r of batch) {
148
+ r.resolve(results.get(r.ref) ?? { known: false });
155
149
  }
156
150
  } catch (error) {
157
- for (const request of batch) {
158
- request.reject(error);
151
+ for (const r of batch) {
152
+ r.reject(error);
159
153
  }
160
154
  }
161
155
  if (this.queue.length > 0) {
162
- this.flushTimeout = setTimeout(() => {
163
- this.flush();
164
- }, this.config.maxWait);
156
+ this.flushTimeout = setTimeout(() => this.flush(), this.config.maxWait);
165
157
  }
166
158
  }
167
159
  /**
@@ -178,8 +170,8 @@ var RequestBatcher = class {
178
170
  clearTimeout(this.flushTimeout);
179
171
  this.flushTimeout = null;
180
172
  }
181
- for (const request of this.queue) {
182
- request.resolve({ known: false, fallback: true });
173
+ for (const r of this.queue) {
174
+ r.resolve({ known: false, fallback: true });
183
175
  }
184
176
  this.queue = [];
185
177
  }
@@ -195,17 +187,15 @@ var LearnBatcher = class {
195
187
  /**
196
188
  * Add a learn entry to the batch queue
197
189
  */
198
- async learn(url, data) {
190
+ async learn(request, data) {
199
191
  return new Promise((resolve, reject) => {
200
- this.queue.push({ entry: { url, data }, resolve, reject });
192
+ this.queue.push({ entry: { request, data }, resolve, reject });
201
193
  if (this.queue.length >= this.config.maxSize) {
202
194
  this.flush();
203
195
  return;
204
196
  }
205
197
  if (!this.flushTimeout) {
206
- this.flushTimeout = setTimeout(() => {
207
- this.flush();
208
- }, this.config.maxWait);
198
+ this.flushTimeout = setTimeout(() => this.flush(), this.config.maxWait);
209
199
  }
210
200
  });
211
201
  }
@@ -225,18 +215,16 @@ var LearnBatcher = class {
225
215
  this.logger.debug(`Flushing learn batch of ${entries.length} entries`);
226
216
  try {
227
217
  const result = await this.executor(entries);
228
- for (const request of batch) {
229
- request.resolve(result);
218
+ for (const r of batch) {
219
+ r.resolve(result);
230
220
  }
231
221
  } catch (error) {
232
- for (const request of batch) {
233
- request.reject(error);
222
+ for (const r of batch) {
223
+ r.reject(error);
234
224
  }
235
225
  }
236
226
  if (this.queue.length > 0) {
237
- this.flushTimeout = setTimeout(() => {
238
- this.flush();
239
- }, this.config.maxWait);
227
+ this.flushTimeout = setTimeout(() => this.flush(), this.config.maxWait);
240
228
  }
241
229
  }
242
230
  /**
@@ -261,8 +249,8 @@ var LearnBatcher = class {
261
249
  clearTimeout(this.flushTimeout);
262
250
  this.flushTimeout = null;
263
251
  }
264
- for (const request of this.queue) {
265
- request.resolve({ status: "rejected", learned: 0 });
252
+ for (const r of this.queue) {
253
+ r.resolve({ status: "rejected", learned: 0 });
266
254
  }
267
255
  this.queue = [];
268
256
  }
@@ -363,7 +351,7 @@ var FetchBrainClient = class {
363
351
  this.logger
364
352
  );
365
353
  this.batcher = new RequestBatcher(
366
- (urls) => this.executeBatchQuery(urls),
354
+ (items) => this.executeBatchQuery(items),
367
355
  this.config.batch,
368
356
  this.logger
369
357
  );
@@ -374,56 +362,48 @@ var FetchBrainClient = class {
374
362
  );
375
363
  }
376
364
  /**
377
- * Query if FetchBrain "knows" a URL
365
+ * Query if FetchBrain "knows" a request
378
366
  */
379
- async query(url) {
367
+ async query(request) {
380
368
  if (this.circuitBreaker.isOpen()) {
381
- this.logger.debug(`Circuit open, skipping query for: ${url}`);
382
369
  return { known: false, fallback: true };
383
370
  }
384
371
  try {
385
- return await this.batcher.query(url);
372
+ return await this.batcher.query(request);
386
373
  } catch (error) {
387
- this.logger.debug(`Query failed for ${url}:`, error);
374
+ this.logger.debug("Query failed:", error);
388
375
  return { known: false, fallback: true };
389
376
  }
390
377
  }
391
378
  /**
392
- * Query multiple URLs at once (bypass batcher for bulk operations)
379
+ * Query multiple requests at once — returns ordered array matching input order
393
380
  */
394
- async queryBulk(urls) {
381
+ async queryBulk(requests) {
395
382
  if (this.circuitBreaker.isOpen()) {
396
- this.logger.debug(`Circuit open, skipping bulk query`);
397
- return new Map(
398
- urls.map((url) => [url, { known: false, fallback: true }])
399
- );
383
+ return requests.map(() => ({ known: false, fallback: true }));
400
384
  }
401
385
  try {
402
- return await this.executeBatchQuery(urls);
403
- } catch (error) {
404
- this.logger.debug(`Bulk query failed:`, error);
405
- return new Map(
406
- urls.map((url) => [url, { known: false, fallback: true }])
407
- );
386
+ const items = requests.map((request, i) => ({ ref: String(i), request }));
387
+ const results = await this.executeBatchQuery(items);
388
+ return items.map((i) => results.get(i.ref) ?? { known: false });
389
+ } catch {
390
+ return requests.map(() => ({ known: false, fallback: true }));
408
391
  }
409
392
  }
410
393
  /**
411
394
  * "Teach" FetchBrain new data (batched for high-concurrency)
412
395
  */
413
- async learn(url, data) {
396
+ async learn(request, data) {
414
397
  if (!this.config.learning) {
415
398
  return { status: "rejected", learned: 0 };
416
399
  }
417
400
  if (this.circuitBreaker.isOpen()) {
418
- this.logger.debug(`Circuit open, skipping learn for: ${url}`);
419
401
  return { status: "rejected", learned: 0 };
420
402
  }
421
403
  try {
422
- const response = await this.learnBatcher.learn(url, data);
423
- this.logger.debug(`Learned data for: ${url}`);
424
- return response;
404
+ return await this.learnBatcher.learn(request, data);
425
405
  } catch (error) {
426
- this.logger.warn(`Learn failed for ${url}:`, error);
406
+ this.logger.warn("Learn failed:", error);
427
407
  return { status: "rejected", learned: 0 };
428
408
  }
429
409
  }
@@ -449,10 +429,10 @@ var FetchBrainClient = class {
449
429
  /**
450
430
  * Execute a batch query against the API
451
431
  */
452
- async executeBatchQuery(urls) {
432
+ async executeBatchQuery(items) {
453
433
  const results = /* @__PURE__ */ new Map();
454
434
  const request = {
455
- urls,
435
+ items,
456
436
  intelligence: this.config.intelligence
457
437
  };
458
438
  if (this.config.refreshOnRebuild && process.env.APIFY_ACTOR_BUILD_ID) {
@@ -465,14 +445,10 @@ var FetchBrainClient = class {
465
445
  });
466
446
  this.circuitBreaker.recordSuccess();
467
447
  for (const item of response.known) {
468
- results.set(item.url, {
469
- known: true,
470
- data: item.data,
471
- confidence: item.confidence
472
- });
448
+ results.set(item.ref, { known: true, data: item.data, confidence: item.confidence });
473
449
  }
474
- for (const url of response.unknown) {
475
- results.set(url, { known: false });
450
+ for (const ref of response.unknown) {
451
+ results.set(ref, { known: false });
476
452
  }
477
453
  return results;
478
454
  } catch (error) {
@@ -484,23 +460,20 @@ var FetchBrainClient = class {
484
460
  * Execute a batch learn against the API
485
461
  */
486
462
  async executeBatchLearn(entries) {
487
- const processedEntries = entries.map((entry) => ({
488
- url: entry.url,
489
- data: this.config.extractForLearning ? this.config.extractForLearning(entry.data) : entry.data
463
+ const processed = entries.map((e) => ({
464
+ request: e.request,
465
+ data: this.config.extractForLearning ? this.config.extractForLearning(e.data) : e.data
490
466
  }));
491
467
  try {
492
468
  const response = await this.makeRequest(
493
469
  "/v1/learn",
494
470
  {
495
471
  method: "POST",
496
- body: JSON.stringify({
497
- entries: processedEntries
498
- })
472
+ body: JSON.stringify({ entries: processed })
499
473
  },
500
474
  DEFAULT_LEARN_TIMEOUT
501
475
  );
502
476
  this.circuitBreaker.recordSuccess();
503
- this.logger.debug(`Batch learned ${entries.length} entries`);
504
477
  return response;
505
478
  } catch (error) {
506
479
  this.circuitBreaker.recordFailure();
@@ -764,6 +737,36 @@ var TelemetryBuffer = class {
764
737
  };
765
738
 
766
739
  // src/enhance.ts
740
+ var STRIP_HEADERS = /* @__PURE__ */ new Set(["authorization", "cookie", "set-cookie"]);
741
+ var SDK_USERDATA_KEYS = /* @__PURE__ */ new Set(["fetchBrainKnown", "fetchBrainData", "__fetchBrainResult"]);
742
+ function buildRawRequest(request) {
743
+ const r = request;
744
+ let headers;
745
+ if (r.headers) {
746
+ headers = {};
747
+ for (const [k, v] of Object.entries(r.headers)) {
748
+ if (!STRIP_HEADERS.has(k.toLowerCase()) && typeof v === "string") headers[k] = v;
749
+ }
750
+ if (Object.keys(headers).length === 0) headers = void 0;
751
+ }
752
+ let userData;
753
+ if (r.userData) {
754
+ userData = {};
755
+ for (const [k, v] of Object.entries(r.userData)) if (!SDK_USERDATA_KEYS.has(k)) userData[k] = v;
756
+ if (Object.keys(userData).length === 0) userData = void 0;
757
+ }
758
+ let body;
759
+ if (typeof r.payload === "string") body = r.payload;
760
+ return { url: r.url, method: r.method, uniqueKey: r.uniqueKey, body, headers, userData, label: r.label };
761
+ }
762
+ function warnDefaultUniqueKey(request, logger, warned) {
763
+ const method = (request.method ?? "GET").toUpperCase();
764
+ const isDefault = !request.uniqueKey || request.uniqueKey === request.url;
765
+ if (method !== "GET" && isDefault && !warned.has(request.url)) {
766
+ warned.add(request.url);
767
+ logger.warn(`FetchBrain: ${method} ${request.url} has a default uniqueKey \u2014 set request.uniqueKey to your stable identity, or these requests won't be cached separately.`);
768
+ }
769
+ }
767
770
  var asyncContext = new async_hooks.AsyncLocalStorage();
768
771
  function getCurrentContext() {
769
772
  return asyncContext.getStore();
@@ -779,7 +782,6 @@ function shouldRunHandler(alwaysRun, label) {
779
782
  const requestLabel = label || "default";
780
783
  return labels.includes(requestLabel);
781
784
  }
782
- var requestContextMap = /* @__PURE__ */ new WeakMap();
783
785
  var FetchBrain = class {
784
786
  constructor(config) {
785
787
  this.client = new FetchBrainClient(config);
@@ -789,7 +791,7 @@ var FetchBrain = class {
789
791
  * Query if FetchBrain "knows" a URL
790
792
  */
791
793
  async query(options) {
792
- const result = await this.client.query(options.url);
794
+ const result = await this.client.query({ url: options.url });
793
795
  return {
794
796
  known: result.known,
795
797
  data: result.data,
@@ -800,7 +802,7 @@ var FetchBrain = class {
800
802
  * "Teach" FetchBrain new data
801
803
  */
802
804
  async learn(options) {
803
- return this.client.learn(options.url, options.data);
805
+ return this.client.learn({ url: options.url }, options.data);
804
806
  }
805
807
  /**
806
808
  * Get usage statistics
@@ -848,6 +850,7 @@ var FetchBrain = class {
848
850
  return Object.assign(crawler, { fetchBrain: client });
849
851
  }
850
852
  const crawlerType = crawler.constructor?.name || "Unknown";
853
+ const warnedKeys = /* @__PURE__ */ new Set();
851
854
  const wrappedHandler = async (context) => {
852
855
  const { request } = context;
853
856
  const url = request.url;
@@ -859,8 +862,10 @@ var FetchBrain = class {
859
862
  label,
860
863
  url
861
864
  });
865
+ const rawRequest = buildRawRequest(request);
866
+ warnDefaultUniqueKey(rawRequest, logger, warnedKeys);
862
867
  try {
863
- const aiResult = await client.query(url);
868
+ const aiResult = await client.query(rawRequest);
864
869
  let usedAIData = false;
865
870
  const originalPushData = context.pushData;
866
871
  context.ai = {
@@ -904,20 +909,18 @@ var FetchBrain = class {
904
909
  } else {
905
910
  logger.debug(`Learning: ${url}`);
906
911
  }
907
- requestContextMap.set(context, url);
908
912
  if (originalPushData && config.learning !== false) {
909
913
  context.pushData = async (data) => {
910
914
  const shouldLearn = !usedAIData && !aiResult.known;
911
915
  if (shouldLearn) {
912
916
  runStats.learned++;
913
- const requestUrl = requestContextMap.get(context) || url;
914
- await client.learn(requestUrl, data);
917
+ await client.learn(rawRequest, data);
915
918
  }
916
919
  return originalPushData.call(context, data);
917
920
  };
918
921
  }
919
922
  const requestContext = {
920
- url,
923
+ request: rawRequest,
921
924
  client,
922
925
  learning: config.learning !== false,
923
926
  aiKnown: aiResult.known
@@ -925,7 +928,6 @@ var FetchBrain = class {
925
928
  await asyncContext.run(requestContext, async () => {
926
929
  await originalHandler.call(crawler, context);
927
930
  });
928
- requestContextMap.delete(context);
929
931
  if (config.telemetry?.enabled) {
930
932
  try {
931
933
  const telemetry = await collectTelemetry(
@@ -1042,7 +1044,7 @@ async function pushData(data, dataset, datasetName) {
1042
1044
  if (ctx && ctx.learning && !ctx.aiKnown) {
1043
1045
  const items = Array.isArray(data) ? data : [data];
1044
1046
  for (const item of items) {
1045
- await ctx.client.learn(ctx.url, item);
1047
+ await ctx.client.learn(ctx.request, item);
1046
1048
  }
1047
1049
  }
1048
1050
  if (datasetName && dataset.open) {