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/README.md CHANGED
@@ -22,6 +22,7 @@ The official Node.js/TypeScript client library for the [ScrapeBadger](https://sc
22
22
  - **Smart Rate Limiting** - Reads API headers and throttles pagination automatically
23
23
  - **Resilient Retries** - Exponential backoff with colored console warnings
24
24
  - **Typed Exceptions** - Distinct error classes for every failure scenario
25
+ - **Async requests and webhooks** - Run any call asynchronously, wait for it or get a signed webhook; idempotent resubmits
25
26
  - **37+ Twitter endpoints** - Tweets, users, lists, communities, trends, geo, real-time streams
26
27
  - **20 Google product APIs** - Search (with optional deferred AI Overview follow-up), Maps, News, Hotels, Trends (incl. topic autocomplete), Jobs, Shopping (+ merchant URL enrichment, barcode offers), Patents, Scholar (search + profiles + author + author citation + cite formats), Images, Videos, Finance, AI Mode, Lens, **Local Pack**, **Shorts**, **Flights**, Products, **Ads Transparency Center**
27
28
  - **Vinted scraping** - Search items, item details, user profiles, brands, colors, markets
@@ -139,9 +140,9 @@ const client = new ScrapeBadger({ apiKey: "your-api-key" });
139
140
  const quote = await client.agent.quote("GET", "/v1/google/search", { params: { q: "coffee" } });
140
141
  console.log(quote.valid, quote.errors, quote.credits.max, quote.usd, quote.latency);
141
142
 
142
- // Poll a call made with `Prefer: respond-async` (202 + request_id).
143
+ // Poll an async call (see "Async requests and webhooks" below).
143
144
  const state = await client.requests.get(requestId);
144
- if (!state.running) console.log(state.status, state.creditsUsed, state.data);
145
+ if (state.status === "completed") console.log(state.statusCode, state.creditsUsed, state.body);
145
146
 
146
147
  // Report a bug or send feedback (pass the failing call's X-Request-ID).
147
148
  await client.agent.reportBug("Empty results for a valid query", { requestId });
@@ -152,7 +153,88 @@ const info = await client.account.getAccountInfo();
152
153
  const trial = info.agent_trial as AgentTrial | undefined;
153
154
  ```
154
155
 
155
- ScrapeBadger does not cache or store responses: every call is fetched fresh and billed, and `results.get` (the old free re-read) is deprecated because `GET /v1/results/{id}` was removed on 2026-11-09. To reshape a result, re-run the call with the `jq`, `fields` or `max_items` view parameters. `requests.get` returns `running: true` while the call is in progress — wait `retryAfterSeconds` and poll again; never re-submit the call. Once finished it returns the original body, or throws the original call's error. The SDK's own methods never send `Prefer: respond-async`; `requests.get` polls a request ID obtained elsewhere (raw HTTP, the CLI or MCP server).
156
+ ScrapeBadger does not cache or store responses: every call is fetched fresh and billed, and `results.get` (the old free re-read) is deprecated because `GET /v1/results/{id}` was removed on 2026-11-09. To reshape a result, re-run the call with the `jq`, `fields` or `max_items` view parameters. `requests.get` returns `status: "running"` while the call is in progress — wait `retryAfterSeconds` and poll again; never re-submit the call. Once completed it returns the original status, headers and body, or throws the original call's error. The SDK's per-endpoint methods are synchronous; run any of them asynchronously with `requests.submit`.
157
+
158
+ ## Async requests and webhooks
159
+
160
+ Any API call can run asynchronously. Submit it, then wait for it, poll it, or get a signed webhook when it completes. Submitting, polling and waiting are free; the call is billed once, when it completes, at its normal price. Results are kept for about 15 minutes.
161
+
162
+ ```typescript
163
+ import { ScrapeBadger } from "scrapebadger";
164
+
165
+ const client = new ScrapeBadger({ apiKey: process.env.SCRAPEBADGER_API_KEY! });
166
+
167
+ // Wait up to 25 s for the answer; a slower call comes back running (HTTP 202).
168
+ const run = await client.requests.submit("/v1/perplexity/ask", {
169
+ params: { prompt: "best crm for startups", country: "us" },
170
+ wait: 25,
171
+ idempotencyKey: "crm-us-2026-11-18", // a resubmit with this key is not run or billed again
172
+ });
173
+
174
+ // A call that completed within `wait` is not kept for polling: use it as it is.
175
+ const done = run.status === "completed" ? run : await client.requests.wait(run.requestId);
176
+ console.log(done.statusCode, done.creditsUsed, done.body);
177
+ ```
178
+
179
+ At volume, skip the waiting: give each call a `callbackUrl` and ScrapeBadger POSTs the result to it when the call completes. Without a `wait`, a call with a callback answers 202 at once.
180
+
181
+ ```typescript
182
+ const prompts = ["best crm for startups", "best crm for agencies", "best crm for nonprofits"];
183
+ for (const [i, prompt] of prompts.entries()) {
184
+ const run = await client.requests.submit("/v1/perplexity/ask", {
185
+ params: { prompt, country: "us" },
186
+ callbackUrl: "https://your-server.example/scrapebadger/webhook",
187
+ idempotencyKey: `crm-run-42-${i}`, // safe to resubmit after a crash or a timeout
188
+ });
189
+ console.log(run.requestId, run.status, run.replayed);
190
+ }
191
+ ```
192
+
193
+ Every webhook is signed with your account's webhook secret (`client.account.webhookSecret()`, needs a full-access API key). `X-ScrapeBadger-Signature` is `sha256=` plus the hex HMAC-SHA256 of the **raw** request body, so read the body as bytes. A body parsed and re-serialised will not match.
194
+
195
+ ```typescript
196
+ import express from "express";
197
+ import { ScrapeBadger, parseWebhookEvent, verifyWebhookSignature } from "scrapebadger";
198
+ import type { WebhookEvent } from "scrapebadger";
199
+
200
+ const client = new ScrapeBadger({ apiKey: process.env.SCRAPEBADGER_API_KEY! });
201
+ const { secret } = await client.account.webhookSecret(); // fetch once and keep it
202
+ const seen = new Set<string>(); // use your database in production
203
+
204
+ const app = express();
205
+
206
+ // express.raw() keeps the exact bytes that were signed; express.json() would not.
207
+ app.post("/scrapebadger/webhook", express.raw({ type: "application/json" }), (req, res) => {
208
+ let event: WebhookEvent<{ answer?: string }>;
209
+ try {
210
+ event = parseWebhookEvent(req.body);
211
+ } catch {
212
+ return res.sendStatus(400);
213
+ }
214
+ // Nothing in the event is trusted until this passes. sent_at is part of the
215
+ // signed body, so an old delivery replayed later fails the freshness check.
216
+ const signature = req.get("X-ScrapeBadger-Signature");
217
+ if (!verifyWebhookSignature(secret, req.body, signature, { sentAt: event.sent_at })) {
218
+ return res.sendStatus(401);
219
+ }
220
+ if (!seen.has(event.request_id)) {
221
+ seen.add(event.request_id); // deliveries can repeat: deduplicate on request_id
222
+ if (event.status === 200) console.log(event.request_id, event.body?.answer);
223
+ else console.warn(event.request_id, "failed with", event.status, event.body);
224
+ }
225
+ res.sendStatus(204);
226
+ });
227
+
228
+ app.listen(3000);
229
+ ```
230
+
231
+ - `event.status` and `event.body` are the call's own, errors included. A body over 1 MB is left out (`body: null`, `body_omitted: true`): fetch it with `client.requests.get(event.request_id)` within about 15 minutes.
232
+ - Answer with any 2xx, quickly. A timeout, a connection error, 408, 429 or 5xx is retried after 10 s, 60 s and 5 min (4 attempts in total).
233
+ - Check deliveries with `client.requests.callbackStatus(requestId)` (one call) or `client.account.webhookDeliveries({ limit })` (the last 24 hours). Rotate the secret with `client.account.rotateWebhookSecret()`.
234
+ - `submit` throws a refusal before anything runs: `invalid_callback_url`, `async_not_supported`, `invalid_idempotency_key` (400), or `ConflictError` when an `idempotencyKey` is reused for a different call (409). A call that completed within `wait` with an error status throws that error, like a normal call.
235
+ - Without an `idempotencyKey`, the SDK retries a submit only when the connection failed before anything was sent. A timeout, a network fault, a 429 or a 5xx is thrown, because the call may already be running. With a key, the SDK retries as usual, and a retry answers the existing call (`replayed: true`).
236
+ - `get` and `wait` throw the call's own error status as the matching SDK error; `wait` does not retry it, because a stored result does not change. `wait` throws `WaitTimeoutError` (a `TimeoutError` with `requestId`) when the call is still running at `timeoutMs` (default ten minutes). The call keeps running: wait or poll again, never resubmit it.
237
+ - The webhook secret and delivery log need a full-access API key; a key limited to some APIs gets `PermissionDeniedError` (403 `full_access_required`).
156
238
 
157
239
  ## Error Handling
158
240
 
@@ -238,6 +320,7 @@ Pro: 1000/min, Enterprise: 5000/min).
238
320
  - `ValidationError` - Invalid request
239
321
  - `ServerError` - Server error
240
322
  - `TimeoutError` - Request timeout
323
+ - `WaitTimeoutError` - `requests.wait()` deadline passed while the call still runs (a `TimeoutError`)
241
324
  - `InsufficientCreditsError` - Out of credits
242
325
  - `AccountRestrictedError` - Account restricted
243
326
  - `WebSocketStreamError` - WebSocket stream failure (auth, limit, or network)
@@ -45,6 +45,32 @@ interface RequestOptions {
45
45
  params?: Record<string, string | number | boolean | undefined>;
46
46
  body?: unknown;
47
47
  headers?: Record<string, string>;
48
+ /** Timeout for this request in milliseconds (default: the client's `timeout`). */
49
+ timeoutMs?: number;
50
+ /** Retry cap for this request (default: the client's `maxRetries`). */
51
+ maxRetries?: number;
52
+ /**
53
+ * What a failed attempt may be retried on (default "all"):
54
+ * - "all": 5xx, 429, timeouts and network faults;
55
+ * - "transport": timeouts and network faults only; an error status is
56
+ * thrown at once (a stored result answers the same every time);
57
+ * - "connect": only a connection that failed before anything was sent.
58
+ * For a request a second copy of which could run and bill a call again,
59
+ * such as an async submit without an `Idempotency-Key`: after a lost
60
+ * 202, a timeout or an edge 5xx the call may already be running.
61
+ */
62
+ retry?: RetryMode;
63
+ }
64
+ /** See {@link RequestOptions.retry}. */
65
+ type RetryMode = "all" | "transport" | "connect";
66
+ /**
67
+ * A response with its status, headers and decoded body: JSON when the
68
+ * response is JSON, otherwise text. Returned by {@link BaseClient.requestResponse}.
69
+ */
70
+ interface RawResponse {
71
+ status: number;
72
+ headers: Headers;
73
+ body: unknown;
48
74
  }
49
75
  /**
50
76
  * Base HTTP client for making API requests.
@@ -76,6 +102,13 @@ declare class BaseClient {
76
102
  * Make an HTTP request and return the data with its rate limit, status and headers.
77
103
  */
78
104
  requestWithHeaders<T>(path: string, options?: RequestOptions): Promise<ResponseWithHeaders<T>>;
105
+ /**
106
+ * Make an HTTP request and return its status, headers and body undigested:
107
+ * the body is JSON-decoded when the response is JSON, otherwise text (the
108
+ * normal path turns a non-JSON, non-HTML body into `{ detail }`). Error
109
+ * statuses still throw the matching typed error.
110
+ */
111
+ requestResponse(path: string, options?: RequestOptions): Promise<RawResponse>;
79
112
  /**
80
113
  * Internal method that builds the request and executes it, returning data and rate limit info.
81
114
  */
@@ -101,7 +134,8 @@ declare class BaseClient {
101
134
  *
102
135
  * Retryable: transient server failures (500/502/503/504), request timeouts,
103
136
  * rate limits, and raw network faults thrown by `fetch` itself. Everything
104
- * else — auth, validation, not-found, conflict — is final.
137
+ * else — auth, validation, not-found, conflict — is final, and so is a
138
+ * replayed result. `mode` narrows this further (see `RequestOptions.retry`).
105
139
  */
106
140
  private static isRetryable;
107
141
  /**
@@ -2663,6 +2697,113 @@ interface ConnectOptions {
2663
2697
  maxReconnects?: number;
2664
2698
  }
2665
2699
 
2700
+ /**
2701
+ * Types of the webhooks ScrapeBadger sends.
2702
+ */
2703
+ /**
2704
+ * Payload of the `request.completed` webhook, POSTed to the `X-Callback-URL`
2705
+ * (or batch `callback_url`) of an async call when it completes.
2706
+ *
2707
+ * Deliveries can repeat: deduplicate on `request_id`.
2708
+ */
2709
+ interface WebhookEvent<T = unknown> {
2710
+ /** The event type. Only "request.completed" is sent today. */
2711
+ event: "request.completed";
2712
+ request_id: string;
2713
+ /** The batch the call was part of, or null. */
2714
+ batch_id: string | null;
2715
+ /** HTTP status of the call itself, errors included. */
2716
+ status: number;
2717
+ /** The call's kept response headers, names lower-cased (e.g. `x-credits-used`). */
2718
+ headers: Record<string, string>;
2719
+ /**
2720
+ * The call's body, errors included: JSON-decoded when the call answered
2721
+ * JSON, otherwise text. null when `body_omitted` (over 1 MB): fetch it from
2722
+ * `result_url` within about 15 minutes.
2723
+ */
2724
+ body: T | null;
2725
+ /** true when the body was left out for its size. */
2726
+ body_omitted?: boolean;
2727
+ /** Size of the call's body in bytes. */
2728
+ body_size: number;
2729
+ /** Where to fetch the result (`GET /v1/requests/{request_id}`) while it is kept. */
2730
+ result_url: string;
2731
+ /** When the result stops being kept (unix seconds). */
2732
+ result_expires_at: number;
2733
+ /** Delivery attempt, from 1. */
2734
+ attempt: number;
2735
+ /** When this attempt was sent (unix seconds). Covered by the signature. */
2736
+ sent_at: number;
2737
+ }
2738
+ /** Options for {@link verifyWebhookSignature}. */
2739
+ interface VerifyWebhookSignatureOptions {
2740
+ /**
2741
+ * When the delivery was sent, in unix seconds: the payload's `sent_at`
2742
+ * (signed) or the `X-ScrapeBadger-Timestamp` header (not signed). When
2743
+ * given, a delivery more than `toleranceS` away from now is rejected, which
2744
+ * stops replays of old deliveries.
2745
+ */
2746
+ sentAt?: number | string | null;
2747
+ /** Largest accepted age of `sentAt`, in seconds (default 300). */
2748
+ toleranceS?: number;
2749
+ }
2750
+
2751
+ /**
2752
+ * Verify and parse the webhooks ScrapeBadger sends: async-request callbacks
2753
+ * (`request.completed`) and Twitter stream monitor deliveries.
2754
+ *
2755
+ * Every delivery carries `X-ScrapeBadger-Signature: sha256=<hex>`, the
2756
+ * HMAC-SHA256 of the raw request body under your webhook secret
2757
+ * (`account.webhookSecret()` for async requests, the monitor's secret for
2758
+ * stream monitors).
2759
+ */
2760
+
2761
+ /** A raw webhook body: exactly the bytes received, before any JSON parsing. */
2762
+ type RawWebhookBody = string | Uint8Array | ArrayBuffer;
2763
+ /**
2764
+ * Verify the signature of a ScrapeBadger webhook. Constant-time.
2765
+ *
2766
+ * Compares `X-ScrapeBadger-Signature` (`sha256=<hex>`) with the HMAC-SHA256
2767
+ * of the raw body under `secret`. Pass the body exactly as received: a body
2768
+ * parsed and re-serialised will not match. With `sentAt`, a delivery sent
2769
+ * more than `toleranceS` seconds (default 300) from now is rejected too.
2770
+ *
2771
+ * @param secret - Your webhook secret (`account.webhookSecret()`, or the stream monitor's).
2772
+ * @param rawBody - The raw request body (string, Buffer, Uint8Array or ArrayBuffer).
2773
+ * @param signature - The `X-ScrapeBadger-Signature` header value.
2774
+ * @param options - `sentAt` (unix seconds; the payload's signed `sent_at`), `toleranceS`.
2775
+ * @returns true when the signature matches (and `sentAt` is fresh, when given).
2776
+ *
2777
+ * @example
2778
+ * ```typescript
2779
+ * import express from "express";
2780
+ * import { parseWebhookEvent, verifyWebhookSignature } from "scrapebadger";
2781
+ *
2782
+ * app.post("/scrapebadger/webhook", express.raw({ type: "application/json" }), (req, res) => {
2783
+ * const event = parseWebhookEvent(req.body);
2784
+ * const ok = verifyWebhookSignature(secret, req.body, req.get("X-ScrapeBadger-Signature"), {
2785
+ * sentAt: event.sent_at,
2786
+ * });
2787
+ * if (!ok) return res.sendStatus(401);
2788
+ * // ... deduplicate on event.request_id, then handle event.status / event.body
2789
+ * res.sendStatus(204);
2790
+ * });
2791
+ * ```
2792
+ */
2793
+ declare function verifyWebhookSignature(secret: string, rawBody: RawWebhookBody, signature: string | null | undefined, options?: VerifyWebhookSignatureOptions): boolean;
2794
+ /**
2795
+ * Parse the raw body of a `request.completed` webhook.
2796
+ *
2797
+ * Verify the signature with {@link verifyWebhookSignature} before acting on
2798
+ * the event. Deliveries can repeat: deduplicate on `request_id`.
2799
+ *
2800
+ * @param rawBody - The raw request body (string, Buffer, Uint8Array or ArrayBuffer).
2801
+ * @returns The event; `body` is the call's own body (JSON-decoded when JSON).
2802
+ * @throws SyntaxError - The body is not JSON.
2803
+ * @throws TypeError - The body is not a ScrapeBadger webhook event.
2804
+ */
2805
+ declare function parseWebhookEvent<T = unknown>(rawBody: RawWebhookBody): WebhookEvent<T>;
2806
+
2666
2807
  /**
2667
2808
  * StreamClient -- stream monitor management and live WebSocket streaming.
2668
2809
  */
@@ -3069,35 +3210,6 @@ declare class StreamClient {
3069
3210
  */
3070
3211
  connectIter(options?: ConnectOptions): AsyncIterableIterator<StreamEvent>;
3071
3212
  }
3072
- /**
3073
- * Verify the HMAC-SHA256 signature of an incoming webhook request.
3074
- *
3075
- * The server sets the header:
3076
- * X-ScrapeBadger-Signature: sha256=<hex-digest>
3077
- *
3078
- * @param secret - The webhook secret configured on the monitor.
3079
- * @param body - The raw request body string or Buffer.
3080
- * @param signatureHeader - The full X-ScrapeBadger-Signature header value.
3081
- * @returns true if the signature is valid.
3082
- *
3083
- * @example
3084
- * ```typescript
3085
- * // In an Express webhook receiver:
3086
- * import { verifyWebhookSignature } from "scrapebadger/twitter";
3087
- * import express from "express";
3088
- *
3089
- * app.post("/webhook", express.raw({ type: "application/json" }), (req, res) => {
3090
- * const sig = req.headers["x-scrapebadger-signature"] as string;
3091
- * if (!verifyWebhookSignature("my-secret", req.body, sig)) {
3092
- * return res.status(401).json({ error: "Invalid signature" });
3093
- * }
3094
- * const event = JSON.parse(req.body.toString());
3095
- * // process event...
3096
- * res.sendStatus(200);
3097
- * });
3098
- * ```
3099
- */
3100
- declare function verifyWebhookSignature(secret: string, body: string | Buffer, signatureHeader: string): boolean;
3101
3213
 
3102
3214
  /**
3103
3215
  * Twitter Spaces API client.
@@ -3240,4 +3352,4 @@ declare class TwitterClient {
3240
3352
  removeWebhookFromMonitor(webhookId: string, body?: unknown, params?: Record<string, string | number | boolean | undefined>): Promise<Record<string, unknown>>;
3241
3353
  }
3242
3354
 
3243
- export { type CommunityMember as $, AuthenticationError as A, BaseClient as B, ConflictError as C, type UserMention as D, type TweetPlace as E, type Tweet as F, GeoClient as G, type Hashtag as H, InsufficientCreditsError as I, type User as J, type UserAbout as K, ListsClient as L, type Media as M, NotFoundError as N, type UserIds as O, PermissionDeniedError as P, type QueryType as Q, type ResolvedConfig as R, type ScrapeBadgerConfig as S, TwitterClient as T, UsersClient as U, ValidationError as V, WebSocketStreamError as W, type List as X, type CommunityBanner as Y, type CommunityRule as Z, type Community as _, ScrapeBadgerError as a, type Trend as a0, type Location as a1, type PlaceTrends as a2, type Place as a3, type Article as a4, type CommunityNote as a5, type Space as a6, type Broadcast as a7, type ApiResponse as a8, type ListResponse as a9, type FilterRulePricingTiersResponse as aA, type MonitorStatus as aa, type StreamMonitor as ab, type StreamMonitorList as ac, type CreateMonitorParams as ad, type UpdateMonitorParams as ae, type StreamTweet as af, type ConnectedEvent as ag, type PingEvent as ah, type TweetEvent as ai, type ErrorEvent as aj, type StreamEvent as ak, type StreamEventType as al, type DeliveryLog as am, type DeliveryLogList as an, type BillingLog as ao, type BillingLogList as ap, type ConnectOptions as aq, type FilterRuleStatus as ar, type FilterRuleResponse as as, type FilterRuleCreate as at, type FilterRuleUpdate as au, type FilterRulePricingTier as av, type FilterRuleListResponse as aw, type FilterRuleValidateResponse as ax, type FilterRuleDeliveryLog as ay, type FilterRuleDeliveryLogListResponse as az, RateLimitError as b, BlockedError as c, ServerError as d, TimeoutError as e, AccountRestrictedError as f, IPNotAllowedError as g, type BlockKind as h, type BlockingCaptcha as i, type PaginatedResponse as j, type PaginationOptions as k, type IteratorOptions as l, collectAll as m, TweetsClient as n, CommunitiesClient as o, TrendsClient as p, type GeoSearchOptions as q, StreamClient as r, type StreamEmitter as s, SpacesClient as t, type TrendCategory as u, verifyWebhookSignature as v, type CommunityTweetType as w, type PollOption as x, type Poll as y, type Url as z };
3355
+ export { type List as $, AuthenticationError as A, BaseClient as B, ConflictError as C, type CommunityTweetType as D, type PollOption as E, type Poll as F, GeoClient as G, type Url as H, InsufficientCreditsError as I, type Hashtag as J, type UserMention as K, ListsClient as L, type Media as M, NotFoundError as N, type TweetPlace as O, PermissionDeniedError as P, type QueryType as Q, type ResolvedConfig as R, type ScrapeBadgerConfig as S, TimeoutError as T, UsersClient as U, ValidationError as V, WebSocketStreamError as W, type Tweet as X, type User as Y, type UserAbout as Z, type UserIds as _, TwitterClient as a, type CommunityBanner as a0, type CommunityRule as a1, type Community as a2, type CommunityMember as a3, type Trend as a4, type Location as a5, type PlaceTrends as a6, type Place as a7, type Article as a8, type CommunityNote as a9, type FilterRuleListResponse as aA, type FilterRuleValidateResponse as aB, type FilterRuleDeliveryLog as aC, type FilterRuleDeliveryLogListResponse as aD, type FilterRulePricingTiersResponse as aE, type Space as aa, type Broadcast as ab, type ApiResponse as ac, type ListResponse as ad, type MonitorStatus as ae, type StreamMonitor as af, type StreamMonitorList as ag, type CreateMonitorParams as ah, type UpdateMonitorParams as ai, type StreamTweet as aj, type ConnectedEvent as ak, type PingEvent as al, type TweetEvent as am, type ErrorEvent as an, type StreamEvent as ao, type StreamEventType as ap, type DeliveryLog as aq, type DeliveryLogList as ar, type BillingLog as as, type BillingLogList as at, type ConnectOptions as au, type FilterRuleStatus as av, type FilterRuleResponse as aw, type FilterRuleCreate as ax, type FilterRuleUpdate as ay, type FilterRulePricingTier as az, ScrapeBadgerError as b, RateLimitError as c, BlockedError as d, ServerError as e, AccountRestrictedError as f, IPNotAllowedError as g, type BlockKind as h, type BlockingCaptcha as i, type PaginatedResponse as j, type PaginationOptions as k, type IteratorOptions as l, collectAll as m, type WebhookEvent as n, type VerifyWebhookSignatureOptions as o, parseWebhookEvent as p, type RawWebhookBody as q, TweetsClient as r, CommunitiesClient as s, TrendsClient as t, type GeoSearchOptions as u, verifyWebhookSignature as v, StreamClient as w, type StreamEmitter as x, SpacesClient as y, type TrendCategory as z };
@@ -45,6 +45,32 @@ interface RequestOptions {
45
45
  params?: Record<string, string | number | boolean | undefined>;
46
46
  body?: unknown;
47
47
  headers?: Record<string, string>;
48
+ /** Timeout for this request in milliseconds (default: the client's `timeout`). */
49
+ timeoutMs?: number;
50
+ /** Retry cap for this request (default: the client's `maxRetries`). */
51
+ maxRetries?: number;
52
+ /**
53
+ * What a failed attempt may be retried on (default "all"):
54
+ * - "all": 5xx, 429, timeouts and network faults;
55
+ * - "transport": timeouts and network faults only; an error status is
56
+ * thrown at once (a stored result answers the same every time);
57
+ * - "connect": only a connection that failed before anything was sent.
58
+ * For a request a second copy of which could run and bill a call again,
59
+ * such as an async submit without an `Idempotency-Key`: after a lost
60
+ * 202, a timeout or an edge 5xx the call may already be running.
61
+ */
62
+ retry?: RetryMode;
63
+ }
64
+ /** See {@link RequestOptions.retry}. */
65
+ type RetryMode = "all" | "transport" | "connect";
66
+ /**
67
+ * A response with its status, headers and decoded body: JSON when the
68
+ * response is JSON, otherwise text. Returned by {@link BaseClient.requestResponse}.
69
+ */
70
+ interface RawResponse {
71
+ status: number;
72
+ headers: Headers;
73
+ body: unknown;
48
74
  }
49
75
  /**
50
76
  * Base HTTP client for making API requests.
@@ -76,6 +102,13 @@ declare class BaseClient {
76
102
  * Make an HTTP request and return the data with its rate limit, status and headers.
77
103
  */
78
104
  requestWithHeaders<T>(path: string, options?: RequestOptions): Promise<ResponseWithHeaders<T>>;
105
+ /**
106
+ * Make an HTTP request and return its status, headers and body undigested:
107
+ * the body is JSON-decoded when the response is JSON, otherwise text (the
108
+ * normal path turns a non-JSON, non-HTML body into `{ detail }`). Error
109
+ * statuses still throw the matching typed error.
110
+ */
111
+ requestResponse(path: string, options?: RequestOptions): Promise<RawResponse>;
79
112
  /**
80
113
  * Internal method that builds the request and executes it, returning data and rate limit info.
81
114
  */
@@ -101,7 +134,8 @@ declare class BaseClient {
101
134
  *
102
135
  * Retryable: transient server failures (500/502/503/504), request timeouts,
103
136
  * rate limits, and raw network faults thrown by `fetch` itself. Everything
104
- * else — auth, validation, not-found, conflict — is final.
137
+ * else — auth, validation, not-found, conflict — is final, and so is a
138
+ * replayed result. `mode` narrows this further (see `RequestOptions.retry`).
105
139
  */
106
140
  private static isRetryable;
107
141
  /**
@@ -2663,6 +2697,113 @@ interface ConnectOptions {
2663
2697
  maxReconnects?: number;
2664
2698
  }
2665
2699
 
2700
+ /**
2701
+ * Types of the webhooks ScrapeBadger sends.
2702
+ */
2703
+ /**
2704
+ * Payload of the `request.completed` webhook, POSTed to the `X-Callback-URL`
2705
+ * (or batch `callback_url`) of an async call when it completes.
2706
+ *
2707
+ * Deliveries can repeat: deduplicate on `request_id`.
2708
+ */
2709
+ interface WebhookEvent<T = unknown> {
2710
+ /** The event type. Only "request.completed" is sent today. */
2711
+ event: "request.completed";
2712
+ request_id: string;
2713
+ /** The batch the call was part of, or null. */
2714
+ batch_id: string | null;
2715
+ /** HTTP status of the call itself, errors included. */
2716
+ status: number;
2717
+ /** The call's kept response headers, names lower-cased (e.g. `x-credits-used`). */
2718
+ headers: Record<string, string>;
2719
+ /**
2720
+ * The call's body, errors included: JSON-decoded when the call answered
2721
+ * JSON, otherwise text. null when `body_omitted` (over 1 MB): fetch it from
2722
+ * `result_url` within about 15 minutes.
2723
+ */
2724
+ body: T | null;
2725
+ /** true when the body was left out for its size. */
2726
+ body_omitted?: boolean;
2727
+ /** Size of the call's body in bytes. */
2728
+ body_size: number;
2729
+ /** Where to fetch the result (`GET /v1/requests/{request_id}`) while it is kept. */
2730
+ result_url: string;
2731
+ /** When the result stops being kept (unix seconds). */
2732
+ result_expires_at: number;
2733
+ /** Delivery attempt, from 1. */
2734
+ attempt: number;
2735
+ /** When this attempt was sent (unix seconds). Covered by the signature. */
2736
+ sent_at: number;
2737
+ }
2738
+ /** Options for {@link verifyWebhookSignature}. */
2739
+ interface VerifyWebhookSignatureOptions {
2740
+ /**
2741
+ * When the delivery was sent, in unix seconds: the payload's `sent_at`
2742
+ * (signed) or the `X-ScrapeBadger-Timestamp` header (not signed). When
2743
+ * given, a delivery more than `toleranceS` away from now is rejected, which
2744
+ * stops replays of old deliveries.
2745
+ */
2746
+ sentAt?: number | string | null;
2747
+ /** Largest accepted age of `sentAt`, in seconds (default 300). */
2748
+ toleranceS?: number;
2749
+ }
2750
+
2751
+ /**
2752
+ * Verify and parse the webhooks ScrapeBadger sends: async-request callbacks
2753
+ * (`request.completed`) and Twitter stream monitor deliveries.
2754
+ *
2755
+ * Every delivery carries `X-ScrapeBadger-Signature: sha256=<hex>`, the
2756
+ * HMAC-SHA256 of the raw request body under your webhook secret
2757
+ * (`account.webhookSecret()` for async requests, the monitor's secret for
2758
+ * stream monitors).
2759
+ */
2760
+
2761
+ /** A raw webhook body: exactly the bytes received, before any JSON parsing. */
2762
+ type RawWebhookBody = string | Uint8Array | ArrayBuffer;
2763
+ /**
2764
+ * Verify the signature of a ScrapeBadger webhook. Constant-time.
2765
+ *
2766
+ * Compares `X-ScrapeBadger-Signature` (`sha256=<hex>`) with the HMAC-SHA256
2767
+ * of the raw body under `secret`. Pass the body exactly as received: a body
2768
+ * parsed and re-serialised will not match. With `sentAt`, a delivery sent
2769
+ * more than `toleranceS` seconds (default 300) from now is rejected too.
2770
+ *
2771
+ * @param secret - Your webhook secret (`account.webhookSecret()`, or the stream monitor's).
2772
+ * @param rawBody - The raw request body (string, Buffer, Uint8Array or ArrayBuffer).
2773
+ * @param signature - The `X-ScrapeBadger-Signature` header value.
2774
+ * @param options - `sentAt` (unix seconds; the payload's signed `sent_at`), `toleranceS`.
2775
+ * @returns true when the signature matches (and `sentAt` is fresh, when given).
2776
+ *
2777
+ * @example
2778
+ * ```typescript
2779
+ * import express from "express";
2780
+ * import { parseWebhookEvent, verifyWebhookSignature } from "scrapebadger";
2781
+ *
2782
+ * app.post("/scrapebadger/webhook", express.raw({ type: "application/json" }), (req, res) => {
2783
+ * const event = parseWebhookEvent(req.body);
2784
+ * const ok = verifyWebhookSignature(secret, req.body, req.get("X-ScrapeBadger-Signature"), {
2785
+ * sentAt: event.sent_at,
2786
+ * });
2787
+ * if (!ok) return res.sendStatus(401);
2788
+ * // ... deduplicate on event.request_id, then handle event.status / event.body
2789
+ * res.sendStatus(204);
2790
+ * });
2791
+ * ```
2792
+ */
2793
+ declare function verifyWebhookSignature(secret: string, rawBody: RawWebhookBody, signature: string | null | undefined, options?: VerifyWebhookSignatureOptions): boolean;
2794
+ /**
2795
+ * Parse the raw body of a `request.completed` webhook.
2796
+ *
2797
+ * Verify the signature with {@link verifyWebhookSignature} before acting on
2798
+ * the event. Deliveries can repeat: deduplicate on `request_id`.
2799
+ *
2800
+ * @param rawBody - The raw request body (string, Buffer, Uint8Array or ArrayBuffer).
2801
+ * @returns The event; `body` is the call's own body (JSON-decoded when JSON).
2802
+ * @throws SyntaxError - The body is not JSON.
2803
+ * @throws TypeError - The body is not a ScrapeBadger webhook event.
2804
+ */
2805
+ declare function parseWebhookEvent<T = unknown>(rawBody: RawWebhookBody): WebhookEvent<T>;
2806
+
2666
2807
  /**
2667
2808
  * StreamClient -- stream monitor management and live WebSocket streaming.
2668
2809
  */
@@ -3069,35 +3210,6 @@ declare class StreamClient {
3069
3210
  */
3070
3211
  connectIter(options?: ConnectOptions): AsyncIterableIterator<StreamEvent>;
3071
3212
  }
3072
- /**
3073
- * Verify the HMAC-SHA256 signature of an incoming webhook request.
3074
- *
3075
- * The server sets the header:
3076
- * X-ScrapeBadger-Signature: sha256=<hex-digest>
3077
- *
3078
- * @param secret - The webhook secret configured on the monitor.
3079
- * @param body - The raw request body string or Buffer.
3080
- * @param signatureHeader - The full X-ScrapeBadger-Signature header value.
3081
- * @returns true if the signature is valid.
3082
- *
3083
- * @example
3084
- * ```typescript
3085
- * // In an Express webhook receiver:
3086
- * import { verifyWebhookSignature } from "scrapebadger/twitter";
3087
- * import express from "express";
3088
- *
3089
- * app.post("/webhook", express.raw({ type: "application/json" }), (req, res) => {
3090
- * const sig = req.headers["x-scrapebadger-signature"] as string;
3091
- * if (!verifyWebhookSignature("my-secret", req.body, sig)) {
3092
- * return res.status(401).json({ error: "Invalid signature" });
3093
- * }
3094
- * const event = JSON.parse(req.body.toString());
3095
- * // process event...
3096
- * res.sendStatus(200);
3097
- * });
3098
- * ```
3099
- */
3100
- declare function verifyWebhookSignature(secret: string, body: string | Buffer, signatureHeader: string): boolean;
3101
3213
 
3102
3214
  /**
3103
3215
  * Twitter Spaces API client.
@@ -3240,4 +3352,4 @@ declare class TwitterClient {
3240
3352
  removeWebhookFromMonitor(webhookId: string, body?: unknown, params?: Record<string, string | number | boolean | undefined>): Promise<Record<string, unknown>>;
3241
3353
  }
3242
3354
 
3243
- export { type CommunityMember as $, AuthenticationError as A, BaseClient as B, ConflictError as C, type UserMention as D, type TweetPlace as E, type Tweet as F, GeoClient as G, type Hashtag as H, InsufficientCreditsError as I, type User as J, type UserAbout as K, ListsClient as L, type Media as M, NotFoundError as N, type UserIds as O, PermissionDeniedError as P, type QueryType as Q, type ResolvedConfig as R, type ScrapeBadgerConfig as S, TwitterClient as T, UsersClient as U, ValidationError as V, WebSocketStreamError as W, type List as X, type CommunityBanner as Y, type CommunityRule as Z, type Community as _, ScrapeBadgerError as a, type Trend as a0, type Location as a1, type PlaceTrends as a2, type Place as a3, type Article as a4, type CommunityNote as a5, type Space as a6, type Broadcast as a7, type ApiResponse as a8, type ListResponse as a9, type FilterRulePricingTiersResponse as aA, type MonitorStatus as aa, type StreamMonitor as ab, type StreamMonitorList as ac, type CreateMonitorParams as ad, type UpdateMonitorParams as ae, type StreamTweet as af, type ConnectedEvent as ag, type PingEvent as ah, type TweetEvent as ai, type ErrorEvent as aj, type StreamEvent as ak, type StreamEventType as al, type DeliveryLog as am, type DeliveryLogList as an, type BillingLog as ao, type BillingLogList as ap, type ConnectOptions as aq, type FilterRuleStatus as ar, type FilterRuleResponse as as, type FilterRuleCreate as at, type FilterRuleUpdate as au, type FilterRulePricingTier as av, type FilterRuleListResponse as aw, type FilterRuleValidateResponse as ax, type FilterRuleDeliveryLog as ay, type FilterRuleDeliveryLogListResponse as az, RateLimitError as b, BlockedError as c, ServerError as d, TimeoutError as e, AccountRestrictedError as f, IPNotAllowedError as g, type BlockKind as h, type BlockingCaptcha as i, type PaginatedResponse as j, type PaginationOptions as k, type IteratorOptions as l, collectAll as m, TweetsClient as n, CommunitiesClient as o, TrendsClient as p, type GeoSearchOptions as q, StreamClient as r, type StreamEmitter as s, SpacesClient as t, type TrendCategory as u, verifyWebhookSignature as v, type CommunityTweetType as w, type PollOption as x, type Poll as y, type Url as z };
3355
+ export { type List as $, AuthenticationError as A, BaseClient as B, ConflictError as C, type CommunityTweetType as D, type PollOption as E, type Poll as F, GeoClient as G, type Url as H, InsufficientCreditsError as I, type Hashtag as J, type UserMention as K, ListsClient as L, type Media as M, NotFoundError as N, type TweetPlace as O, PermissionDeniedError as P, type QueryType as Q, type ResolvedConfig as R, type ScrapeBadgerConfig as S, TimeoutError as T, UsersClient as U, ValidationError as V, WebSocketStreamError as W, type Tweet as X, type User as Y, type UserAbout as Z, type UserIds as _, TwitterClient as a, type CommunityBanner as a0, type CommunityRule as a1, type Community as a2, type CommunityMember as a3, type Trend as a4, type Location as a5, type PlaceTrends as a6, type Place as a7, type Article as a8, type CommunityNote as a9, type FilterRuleListResponse as aA, type FilterRuleValidateResponse as aB, type FilterRuleDeliveryLog as aC, type FilterRuleDeliveryLogListResponse as aD, type FilterRulePricingTiersResponse as aE, type Space as aa, type Broadcast as ab, type ApiResponse as ac, type ListResponse as ad, type MonitorStatus as ae, type StreamMonitor as af, type StreamMonitorList as ag, type CreateMonitorParams as ah, type UpdateMonitorParams as ai, type StreamTweet as aj, type ConnectedEvent as ak, type PingEvent as al, type TweetEvent as am, type ErrorEvent as an, type StreamEvent as ao, type StreamEventType as ap, type DeliveryLog as aq, type DeliveryLogList as ar, type BillingLog as as, type BillingLogList as at, type ConnectOptions as au, type FilterRuleStatus as av, type FilterRuleResponse as aw, type FilterRuleCreate as ax, type FilterRuleUpdate as ay, type FilterRulePricingTier as az, ScrapeBadgerError as b, RateLimitError as c, BlockedError as d, ServerError as e, AccountRestrictedError as f, IPNotAllowedError as g, type BlockKind as h, type BlockingCaptcha as i, type PaginatedResponse as j, type PaginationOptions as k, type IteratorOptions as l, collectAll as m, type WebhookEvent as n, type VerifyWebhookSignatureOptions as o, parseWebhookEvent as p, type RawWebhookBody as q, TweetsClient as r, CommunitiesClient as s, TrendsClient as t, type GeoSearchOptions as u, verifyWebhookSignature as v, StreamClient as w, type StreamEmitter as x, SpacesClient as y, type TrendCategory as z };