serpbit 0.0.0-stage → 0.1.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.
Files changed (5) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +65 -2
  3. package/index.d.ts +277 -0
  4. package/index.js +199 -0
  5. package/package.json +27 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Serpbit
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,66 @@
1
- # Temporary Holding Version
1
+ # serpbit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Google Search, News, Shopping, Images, Videos, Maps, Autocomplete and AI Mode as data, from
4
+ [Serpbit](https://serpbit.com). No dependencies: it uses the platform's `fetch` (Node 18+, Deno, Bun, browsers),
5
+ and comes with TypeScript types.
6
+
7
+ ```sh
8
+ npm install serpbit
9
+ ```
10
+
11
+ ```js
12
+ import Serpbit from "serpbit";
13
+
14
+ const sb = new Serpbit(); // reads SERPBIT_API_KEY; make a key at https://app.serpbit.com/keys
15
+
16
+ const answer = await sb.search("espresso grinder", { gl: "de", hl: "de", pages: 2 });
17
+ for (const r of answer.organic) console.log(r.position, r.title, r.url);
18
+
19
+ // The first three results' pages, as Markdown text: 1 credit a page read.
20
+ const read = await sb.search("how to descale an espresso machine", { content: 3 });
21
+ console.log(read.organic[0].content?.text?.slice(0, 500));
22
+
23
+ // Markdown instead of JSON, for a language model's context.
24
+ console.log(await sb.news("wildfire", { sort: "date", output: "md" }));
25
+ ```
26
+
27
+ Every door of the API has a method: `search`, `news`, `shopping`, `shoppingProduct`, `images`, `videos`, `maps`,
28
+ `autocomplete`, `aiMode`. The second argument holds the door's parameters, as the [docs](https://serpbit.com/docs/)
29
+ name them:
30
+ - `true` is sent as `true`;
31
+ - `undefined`, `null` and `false` are left out;
32
+ - an array is joined with commas.
33
+
34
+ A method resolves to the API's JSON, or to a string with `output: "md"`. `sb.lastRequestId` and `sb.lastCredits`
35
+ give the last answer's id and the credits it spent.
36
+
37
+ ## Errors and retries
38
+
39
+ A failed call rejects with a `SerpbitError`. The subclasses are:
40
+ - `BadRequestError` (400);
41
+ - `AuthenticationError` (401);
42
+ - `InsufficientCreditsError` (402);
43
+ - `RateLimitError` (429, with `retryAfter`);
44
+ - `APIError` (5xx);
45
+ - `APIConnectionError`.
46
+
47
+ Each carries `status`, `code` and `requestId`. Quote the `requestId` to support.
48
+
49
+ Calls are retried twice on 429 and 5xx (set with `maxRetries`), waiting as `Retry-After` says. Every attempt of one
50
+ call carries the same `Idempotency-Key`, so an answer lost on the way is given back free instead of being billed
51
+ twice. Pass `idempotencyKey` to use your own, and `signal` to cancel a call.
52
+
53
+ Keep the key on a server: an API key in a browser page is anyone's to read.
54
+
55
+ ## Batches
56
+
57
+ ```js
58
+ const b = await sb.batch(keywords.map((kw) => ({ path: "/v1/search", params: { q: kw, gl: "us" }, id: kw })),
59
+ { webhook: "https://example.com/serpbit" });
60
+ await sb.getBatch(b.id); // status, and each call's
61
+ await sb.batchResults(b.id, { offset: 0 }); // the answers, 100 at a time, for a day after it ends
62
+
63
+ // In your webhook: check the event is Serpbit's before you trust it (pass the raw body).
64
+ import { verifyWebhook } from "serpbit";
65
+ const ok = await verifyWebhook(rawBody, req.headers["serpbit-signature"], apiKey);
66
+ ```
package/index.d.ts ADDED
@@ -0,0 +1,277 @@
1
+ // Types of the Serpbit API's answers: the fields most code reads. Every answer may carry more; see
2
+ // https://serpbit.com/docs/ for all of them.
3
+
4
+ export declare const VERSION: string;
5
+
6
+ export interface ClientOptions {
7
+ /** Defaults to the SERPBIT_API_KEY environment variable. */
8
+ apiKey?: string;
9
+ /** Defaults to SERPBIT_BASE_URL, then https://api.serpbit.com. */
10
+ baseURL?: string;
11
+ /** Milliseconds a call may take, each attempt. Default 90000. */
12
+ timeout?: number;
13
+ /** Retries on 429 and 5xx, each with the same Idempotency-Key. Default 2. */
14
+ maxRetries?: number;
15
+ /** A fetch of your own (a proxy, a test). */
16
+ fetch?: typeof fetch;
17
+ }
18
+
19
+ /** Any parameter of a door, as the docs name it: true is sent as true; undefined, null and false are left out. */
20
+ export type ParamValue = string | number | boolean | null | undefined | ReadonlyArray<string | number>;
21
+
22
+ export interface RequestOptions {
23
+ idempotencyKey?: string;
24
+ signal?: AbortSignal;
25
+ }
26
+
27
+ export interface SearchParams extends RequestOptions {
28
+ gl?: string;
29
+ hl?: string;
30
+ location?: string;
31
+ uule?: string;
32
+ device?: "desktop" | "mobile" | "iphone" | "ipad";
33
+ pages?: number;
34
+ num?: number;
35
+ start?: number;
36
+ /** Read the first N results' pages as text (1 credit a page read); true reads 10. */
37
+ content?: number | boolean;
38
+ content_chars?: number;
39
+ ai_overview?: boolean;
40
+ safe?: "off" | "active";
41
+ lr?: string;
42
+ tbs?: string;
43
+ nfpr?: boolean | 1 | 0;
44
+ filter?: 0 | 1;
45
+ html?: boolean;
46
+ no_cache?: boolean;
47
+ output?: "json" | "md";
48
+ [param: string]: ParamValue | AbortSignal;
49
+ }
50
+
51
+ export interface Meta { elapsed_ms: number; credits: number }
52
+ export interface Page { page: number; results: number; html?: string }
53
+ export interface Pagination { next_start: number | null }
54
+
55
+ /** A result's page read as text (content=N), or why it could not be read. */
56
+ export interface Content {
57
+ url?: string;
58
+ title?: string;
59
+ byline?: string;
60
+ site_name?: string;
61
+ published_at?: string;
62
+ lang?: string;
63
+ /** The page's main text as Markdown. */
64
+ text?: string;
65
+ chars?: number;
66
+ truncated?: boolean;
67
+ error?: "timeout" | "blocked" | "not_found" | "not_html" | "unreadable" | "unresolved" | "failed";
68
+ }
69
+
70
+ export interface OrganicResult {
71
+ position: number;
72
+ page: number;
73
+ title: string;
74
+ url: string;
75
+ domain?: string;
76
+ displayed_url?: string;
77
+ snippet?: string;
78
+ content?: Content;
79
+ }
80
+
81
+ export interface SearchResponse {
82
+ request_id: string;
83
+ search: Record<string, unknown>;
84
+ ai_overview?: { text: string; sources?: Array<{ title: string; url: string }>; [k: string]: unknown };
85
+ organic: OrganicResult[];
86
+ related_questions?: unknown[];
87
+ related_searches?: unknown[];
88
+ knowledge_graph?: Record<string, unknown>;
89
+ top_stories?: unknown[];
90
+ showing_results_for?: string;
91
+ pages: Page[];
92
+ pagination: Pagination;
93
+ meta: Meta;
94
+ [k: string]: unknown;
95
+ }
96
+
97
+ export interface NewsArticle {
98
+ position: number;
99
+ page: number;
100
+ title: string;
101
+ url: string;
102
+ domain?: string;
103
+ source?: string;
104
+ date?: string;
105
+ published_at?: string;
106
+ snippet?: string;
107
+ thumbnail?: string;
108
+ story_id?: string;
109
+ content?: Content;
110
+ }
111
+ export interface NewsResponse {
112
+ request_id: string; search: Record<string, unknown>; news: NewsArticle[]; pages: Page[]; pagination: Pagination;
113
+ meta: Meta; [k: string]: unknown;
114
+ }
115
+
116
+ export interface ShoppingProduct {
117
+ position: number;
118
+ page: number;
119
+ title: string;
120
+ product_id?: string;
121
+ product_link?: string;
122
+ source?: string;
123
+ price?: string;
124
+ extracted_price?: number;
125
+ old_price?: string;
126
+ rating?: number;
127
+ reviews?: number;
128
+ delivery?: string;
129
+ thumbnail?: string;
130
+ [k: string]: unknown;
131
+ }
132
+ export interface ShoppingResponse {
133
+ request_id: string; search: Record<string, unknown>; shopping: ShoppingProduct[]; filters?: unknown[]; pages: Page[];
134
+ pagination: Pagination; meta: Meta; [k: string]: unknown;
135
+ }
136
+
137
+ export interface Image {
138
+ position: number; page: number; title: string; url: string; source?: string; original?: string;
139
+ original_width?: number; original_height?: number; thumbnail?: string; [k: string]: unknown;
140
+ }
141
+ export interface ImagesResponse {
142
+ request_id: string; search: Record<string, unknown>; images: Image[]; suggested_searches?: Array<{ name: string; q: string }>;
143
+ pages: Page[]; pagination: Pagination; meta: Meta; [k: string]: unknown;
144
+ }
145
+
146
+ export interface Video {
147
+ position: number; page: number; title: string; url: string; snippet?: string; duration?: string; duration_seconds?: number;
148
+ platform?: string; channel?: string; date?: string; thumbnail?: string; video_id?: string;
149
+ }
150
+ export interface VideosResponse {
151
+ request_id: string; search: Record<string, unknown>; videos: Video[]; pages: Page[]; pagination: Pagination; meta: Meta;
152
+ [k: string]: unknown;
153
+ }
154
+
155
+ export interface Place {
156
+ position: number; page: number; title: string; link?: string; place_id?: string; rating?: number; reviews?: number;
157
+ price?: string; type?: string; address?: string; hours?: string; phone?: string; website?: string;
158
+ gps_coordinates?: { latitude: number; longitude: number }; [k: string]: unknown;
159
+ }
160
+ export interface MapsResponse {
161
+ request_id: string; search: Record<string, unknown>; places: Place[]; pages: Page[]; pagination: Pagination; meta: Meta;
162
+ [k: string]: unknown;
163
+ }
164
+
165
+ export interface AutocompleteResponse {
166
+ request_id: string;
167
+ search: Record<string, unknown>;
168
+ suggestions: Array<{ position: number; value: string; type?: string; relevance?: number; [k: string]: unknown }>;
169
+ meta: Meta;
170
+ [k: string]: unknown;
171
+ }
172
+
173
+ export interface AIModeResponse {
174
+ request_id: string;
175
+ search: Record<string, unknown>;
176
+ text_blocks: unknown[];
177
+ references: Array<{ title?: string; link?: string; snippet?: string; source?: string; [k: string]: unknown }>;
178
+ local_results?: unknown[];
179
+ markdown: string;
180
+ meta: Meta;
181
+ [k: string]: unknown;
182
+ }
183
+
184
+ export interface ProductResponse {
185
+ request_id: string; search: Record<string, unknown>; product: Record<string, unknown>; sellers: unknown[];
186
+ sellers_count: number; complete: boolean; meta: Meta; [k: string]: unknown;
187
+ }
188
+
189
+ type Md<P> = P & { output: "md" };
190
+ type Params = { [param: string]: ParamValue | AbortSignal } & RequestOptions;
191
+
192
+ export declare class Serpbit {
193
+ constructor(options?: ClientOptions);
194
+ apiKey: string;
195
+ baseURL: string;
196
+ timeout: number;
197
+ maxRetries: number;
198
+ lastRequestId?: string;
199
+ lastCredits?: number;
200
+
201
+ search(q: string | undefined, params: Md<SearchParams>): Promise<string>;
202
+ search(q?: string, params?: SearchParams): Promise<SearchResponse>;
203
+ news(q: string, params: Md<SearchParams>): Promise<string>;
204
+ news(q: string, params?: SearchParams): Promise<NewsResponse>;
205
+ shopping(q: string, params: Md<Params>): Promise<string>;
206
+ shopping(q: string, params?: Params): Promise<ShoppingResponse>;
207
+ shoppingProduct(productId: string | undefined, params: Md<Params>): Promise<string>;
208
+ shoppingProduct(productId?: string, params?: Params): Promise<ProductResponse>;
209
+ images(q: string, params: Md<Params>): Promise<string>;
210
+ images(q: string, params?: Params): Promise<ImagesResponse>;
211
+ videos(q: string, params: Md<Params>): Promise<string>;
212
+ videos(q: string, params?: Params): Promise<VideosResponse>;
213
+ maps(q: string, params: Md<Params>): Promise<string>;
214
+ maps(q: string, params?: Params): Promise<MapsResponse>;
215
+ autocomplete(q: string, params?: Params): Promise<AutocompleteResponse>;
216
+ aiMode(q: string, params: Md<Params>): Promise<string>;
217
+ aiMode(q: string, params?: Params): Promise<AIModeResponse>;
218
+ /** Start a batch of up to 1,000 calls; answers go to the webhook and stay readable a day after it ends. */
219
+ batch(requests: BatchRequest[], options?: { webhook?: string } & RequestOptions): Promise<BatchSummary>;
220
+ getBatch(id: string, params?: RequestOptions): Promise<BatchSummary>;
221
+ batchResults(id: string, options?: { offset?: number; limit?: number } & RequestOptions): Promise<BatchResults>;
222
+ request<T = unknown>(path: string, params?: Params, options?: { method?: "GET" | "POST"; body?: unknown }): Promise<T>;
223
+ }
224
+
225
+ export interface BatchRequest {
226
+ path: "/v1/search" | "/v1/news" | "/v1/shopping" | "/v1/shopping/product" | "/v1/images" | "/v1/videos" | "/v1/maps" | "/v1/autocomplete" | "/v1/ai-mode";
227
+ params?: { [param: string]: ParamValue };
228
+ /** Your own reference, echoed with the answer. */
229
+ id?: string;
230
+ }
231
+ export interface BatchItem {
232
+ index: number;
233
+ id?: string;
234
+ path: string;
235
+ /** The call's HTTP status; absent while it waits or runs. */
236
+ status?: number;
237
+ credits?: number;
238
+ request_id?: string;
239
+ /** With a webhook: whether it took the answer. */
240
+ delivered?: boolean;
241
+ /** The API's answer, or its error: as the call's own door gives it. */
242
+ answer?: unknown;
243
+ }
244
+ export interface BatchSummary {
245
+ id: string;
246
+ status: "running" | "completed";
247
+ total: number;
248
+ done: number;
249
+ succeeded: number;
250
+ failed: number;
251
+ credits: number;
252
+ webhook?: string;
253
+ created_at: string;
254
+ completed_at?: string;
255
+ expires_at?: string;
256
+ items?: BatchItem[];
257
+ }
258
+ export interface BatchResults extends BatchSummary { offset: number; limit: number; items: BatchItem[] }
259
+
260
+ /** Whether a webhook's raw body is Serpbit's: its Serpbit-Signature checked with the API key that started the batch. */
261
+ export declare function verifyWebhook(body: string | ArrayBuffer | Uint8Array, signature: string | null | undefined, apiKey: string,
262
+ options?: { tolerance?: number }): Promise<boolean>;
263
+
264
+ export declare class SerpbitError extends Error {
265
+ status?: number;
266
+ code?: string;
267
+ requestId?: string;
268
+ body?: Record<string, unknown>;
269
+ }
270
+ export declare class BadRequestError extends SerpbitError {}
271
+ export declare class AuthenticationError extends SerpbitError {}
272
+ export declare class InsufficientCreditsError extends SerpbitError {}
273
+ export declare class RateLimitError extends SerpbitError { retryAfter?: number }
274
+ export declare class APIError extends SerpbitError {}
275
+ export declare class APIConnectionError extends SerpbitError {}
276
+
277
+ export default Serpbit;
package/index.js ADDED
@@ -0,0 +1,199 @@
1
+ // Serpbit: Google results as data. A small client for https://api.serpbit.com on the platform's fetch (Node 18+,
2
+ // Deno, Bun, browsers), with no dependencies.
3
+
4
+ export const VERSION = "0.1.0";
5
+ const DEFAULT_BASE_URL = "https://api.serpbit.com";
6
+ // A call is retried on these: the rate limit (after Retry-After), Google giving no page in time, our side failing.
7
+ const RETRY = new Set([429, 500, 502, 503, 504]);
8
+
9
+ /** A call that did not answer: status, code and requestId are the API's (requestId is what support asks for). */
10
+ export class SerpbitError extends Error {
11
+ constructor(message, { status, code, requestId, body } = {}) {
12
+ super(message);
13
+ this.name = new.target.name;
14
+ this.status = status;
15
+ this.code = code;
16
+ this.requestId = requestId;
17
+ this.body = body;
18
+ }
19
+ }
20
+ export class BadRequestError extends SerpbitError {}
21
+ export class AuthenticationError extends SerpbitError {}
22
+ export class InsufficientCreditsError extends SerpbitError {}
23
+ export class RateLimitError extends SerpbitError {
24
+ constructor(message, opts = {}) {
25
+ super(message, opts);
26
+ this.retryAfter = opts.retryAfter;
27
+ }
28
+ }
29
+ export class APIError extends SerpbitError {}
30
+ export class APIConnectionError extends SerpbitError {}
31
+
32
+ function errorFor(status, message, opts) {
33
+ if (status === 400) return new BadRequestError(message, opts);
34
+ if (status === 401) return new AuthenticationError(message, opts);
35
+ if (status === 402) return new InsufficientCreditsError(message, opts);
36
+ if (status === 429) return new RateLimitError(message, opts);
37
+ if (status >= 500) return new APIError(message, opts);
38
+ return new SerpbitError(message, opts);
39
+ }
40
+
41
+ const env = (name) => (typeof process !== "undefined" && process.env ? process.env[name] : undefined);
42
+
43
+ export class Serpbit {
44
+ /**
45
+ * @param {{apiKey?: string, baseURL?: string, timeout?: number, maxRetries?: number, fetch?: typeof fetch}} [options]
46
+ */
47
+ constructor({ apiKey, baseURL, timeout = 90_000, maxRetries = 2, fetch: f } = {}) {
48
+ this.apiKey = apiKey ?? env("SERPBIT_API_KEY");
49
+ if (!this.apiKey) {
50
+ throw new SerpbitError("no API key: pass apiKey or set SERPBIT_API_KEY (keys are made at https://app.serpbit.com/keys)");
51
+ }
52
+ this.baseURL = (baseURL ?? env("SERPBIT_BASE_URL") ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
53
+ this.timeout = timeout;
54
+ this.maxRetries = Math.max(0, maxRetries);
55
+ this.fetch = f ?? globalThis.fetch.bind(globalThis);
56
+ // The last answer's id and credits, from its headers: a Markdown answer has no JSON to carry them.
57
+ this.lastRequestId = undefined;
58
+ this.lastCredits = undefined;
59
+ }
60
+
61
+ /** Google's results page (/v1/search). `url` takes a Google results address instead of `q`. */
62
+ search(q, params) { return this.request("/v1/search", { q, ...params }); }
63
+ /** Google's News tab (/v1/news). */
64
+ news(q, params) { return this.request("/v1/news", { q, ...params }); }
65
+ /** Google's Shopping tab (/v1/shopping). */
66
+ shopping(q, params) { return this.request("/v1/shopping", { q, ...params }); }
67
+ /** One product and every store's offer (/v1/shopping/product). */
68
+ shoppingProduct(productId, params) { return this.request("/v1/shopping/product", { product_id: productId, ...params }); }
69
+ /** Google's Images tab (/v1/images). */
70
+ images(q, params) { return this.request("/v1/images", { q, ...params }); }
71
+ /** Google's Videos tab (/v1/videos). */
72
+ videos(q, params) { return this.request("/v1/videos", { q, ...params }); }
73
+ /** Places as Google Maps lists them (/v1/maps). */
74
+ maps(q, params) { return this.request("/v1/maps", { q, ...params }); }
75
+ /** Google's search-box suggestions (/v1/autocomplete). */
76
+ autocomplete(q, params) { return this.request("/v1/autocomplete", { q, ...params }); }
77
+ /** Google's AI Mode answer with its sources (/v1/ai-mode). */
78
+ aiMode(q, params) { return this.request("/v1/ai-mode", { q, ...params }); }
79
+
80
+ /**
81
+ * Start a batch of up to 1,000 calls (POST /v1/batches), each { path: "/v1/search", params: {...}, id }. The calls
82
+ * run in the background at the key's limits; each answer goes to the webhook as it comes (check it with
83
+ * verifyWebhook) and stays readable with batchResults for a day after the batch ends.
84
+ */
85
+ batch(requests, { webhook, idempotencyKey, signal } = {}) {
86
+ const clean = (params = {}) => Object.fromEntries(Object.entries(params).filter(([, v]) => v !== undefined && v !== null && v !== false));
87
+ const body = { requests: requests.map((r) => ({ ...r, params: clean(r.params) })) };
88
+ if (webhook) body.webhook = webhook;
89
+ return this.request("/v1/batches", { idempotencyKey, signal }, { method: "POST", body });
90
+ }
91
+ /** A batch's state and each call's status (GET /v1/batches/{id}). */
92
+ getBatch(id, params) { return this.request("/v1/batches/" + encodeURIComponent(id), { ...params }); }
93
+ /** A batch's answers, limit (at most 100) from offset (GET /v1/batches/{id}/results). */
94
+ batchResults(id, { offset = 0, limit = 100, ...params } = {}) {
95
+ return this.request("/v1/batches/" + encodeURIComponent(id) + "/results", { offset, limit, ...params });
96
+ }
97
+
98
+ /**
99
+ * GET path with params: true is sent as true; undefined, null and false are left out; an array is joined by
100
+ * commas. Resolves to the JSON, or to a string with output "md". Every attempt carries one Idempotency-Key, so an
101
+ * answer lost on the way is given back free rather than billed again.
102
+ */
103
+ async request(path, params = {}, { method = "GET", body } = {}) {
104
+ const { idempotencyKey, signal, ...rest } = params;
105
+ const query = new URLSearchParams();
106
+ for (const [k, v] of Object.entries(rest)) {
107
+ if (v === undefined || v === null || v === false) continue;
108
+ query.set(k, v === true ? "true" : Array.isArray(v) ? v.join(",") : String(v));
109
+ }
110
+ const qs = query.toString();
111
+ const url = this.baseURL + path + (qs ? "?" + qs : "");
112
+ const key = idempotencyKey ?? (this.maxRetries ? randomKey() : undefined);
113
+ const headers = { Authorization: "Bearer " + this.apiKey, Accept: "application/json, text/markdown" };
114
+ if (key) headers["Idempotency-Key"] = key;
115
+ if (typeof window === "undefined") headers["User-Agent"] = "serpbit-js/" + VERSION;
116
+ const payload = body === undefined ? undefined : JSON.stringify(body);
117
+ if (payload !== undefined) headers["Content-Type"] = "application/json";
118
+
119
+ for (let attempt = 0; ; attempt++) {
120
+ const ctl = new AbortController();
121
+ const timer = setTimeout(() => ctl.abort(new Error("timed out")), this.timeout);
122
+ const onAbort = () => ctl.abort(signal.reason);
123
+ signal?.addEventListener("abort", onAbort, { once: true });
124
+ let resp;
125
+ try {
126
+ resp = await this.fetch(url, { method, headers, body: payload, signal: ctl.signal });
127
+ } catch (err) {
128
+ clearTimeout(timer);
129
+ signal?.removeEventListener("abort", onAbort);
130
+ if (signal?.aborted) throw err;
131
+ if (attempt < this.maxRetries) {
132
+ await sleep(backoff(attempt));
133
+ continue;
134
+ }
135
+ throw new APIConnectionError(`could not reach ${this.baseURL}: ${err?.message ?? err}`);
136
+ }
137
+ const text = await resp.text().finally(() => {
138
+ clearTimeout(timer);
139
+ signal?.removeEventListener("abort", onAbort);
140
+ });
141
+ if (resp.ok) {
142
+ this.lastRequestId = resp.headers.get("X-Request-Id") ?? undefined;
143
+ const credits = resp.headers.get("X-Credits");
144
+ this.lastCredits = credits === null ? undefined : Number(credits);
145
+ return (resp.headers.get("Content-Type") ?? "").startsWith("application/json") ? JSON.parse(text) : text;
146
+ }
147
+ const ra = resp.headers.get("Retry-After");
148
+ const retryAfter = ra === null || Number.isNaN(Number(ra)) ? undefined : Number(ra);
149
+ if (RETRY.has(resp.status) && attempt < this.maxRetries) {
150
+ await sleep(backoff(attempt, retryAfter));
151
+ continue;
152
+ }
153
+ let body = {};
154
+ try {
155
+ body = JSON.parse(text);
156
+ } catch {}
157
+ throw errorFor(resp.status, body.message || `the API answered ${resp.status}`, {
158
+ status: resp.status, code: body.error, requestId: body.request_id ?? resp.headers.get("X-Request-Id") ?? undefined,
159
+ body, retryAfter,
160
+ });
161
+ }
162
+ }
163
+ }
164
+
165
+ /**
166
+ * Whether a webhook's body is Serpbit's: its Serpbit-Signature header ("t=<unix>,v1=<hex>") is the HMAC-SHA256 of
167
+ * "t.body" with the API key that started the batch, sent within tolerance seconds. Pass the raw body as received.
168
+ */
169
+ export async function verifyWebhook(body, signature, apiKey, { tolerance = 300 } = {}) {
170
+ if (!signature || !apiKey) return false;
171
+ const parts = Object.fromEntries(String(signature).split(",").map((p) => p.split("=", 2)));
172
+ const ts = parts.t ?? "", sig = parts.v1 ?? "";
173
+ if (!/^\d+$/.test(ts) || !sig) return false;
174
+ if (tolerance && Math.abs(Date.now() / 1000 - Number(ts)) > tolerance) return false;
175
+ const subtle = globalThis.crypto?.subtle ?? (await import("node:crypto")).webcrypto.subtle;
176
+ const enc = new TextEncoder();
177
+ const raw = typeof body === "string" ? enc.encode(body) : new Uint8Array(body);
178
+ const key = await subtle.importKey("raw", enc.encode(apiKey), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
179
+ const msg = new Uint8Array([...enc.encode(ts + "."), ...raw]);
180
+ const want = Array.from(new Uint8Array(await subtle.sign("HMAC", key, msg)), (b) => b.toString(16).padStart(2, "0")).join("");
181
+ if (want.length !== sig.length) return false;
182
+ let diff = 0;
183
+ for (let i = 0; i < want.length; i++) diff |= want.charCodeAt(i) ^ sig.charCodeAt(i);
184
+ return diff === 0;
185
+ }
186
+
187
+ function randomKey() {
188
+ if (globalThis.crypto?.randomUUID) return globalThis.crypto.randomUUID().replace(/-/g, "");
189
+ return Array.from({ length: 32 }, () => Math.floor(Math.random() * 16).toString(16)).join("");
190
+ }
191
+
192
+ function backoff(attempt, retryAfter) {
193
+ if (retryAfter !== undefined) return Math.min(retryAfter, 60) * 1000;
194
+ return Math.min(500 * 2 ** attempt, 8000) * (0.75 + Math.random() / 2);
195
+ }
196
+
197
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
198
+
199
+ export default Serpbit;
package/package.json CHANGED
@@ -1,6 +1,29 @@
1
1
  {
2
2
  "name": "serpbit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Google Search, News, Shopping, Images, Videos, Maps, Autocomplete and AI Mode as data: the Serpbit API client.",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./index.d.ts",
9
+ "default": "./index.js"
10
+ }
11
+ },
12
+ "main": "./index.js",
13
+ "types": "./index.d.ts",
14
+ "files": ["index.js", "index.d.ts", "README.md", "LICENSE"],
15
+ "engines": {
16
+ "node": ">=18"
17
+ },
18
+ "scripts": {
19
+ "test": "node --test test/client.test.js"
20
+ },
21
+ "keywords": ["serp", "google search api", "serp api", "web search", "ai agents", "rag", "mcp"],
22
+ "homepage": "https://serpbit.com",
23
+ "bugs": {
24
+ "email": "support@serpbit.com"
25
+ },
26
+ "author": "Serpbit <support@serpbit.com>",
27
+ "license": "MIT",
28
+ "sideEffects": false
29
+ }