scrapebadger 0.78.0 → 0.80.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.cjs CHANGED
@@ -1,15 +1,15 @@
1
1
  'use strict';
2
2
 
3
- var crypto = require('crypto');
4
3
  var events = require('events');
5
4
  var WebSocket = require('ws');
5
+ var crypto = require('crypto');
6
6
 
7
7
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
8
8
 
9
9
  var WebSocket__default = /*#__PURE__*/_interopDefault(WebSocket);
10
10
 
11
11
  // src/internal/version.ts
12
- var SDK_VERSION = "0.77.0";
12
+ var SDK_VERSION = "0.80.0";
13
13
 
14
14
  // src/internal/exceptions.ts
15
15
  var ScrapeBadgerError = class _ScrapeBadgerError extends Error {
@@ -167,6 +167,21 @@ var WebSocketStreamError = class _WebSocketStreamError extends ScrapeBadgerError
167
167
 
168
168
  // src/internal/client.ts
169
169
  var RETRYABLE_STATUS_CODES = [500, 502, 503, 504];
170
+ var NOT_SENT_CODES = /* @__PURE__ */ new Set([
171
+ "ECONNREFUSED",
172
+ "ENOTFOUND",
173
+ "EAI_AGAIN",
174
+ "EHOSTUNREACH",
175
+ "ENETUNREACH",
176
+ "UND_ERR_CONNECT_TIMEOUT"
177
+ ]);
178
+ function failedBeforeSend(error) {
179
+ const cause = error?.cause;
180
+ if (!cause) return false;
181
+ if (typeof cause.code === "string") return NOT_SENT_CODES.has(cause.code);
182
+ return Array.isArray(cause.errors) && cause.errors.length > 0 && cause.errors.every((e) => NOT_SENT_CODES.has(String(e?.code)));
183
+ }
184
+ var finalErrors = /* @__PURE__ */ new WeakSet();
170
185
  var BaseClient = class _BaseClient {
171
186
  config;
172
187
  constructor(config) {
@@ -218,11 +233,41 @@ var BaseClient = class _BaseClient {
218
233
  async requestWithHeaders(path, options = {}) {
219
234
  return this.requestRaw(path, options);
220
235
  }
236
+ /**
237
+ * Make an HTTP request and return its status, headers and body undigested:
238
+ * the body is JSON-decoded when the response is JSON, otherwise text (the
239
+ * normal path turns a non-JSON, non-HTML body into `{ detail }`). Error
240
+ * statuses still throw the matching typed error.
241
+ */
242
+ async requestResponse(path, options = {}) {
243
+ const { data } = await this.requestRaw(path, options, async (response) => {
244
+ if (!response.ok) {
245
+ try {
246
+ await this.handleResponse(response);
247
+ } catch (error) {
248
+ if (response.headers.get("Idempotent-Replayed")?.trim().toLowerCase() === "true") {
249
+ finalErrors.add(error);
250
+ }
251
+ throw error;
252
+ }
253
+ }
254
+ const text = await response.text();
255
+ let body = text;
256
+ if (response.headers.get("content-type")?.toLowerCase().includes("json")) {
257
+ try {
258
+ body = JSON.parse(text);
259
+ } catch {
260
+ }
261
+ }
262
+ return { status: response.status, headers: response.headers, body };
263
+ });
264
+ return data;
265
+ }
221
266
  /**
222
267
  * Internal method that builds the request and executes it, returning data and rate limit info.
223
268
  */
224
- async requestRaw(path, options = {}) {
225
- const { method = "GET", params, body, headers = {} } = options;
269
+ async requestRaw(path, options = {}, decode) {
270
+ const { method = "GET", params, body, headers = {}, timeoutMs, maxRetries, retry } = options;
226
271
  const url = new URL(path, this.config.baseUrl);
227
272
  if (params) {
228
273
  for (const [key, value] of Object.entries(params)) {
@@ -245,17 +290,24 @@ var BaseClient = class _BaseClient {
245
290
  if (body && method !== "GET") {
246
291
  fetchOptions.body = JSON.stringify(body);
247
292
  }
248
- return this.executeWithRetry(url.toString(), fetchOptions);
293
+ return this.executeWithRetry(url.toString(), fetchOptions, {
294
+ decode,
295
+ timeoutMs,
296
+ maxRetries,
297
+ retry
298
+ });
249
299
  }
250
300
  /**
251
301
  * Execute request with exponential backoff retry logic.
252
302
  */
253
- async executeWithRetry(url, options) {
303
+ async executeWithRetry(url, options, policy = {}) {
254
304
  let lastError;
255
- for (let attempt = 0; attempt <= this.config.maxRetries; attempt++) {
305
+ const maxRetries = policy.maxRetries ?? this.config.maxRetries;
306
+ const decode = policy.decode ?? ((response) => this.handleResponse(response));
307
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
256
308
  let retryAfterMs = 0;
257
309
  try {
258
- const httpResponse = await this.fetchWithTimeout(url, options);
310
+ const httpResponse = await this.fetchWithTimeout(url, options, policy.timeoutMs);
259
311
  const retryAfter = httpResponse.headers.get("Retry-After")?.trim();
260
312
  if (retryAfter) {
261
313
  let requestedDelay = 0;
@@ -274,21 +326,20 @@ var BaseClient = class _BaseClient {
274
326
  retryAfterMs = requestedDelay;
275
327
  }
276
328
  }
277
- const data = await this.handleResponse(httpResponse);
329
+ const data = await decode(httpResponse);
278
330
  const rateLimit = this.parseRateLimitHeaders(httpResponse.headers);
279
331
  return { data, rateLimit, status: httpResponse.status, headers: httpResponse.headers };
280
332
  } catch (error) {
281
333
  lastError = error;
282
- if (!_BaseClient.isRetryable(error)) {
334
+ if (!_BaseClient.isRetryable(error, policy.retry ?? "all")) {
283
335
  throw error;
284
336
  }
285
- if (attempt === this.config.maxRetries) {
337
+ if (attempt === maxRetries) {
286
338
  break;
287
339
  }
288
340
  const delay = Math.max(this.config.retryDelay * Math.pow(2, attempt), retryAfterMs);
289
341
  const delaySec = Math.round(delay / 1e3);
290
342
  const attemptNum = attempt + 1;
291
- const maxRetries = this.config.maxRetries;
292
343
  if (error instanceof RateLimitError) {
293
344
  console.warn(
294
345
  `\x1B[33m\u26A0 ScrapeBadger: 429 Rate Limited \u2014 retrying in ${delaySec}s (attempt ${attemptNum}/${maxRetries})\x1B[0m`
@@ -339,9 +390,9 @@ var BaseClient = class _BaseClient {
339
390
  /**
340
391
  * Fetch with timeout support.
341
392
  */
342
- async fetchWithTimeout(url, options) {
393
+ async fetchWithTimeout(url, options, timeoutMs = this.config.timeout) {
343
394
  const controller = new AbortController();
344
- const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
395
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
345
396
  try {
346
397
  const response = await fetch(url, {
347
398
  ...options,
@@ -350,10 +401,7 @@ var BaseClient = class _BaseClient {
350
401
  return response;
351
402
  } catch (error) {
352
403
  if (error instanceof Error && error.name === "AbortError") {
353
- throw new TimeoutError(
354
- `Request timed out after ${this.config.timeout}ms`,
355
- this.config.timeout
356
- );
404
+ throw new TimeoutError(`Request timed out after ${timeoutMs}ms`, timeoutMs);
357
405
  }
358
406
  throw error;
359
407
  } finally {
@@ -389,7 +437,7 @@ var BaseClient = class _BaseClient {
389
437
  if (errorData.error === "ip_not_allowed") {
390
438
  throw new IPNotAllowedError(message, errorData.client_ip ?? null);
391
439
  }
392
- if (errorData.error === "insufficient_scope") {
440
+ if (errorData.error === "insufficient_scope" || errorData.error === "full_access_required") {
393
441
  throw new PermissionDeniedError(
394
442
  message,
395
443
  errorData.required_scope,
@@ -432,16 +480,24 @@ var BaseClient = class _BaseClient {
432
480
  *
433
481
  * Retryable: transient server failures (500/502/503/504), request timeouts,
434
482
  * rate limits, and raw network faults thrown by `fetch` itself. Everything
435
- * else — auth, validation, not-found, conflict — is final.
483
+ * else — auth, validation, not-found, conflict — is final, and so is a
484
+ * replayed result. `mode` narrows this further (see `RequestOptions.retry`).
436
485
  */
437
- static isRetryable(error) {
486
+ static isRetryable(error, mode) {
487
+ if (typeof error === "object" && error !== null && finalErrors.has(error)) {
488
+ return false;
489
+ }
490
+ const networkFault = !(error instanceof ScrapeBadgerError);
491
+ if (mode === "connect") {
492
+ return networkFault && failedBeforeSend(error);
493
+ }
438
494
  if (error instanceof ServerError) {
439
- return RETRYABLE_STATUS_CODES.includes(error.statusCode);
495
+ return mode === "all" && RETRYABLE_STATUS_CODES.includes(error.statusCode);
440
496
  }
441
- if (error instanceof RateLimitError || error instanceof TimeoutError) {
442
- return true;
497
+ if (error instanceof RateLimitError) {
498
+ return mode === "all";
443
499
  }
444
- return !(error instanceof ScrapeBadgerError);
500
+ return error instanceof TimeoutError || networkFault;
445
501
  }
446
502
  /**
447
503
  * Sleep for a given duration.
@@ -1823,6 +1879,48 @@ var GeoClient = class {
1823
1879
  return createPaginatedResponse(response.data ?? []);
1824
1880
  }
1825
1881
  };
1882
+ var DEFAULT_TOLERANCE_S = 300;
1883
+ var SIGNATURE_RE = /^sha256=([0-9a-fA-F]{64})$/;
1884
+ function rawBytes(rawBody, fn) {
1885
+ if (typeof rawBody === "string") return Buffer.from(rawBody, "utf-8");
1886
+ if (rawBody instanceof Uint8Array) {
1887
+ return Buffer.from(rawBody.buffer, rawBody.byteOffset, rawBody.byteLength);
1888
+ }
1889
+ if (rawBody instanceof ArrayBuffer) return Buffer.from(rawBody);
1890
+ throw new TypeError(
1891
+ `${fn} needs the raw request body (a string or Buffer) exactly as received, not a parsed object: read it with express.raw({ type: "application/json" }) or equivalent.`
1892
+ );
1893
+ }
1894
+ function verifyWebhookSignature(secret, rawBody, signature, options = {}) {
1895
+ const body = rawBytes(rawBody, "verifyWebhookSignature");
1896
+ if (!secret || typeof signature !== "string") return false;
1897
+ const match = SIGNATURE_RE.exec(signature.trim());
1898
+ if (!match?.[1]) return false;
1899
+ const expected = crypto.createHmac("sha256", secret).update(body).digest();
1900
+ if (!crypto.timingSafeEqual(expected, Buffer.from(match[1], "hex"))) return false;
1901
+ const { sentAt, toleranceS = DEFAULT_TOLERANCE_S } = options;
1902
+ if (sentAt === void 0 || sentAt === null) return true;
1903
+ const sentAtS = typeof sentAt === "number" ? sentAt : Number(sentAt.trim() || Number.NaN);
1904
+ return Math.abs(Date.now() / 1e3 - sentAtS) <= toleranceS;
1905
+ }
1906
+ function parseWebhookEvent(rawBody) {
1907
+ const text = typeof rawBody === "string" ? rawBody : rawBytes(rawBody, "parseWebhookEvent").toString("utf-8");
1908
+ let parsed;
1909
+ try {
1910
+ parsed = JSON.parse(text);
1911
+ } catch (error) {
1912
+ throw new SyntaxError(`Webhook body is not JSON: ${error.message}`);
1913
+ }
1914
+ const event = parsed;
1915
+ if (typeof event !== "object" || event === null || Array.isArray(event) || typeof event.event !== "string" || typeof event.request_id !== "string") {
1916
+ throw new TypeError(
1917
+ "Not a ScrapeBadger webhook event: expected a JSON object with string `event` and `request_id`."
1918
+ );
1919
+ }
1920
+ return event;
1921
+ }
1922
+
1923
+ // src/twitter/stream.ts
1826
1924
  var MIN_RECONNECT_DELAY_SECONDS = 5;
1827
1925
  function wsUrlFromBase(baseUrl) {
1828
1926
  if (baseUrl.startsWith("https://")) {
@@ -2501,19 +2599,6 @@ var StreamClient = class {
2501
2599
  }
2502
2600
  }
2503
2601
  };
2504
- function verifyWebhookSignature(secret, body, signatureHeader) {
2505
- if (!signatureHeader.startsWith("sha256=")) {
2506
- return false;
2507
- }
2508
- const expectedHex = signatureHeader.slice("sha256=".length);
2509
- const bodyBuffer = typeof body === "string" ? Buffer.from(body, "utf-8") : body;
2510
- const actualHex = crypto.createHmac("sha256", secret).update(bodyBuffer).digest("hex");
2511
- try {
2512
- return crypto.timingSafeEqual(Buffer.from(expectedHex, "hex"), Buffer.from(actualHex, "hex"));
2513
- } catch {
2514
- return false;
2515
- }
2516
- }
2517
2602
 
2518
2603
  // src/twitter/spaces.ts
2519
2604
  var SpacesClient = class {
@@ -3845,6 +3930,38 @@ var GooglePlayClient = class {
3845
3930
  }
3846
3931
  };
3847
3932
 
3933
+ // src/grok/client.ts
3934
+ var GrokClient = class {
3935
+ client;
3936
+ constructor(client) {
3937
+ this.client = client;
3938
+ }
3939
+ /** Ask Grok a question. Generated from the OpenAPI spec; returns the raw response object. */
3940
+ async askGrokAQuestion(params = {}) {
3941
+ return this.client.request("/v1/grok/ask", { params });
3942
+ }
3943
+ /** Ask Grok a question (POST). Generated from the OpenAPI spec; returns the raw response object. */
3944
+ async askGrokAQuestionPost(body, params = {}) {
3945
+ return this.client.request("/v1/grok/ask", { method: "POST", params, body });
3946
+ }
3947
+ /** Measure brand visibility in Grok. Generated from the OpenAPI spec; returns the raw response object. */
3948
+ async measureBrandVisibilityInGrok(params = {}) {
3949
+ return this.client.request("/v1/grok/brand-visibility", { params });
3950
+ }
3951
+ /** Measure brand visibility in Grok (POST). Generated from the OpenAPI spec; returns the raw response object. */
3952
+ async measureBrandVisibilityInGrokPost(body, params = {}) {
3953
+ return this.client.request("/v1/grok/brand-visibility", { method: "POST", params, body });
3954
+ }
3955
+ /** Get a Grok conversation. Generated from the OpenAPI spec; returns the raw response object. */
3956
+ async getAGrokConversation(conversationId, params = {}) {
3957
+ return this.client.request(`/v1/grok/conversations/${conversationId}`, { params });
3958
+ }
3959
+ /** List Grok assistant modes. Generated from the OpenAPI spec; returns the raw response object. */
3960
+ async listGrokAssistantModes(params = {}) {
3961
+ return this.client.request("/v1/grok/models", { params });
3962
+ }
3963
+ };
3964
+
3848
3965
  // src/idealista/client.ts
3849
3966
  var IdealistaClient = class {
3850
3967
  client;
@@ -5033,12 +5150,65 @@ var RedfinClient = class {
5033
5150
  // --- END generated by sdk/codegen/facade ---
5034
5151
  };
5035
5152
 
5153
+ // src/rufus/client.ts
5154
+ var RufusClient = class {
5155
+ client;
5156
+ constructor(client) {
5157
+ this.client = client;
5158
+ }
5159
+ /** Ask Amazon Rufus a question. Generated from the OpenAPI spec; returns the raw response object. */
5160
+ async askAmazonRufusAQuestion(params = {}) {
5161
+ return this.client.request("/v1/rufus/ask", { params });
5162
+ }
5163
+ /** Ask Amazon Rufus a question (POST). Generated from the OpenAPI spec; returns the raw response object. */
5164
+ async askAmazonRufusAQuestionPost(body, params = {}) {
5165
+ return this.client.request("/v1/rufus/ask", { method: "POST", params, body });
5166
+ }
5167
+ /** List Amazon Rufus models. Generated from the OpenAPI spec; returns the raw response object. */
5168
+ async listAmazonRufusModels(params = {}) {
5169
+ return this.client.request("/v1/rufus/models", { params });
5170
+ }
5171
+ };
5172
+
5036
5173
  // src/account/client.ts
5037
5174
  var AccountClient = class {
5038
- client;
5039
5175
  constructor(client) {
5040
5176
  this.client = client;
5041
5177
  }
5178
+ /**
5179
+ * The secret that signs this account's async-request and batch webhooks,
5180
+ * created on first use. Free. Needs a full-access API key.
5181
+ *
5182
+ * @throws PermissionDeniedError - 403 `full_access_required`: a key limited to some APIs.
5183
+ */
5184
+ async webhookSecret() {
5185
+ return this.client.request("/v1/account/webhook-secret");
5186
+ }
5187
+ /**
5188
+ * Replace the webhook signing secret. Deliveries that start from now on are
5189
+ * signed with the new one; retries of a delivery already under way keep the
5190
+ * old one. Free. Needs a full-access API key.
5191
+ *
5192
+ * @throws PermissionDeniedError - 403 `full_access_required`: a key limited to some APIs.
5193
+ */
5194
+ async rotateWebhookSecret() {
5195
+ return this.client.request("/v1/account/webhook-secret/rotate", {
5196
+ method: "POST"
5197
+ });
5198
+ }
5199
+ /**
5200
+ * The account's webhook deliveries of the last 24 hours, newest first.
5201
+ * Free. Needs a full-access API key.
5202
+ *
5203
+ * @param options - `limit` (API default 50, max 200).
5204
+ * @throws PermissionDeniedError - 403 `full_access_required`: a key limited to some APIs.
5205
+ */
5206
+ async webhookDeliveries(options = {}) {
5207
+ return this.client.request("/v1/account/webhook-deliveries", {
5208
+ params: { limit: options.limit }
5209
+ });
5210
+ }
5211
+ // --- BEGIN generated by sdk/codegen/facade — do not edit ---
5042
5212
  /** Get account info. Generated from the OpenAPI spec; returns the raw response object. */
5043
5213
  async getAccountInfo(params = {}) {
5044
5214
  return this.client.request("/v1/account/me", { params });
@@ -5055,7 +5225,208 @@ var AccountClient = class {
5055
5225
  body
5056
5226
  });
5057
5227
  }
5228
+ // --- END generated by sdk/codegen/facade ---
5229
+ };
5230
+
5231
+ // src/requests/client.ts
5232
+ var DEFAULT_WAIT_S = 25;
5233
+ var MAX_WAIT_S = 120;
5234
+ var DEFAULT_POLL_S = 5;
5235
+ var MIN_POLL_MS = 250;
5236
+ var DEFAULT_WAIT_TIMEOUT_MS = 6e5;
5237
+ var WAIT_POLL_RETRIES = 2;
5238
+ var WaitTimeoutError = class _WaitTimeoutError extends TimeoutError {
5239
+ /** The request that is still running. */
5240
+ requestId;
5241
+ constructor(requestId, timeoutMs) {
5242
+ super(
5243
+ `Request ${requestId} still running after ${timeoutMs}ms. It keeps running: poll it again with requests.get() or requests.wait(); do not re-submit it.`,
5244
+ timeoutMs
5245
+ );
5246
+ this.name = "WaitTimeoutError";
5247
+ this.requestId = requestId;
5248
+ Object.setPrototypeOf(this, _WaitTimeoutError.prototype);
5249
+ }
5250
+ };
5251
+ var RequestsClient = class {
5252
+ constructor(client) {
5253
+ this.client = client;
5254
+ }
5255
+ /**
5256
+ * Submit any API call asynchronously.
5257
+ *
5258
+ * Sends `Prefer: respond-async[, wait=N]`, plus `X-Callback-URL` and
5259
+ * `Idempotency-Key` when given. A call that finishes within `wait` comes
5260
+ * back completed; otherwise the API answers 202 and this returns a running
5261
+ * request to {@link get} or {@link wait} for (or to expect a webhook for).
5262
+ *
5263
+ * Without an `idempotencyKey`, a submit is retried only when the connection
5264
+ * failed before anything was sent. A timeout, a network fault, a 429 or a
5265
+ * 5xx is thrown: the call may already be running, and a second submit would
5266
+ * run and bill it again. With a key, the usual retries are safe (a retry
5267
+ * answers the existing call), except that a replayed error is never retried.
5268
+ *
5269
+ * @param path - API path, e.g. "/v1/perplexity/ask" (the "/v1" prefix is optional).
5270
+ * @param options - `method`, `params`, `body`, `callbackUrl`, `wait`, `idempotencyKey`.
5271
+ * @returns The running request (202) or the completed call.
5272
+ * @throws ScrapeBadgerError - A refusal before anything ran (400 `invalid_callback_url`,
5273
+ * `async_not_supported`, `invalid_idempotency_key`; 401; 402; 429), or the call's own
5274
+ * error when it completed within `wait`, as the matching subclass.
5275
+ * @throws ConflictError - 409 `idempotency_key_reused`: the key was used for a different call.
5276
+ */
5277
+ async submit(path, options = {}) {
5278
+ const { method = "GET", params, body, callbackUrl, wait, idempotencyKey } = options;
5279
+ if (wait !== void 0 && (!Number.isFinite(wait) || wait < 0)) {
5280
+ throw new RangeError(`wait must be a number of seconds (0-${MAX_WAIT_S}), got ${wait}`);
5281
+ }
5282
+ const waitS = wait !== void 0 ? Math.floor(wait) : callbackUrl ? 0 : void 0;
5283
+ const headers = {
5284
+ Prefer: waitS === void 0 ? "respond-async" : `respond-async, wait=${waitS}`
5285
+ };
5286
+ if (callbackUrl !== void 0) headers["X-Callback-URL"] = callbackUrl;
5287
+ if (idempotencyKey !== void 0) headers["Idempotency-Key"] = idempotencyKey;
5288
+ const query = {};
5289
+ for (const [key, value] of Object.entries(params ?? {})) {
5290
+ if (value !== null && value !== void 0) query[key] = value;
5291
+ }
5292
+ const effectiveWaitS = Math.min(waitS ?? DEFAULT_WAIT_S, MAX_WAIT_S);
5293
+ const timeoutMs = Math.max(this.client.config.timeout, (effectiveWaitS + 15) * 1e3);
5294
+ const response = await this.client.requestResponse(apiPath(path), {
5295
+ method,
5296
+ params: query,
5297
+ body,
5298
+ headers,
5299
+ timeoutMs,
5300
+ retry: idempotencyKey !== void 0 ? "all" : "connect"
5301
+ });
5302
+ return toAsyncRequest(response);
5303
+ }
5304
+ /**
5305
+ * Poll an async request once. Free.
5306
+ *
5307
+ * @param requestId - `request_id` from the 202 response (or `AsyncRequest.requestId`).
5308
+ * @returns `status: "running"` while in progress; once completed, the original status,
5309
+ * headers and body.
5310
+ * @throws NotFoundError - Unknown or expired request (results are kept about 15 minutes;
5311
+ * one that never completed was not billed).
5312
+ * @throws ScrapeBadgerError - The original call finished with an error status (as the
5313
+ * matching subclass).
5314
+ */
5315
+ async get(requestId) {
5316
+ return this.poll(requestId);
5317
+ }
5318
+ /**
5319
+ * Poll an async request until it completes, pausing as long as the API's
5320
+ * `Retry-After` says between polls. Free. An error status is thrown at
5321
+ * once, never retried: a stored result answers the same every time.
5322
+ *
5323
+ * @param requestId - `request_id` of the running request.
5324
+ * @param options - `timeoutMs` (default 600000, ten minutes).
5325
+ * @returns The completed request.
5326
+ * @throws WaitTimeoutError - Still running at the deadline (it keeps running; poll it again).
5327
+ * @throws NotFoundError - Unknown or expired request.
5328
+ * @throws ScrapeBadgerError - The original call finished with an error status.
5329
+ */
5330
+ async wait(requestId, options = {}) {
5331
+ const timeoutMs = options.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;
5332
+ const deadline = Date.now() + timeoutMs;
5333
+ const maxRetries = Math.min(this.client.config.maxRetries, WAIT_POLL_RETRIES);
5334
+ for (; ; ) {
5335
+ const state = await this.poll(requestId, { maxRetries, retry: "transport" });
5336
+ if (state.status === "completed") return state;
5337
+ const remainingMs = deadline - Date.now();
5338
+ if (remainingMs <= 0) throw new WaitTimeoutError(requestId, timeoutMs);
5339
+ const suggestedMs = (state.retryAfterSeconds ?? DEFAULT_POLL_S) * 1e3;
5340
+ await sleep2(Math.min(Math.max(suggestedMs, MIN_POLL_MS), remainingMs));
5341
+ }
5342
+ }
5343
+ /**
5344
+ * Webhook delivery state of a call submitted with a `callbackUrl`. Free.
5345
+ *
5346
+ * @param requestId - `request_id` of the call.
5347
+ * @throws NotFoundError - 404 `callback_not_found`: no such request, or it had no callback.
5348
+ */
5349
+ async callbackStatus(requestId) {
5350
+ return this.client.request(
5351
+ `/v1/requests/${encodeURIComponent(requestId)}/callback`
5352
+ );
5353
+ }
5354
+ /**
5355
+ * Submit up to 100 GET reads as async requests in one call. Submitting is free.
5356
+ *
5357
+ * Each item runs under this key with the same auth, credit check, rate limit
5358
+ * and price as if sent alone; at most 10 of a batch run at a time.
5359
+ *
5360
+ * @example
5361
+ * ```typescript
5362
+ * const sub = await client.requests.batch(
5363
+ * prompts.map((prompt) => ({ path: "/v1/chatgpt/ask", query: { prompt } })),
5364
+ * { callbackUrl: "https://example.com/hook" }
5365
+ * );
5366
+ * const ids = sub.requests.filter((r) => r.accepted).map((r) => r.request_id);
5367
+ * ```
5368
+ *
5369
+ * @param items - `{ path: "/v1/...", query: {...} }` (method defaults to GET).
5370
+ * @param options - `callbackUrl` for one signed webhook per item.
5371
+ * @returns A request_id (or the refusal) for every item.
5372
+ */
5373
+ async batch(items, options = {}) {
5374
+ return this.client.request("/v1/batch", {
5375
+ method: "POST",
5376
+ body: { requests: items, callback_url: options.callbackUrl }
5377
+ });
5378
+ }
5379
+ async poll(requestId, options = {}) {
5380
+ const response = await this.client.requestResponse(
5381
+ `/v1/requests/${encodeURIComponent(requestId)}`,
5382
+ options
5383
+ );
5384
+ return toAsyncRequest(response, requestId);
5385
+ }
5058
5386
  };
5387
+ function apiPath(path) {
5388
+ if (/^[a-z][a-z0-9+.-]*:/i.test(path) || path.startsWith("//") || path.startsWith("\\")) {
5389
+ throw new TypeError(`path must be an API path such as "/v1/perplexity/ask", not a URL`);
5390
+ }
5391
+ const bare = path.replace(/^\/+/, "");
5392
+ return bare === "v1" || bare.startsWith("v1/") ? `/${bare}` : `/v1/${bare}`;
5393
+ }
5394
+ function toAsyncRequest(response, requestId) {
5395
+ const { status, headers, body } = response;
5396
+ const accepted = status === 202 && typeof body === "object" && body !== null ? body : null;
5397
+ const running = status === 202 && (requestId !== void 0 || typeof accepted?.request_id === "string");
5398
+ const headerMap = {};
5399
+ headers.forEach((value, name) => {
5400
+ headerMap[name.toLowerCase()] = value;
5401
+ });
5402
+ const credits = headers.get("X-Credits-Used");
5403
+ return {
5404
+ requestId: requestId ?? (typeof accepted?.request_id === "string" ? accepted.request_id : null) ?? headers.get("X-Request-ID") ?? "",
5405
+ status: running ? "running" : "completed",
5406
+ running,
5407
+ retryAfterSeconds: running ? retryAfterSeconds(headers, accepted?.retry_after_seconds) : null,
5408
+ statusCode: status,
5409
+ headers: headerMap,
5410
+ body,
5411
+ replayed: headers.get("Idempotent-Replayed")?.trim().toLowerCase() === "true",
5412
+ creditsUsed: credits && /^\d+$/.test(credits) ? Number(credits) : null,
5413
+ resultId: null,
5414
+ // deprecated: the API no longer sends X-Result-ID
5415
+ data: body
5416
+ };
5417
+ }
5418
+ function retryAfterSeconds(headers, fromBody) {
5419
+ const header = headers.get("Retry-After")?.trim();
5420
+ if (header) {
5421
+ if (/^\d+$/.test(header)) return Number(header);
5422
+ const at = Date.parse(header);
5423
+ if (!Number.isNaN(at)) return Math.max(0, Math.ceil((at - Date.now()) / 1e3));
5424
+ }
5425
+ return typeof fromBody === "number" && Number.isFinite(fromBody) && fromBody >= 0 ? fromBody : null;
5426
+ }
5427
+ function sleep2(ms) {
5428
+ return new Promise((resolve) => setTimeout(resolve, ms));
5429
+ }
5059
5430
 
5060
5431
  // src/agent/client.ts
5061
5432
  var AgentClient = class {
@@ -5145,62 +5516,6 @@ var ResultsClient = class {
5145
5516
  });
5146
5517
  }
5147
5518
  };
5148
- var RequestsClient = class {
5149
- constructor(client) {
5150
- this.client = client;
5151
- }
5152
- /**
5153
- * Poll an async request. Free.
5154
- *
5155
- * @param requestId - `request_id` from the 202 response.
5156
- * @returns `running: true` while in progress; once done, `data` is the original body.
5157
- * @throws NotFoundError - Unknown or expired request (one that never completed was not billed).
5158
- * @throws ScrapeBadgerError - The original call finished with an error status (as the matching subclass).
5159
- */
5160
- async get(requestId) {
5161
- const { data, status, headers } = await this.client.requestWithHeaders(
5162
- `/v1/requests/${encodeURIComponent(requestId)}`
5163
- );
5164
- const running = status === 202;
5165
- const retryAfter = running ? data?.retry_after_seconds : void 0;
5166
- const credits = headers?.get("X-Credits-Used");
5167
- return {
5168
- requestId,
5169
- running,
5170
- status: status ?? 200,
5171
- retryAfterSeconds: retryAfter ?? null,
5172
- resultId: null,
5173
- // deprecated: the API no longer sends X-Result-ID
5174
- creditsUsed: credits && /^\d+$/.test(credits) ? Number(credits) : null,
5175
- data
5176
- };
5177
- }
5178
- /**
5179
- * Submit up to 100 GET reads as async requests in one call. Submitting is free.
5180
- *
5181
- * Each item runs under this key with the same auth, credit check, rate limit
5182
- * and price as if sent alone; at most 10 of a batch run at a time.
5183
- *
5184
- * @example
5185
- * ```typescript
5186
- * const sub = await client.requests.batch(
5187
- * prompts.map((prompt) => ({ path: "/v1/chatgpt/ask", query: { prompt } })),
5188
- * { callbackUrl: "https://example.com/hook" }
5189
- * );
5190
- * const ids = sub.requests.filter((r) => r.accepted).map((r) => r.request_id);
5191
- * ```
5192
- *
5193
- * @param items - `{ path: "/v1/...", query: {...} }` (method defaults to GET).
5194
- * @param options - `callbackUrl` for one signed webhook per item.
5195
- * @returns A request_id (or the refusal) for every item.
5196
- */
5197
- async batch(items, options = {}) {
5198
- return this.client.request("/v1/batch", {
5199
- method: "POST",
5200
- body: { requests: items, callback_url: options.callbackUrl }
5201
- });
5202
- }
5203
- };
5204
5519
 
5205
5520
  // src/airbnb/client.ts
5206
5521
  var AirbnbClient = class {
@@ -10777,6 +11092,8 @@ var ScrapeBadger = class {
10777
11092
  google;
10778
11093
  /** Google_Play API client. (Generated from the OpenAPI spec.) */
10779
11094
  google_play;
11095
+ /** Grok API client. (Generated from the OpenAPI spec.) */
11096
+ grok;
10780
11097
  /** Idealista API client. (Generated from the OpenAPI spec.) */
10781
11098
  idealista;
10782
11099
  /** Reddit scraper API client */
@@ -10793,8 +11110,10 @@ var ScrapeBadger = class {
10793
11110
  instagram;
10794
11111
  /** Redfin scraper API client — search, property, agent, autocomplete, markets (redfin.com, US) */
10795
11112
  redfin;
11113
+ /** Rufus API client. (Generated from the OpenAPI spec.) */
11114
+ rufus;
10796
11115
  /** Amazon scraper API client — 14 endpoints */
10797
- /** Account API client. (Generated from the OpenAPI spec.) */
11116
+ /** Account info, the webhook signing secret and the webhook delivery log. Free. */
10798
11117
  account;
10799
11118
  /** Quote a call before making it, and report bugs or send feedback. Free. */
10800
11119
  agent;
@@ -10803,7 +11122,11 @@ var ScrapeBadger = class {
10803
11122
  * 410 Gone since 2026-11-09); see `ResultsClient.get`.
10804
11123
  */
10805
11124
  results;
10806
- /** Poll a call made with `Prefer: respond-async`. Free. */
11125
+ /**
11126
+ * Async requests: submit any call (optionally with a webhook and an
11127
+ * idempotency key), poll it, wait for it, check its webhook delivery.
11128
+ * Polling is free; the call is billed once, when it completes.
11129
+ */
10807
11130
  requests;
10808
11131
  /** Airbnb API client. (Generated from the OpenAPI spec.) */
10809
11132
  airbnb;
@@ -10917,6 +11240,7 @@ var ScrapeBadger = class {
10917
11240
  this.vinted = new VintedClient(this.baseClient);
10918
11241
  this.google = new GoogleClient(this.baseClient);
10919
11242
  this.google_play = new GooglePlayClient(this.baseClient);
11243
+ this.grok = new GrokClient(this.baseClient);
10920
11244
  this.idealista = new IdealistaClient(this.baseClient);
10921
11245
  this.reddit = new RedditClient(this.baseClient);
10922
11246
  this.apartments = new ApartmentsClient(this.baseClient);
@@ -10925,6 +11249,7 @@ var ScrapeBadger = class {
10925
11249
  this.autoscout24 = new Autoscout24Client(this.baseClient);
10926
11250
  this.instagram = new InstagramClient(this.baseClient);
10927
11251
  this.redfin = new RedfinClient(this.baseClient);
11252
+ this.rufus = new RufusClient(this.baseClient);
10928
11253
  this.account = new AccountClient(this.baseClient);
10929
11254
  this.agent = new AgentClient(this.baseClient);
10930
11255
  this.results = new ResultsClient(this.baseClient);
@@ -11104,6 +11429,7 @@ exports.VintedItemsClient = ItemsClient;
11104
11429
  exports.VintedReferenceClient = ReferenceClient;
11105
11430
  exports.VintedSearchClient = SearchClient;
11106
11431
  exports.VintedUsersClient = UsersClient2;
11432
+ exports.WaitTimeoutError = WaitTimeoutError;
11107
11433
  exports.WallapopClient = WallapopClient;
11108
11434
  exports.WalmartClient = WalmartClient;
11109
11435
  exports.WalmartProductsClient = ProductsClient4;
@@ -11138,6 +11464,7 @@ exports.ZillowPropertiesClient = PropertiesClient2;
11138
11464
  exports.ZillowReferenceClient = ReferenceClient14;
11139
11465
  exports.ZillowSearchClient = SearchClient18;
11140
11466
  exports.collectAll = collectAll;
11467
+ exports.parseWebhookEvent = parseWebhookEvent;
11141
11468
  exports.verifyWebhookSignature = verifyWebhookSignature;
11142
11469
  //# sourceMappingURL=index.cjs.map
11143
11470
  //# sourceMappingURL=index.cjs.map