firecrawl 1.18.4 → 1.18.5
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 +1149 -0
- package/dist/index.d.cts +669 -0
- package/dist/index.d.ts +669 -0
- package/dist/index.js +1113 -0
- package/dump.rdb +0 -0
- package/package.json +1 -1
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,1149 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var src_exports = {};
|
|
32
|
+
__export(src_exports, {
|
|
33
|
+
CrawlWatcher: () => CrawlWatcher,
|
|
34
|
+
FirecrawlError: () => FirecrawlError,
|
|
35
|
+
default: () => FirecrawlApp
|
|
36
|
+
});
|
|
37
|
+
module.exports = __toCommonJS(src_exports);
|
|
38
|
+
var import_axios = __toESM(require("axios"), 1);
|
|
39
|
+
var zt = __toESM(require("zod"), 1);
|
|
40
|
+
var import_zod_to_json_schema = require("zod-to-json-schema");
|
|
41
|
+
var import_isows = require("isows");
|
|
42
|
+
var import_typescript_event_target = require("typescript-event-target");
|
|
43
|
+
var FirecrawlError = class extends Error {
|
|
44
|
+
statusCode;
|
|
45
|
+
details;
|
|
46
|
+
constructor(message, statusCode, details) {
|
|
47
|
+
super(message);
|
|
48
|
+
this.statusCode = statusCode;
|
|
49
|
+
this.details = details;
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
var FirecrawlApp = class {
|
|
53
|
+
apiKey;
|
|
54
|
+
apiUrl;
|
|
55
|
+
isCloudService(url) {
|
|
56
|
+
return url.includes("api.firecrawl.dev");
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Initializes a new instance of the FirecrawlApp class.
|
|
60
|
+
* @param config - Configuration options for the FirecrawlApp instance.
|
|
61
|
+
*/
|
|
62
|
+
constructor({ apiKey = null, apiUrl = null }) {
|
|
63
|
+
const baseUrl = apiUrl || "https://api.firecrawl.dev";
|
|
64
|
+
if (this.isCloudService(baseUrl) && typeof apiKey !== "string") {
|
|
65
|
+
throw new FirecrawlError("No API key provided", 401);
|
|
66
|
+
}
|
|
67
|
+
this.apiKey = apiKey || "";
|
|
68
|
+
this.apiUrl = baseUrl;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Scrapes a URL using the Firecrawl API.
|
|
72
|
+
* @param url - The URL to scrape.
|
|
73
|
+
* @param params - Additional parameters for the scrape request.
|
|
74
|
+
* @returns The response from the scrape operation.
|
|
75
|
+
*/
|
|
76
|
+
async scrapeUrl(url, params) {
|
|
77
|
+
const headers = {
|
|
78
|
+
"Content-Type": "application/json",
|
|
79
|
+
Authorization: `Bearer ${this.apiKey}`
|
|
80
|
+
};
|
|
81
|
+
let jsonData = { url, ...params };
|
|
82
|
+
if (jsonData?.extract?.schema) {
|
|
83
|
+
let schema = jsonData.extract.schema;
|
|
84
|
+
try {
|
|
85
|
+
schema = (0, import_zod_to_json_schema.zodToJsonSchema)(schema);
|
|
86
|
+
} catch (error) {
|
|
87
|
+
}
|
|
88
|
+
jsonData = {
|
|
89
|
+
...jsonData,
|
|
90
|
+
extract: {
|
|
91
|
+
...jsonData.extract,
|
|
92
|
+
schema
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
if (jsonData?.jsonOptions?.schema) {
|
|
97
|
+
let schema = jsonData.jsonOptions.schema;
|
|
98
|
+
try {
|
|
99
|
+
schema = (0, import_zod_to_json_schema.zodToJsonSchema)(schema);
|
|
100
|
+
} catch (error) {
|
|
101
|
+
}
|
|
102
|
+
jsonData = {
|
|
103
|
+
...jsonData,
|
|
104
|
+
jsonOptions: {
|
|
105
|
+
...jsonData.jsonOptions,
|
|
106
|
+
schema
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
try {
|
|
111
|
+
const response = await import_axios.default.post(
|
|
112
|
+
this.apiUrl + `/v1/scrape`,
|
|
113
|
+
jsonData,
|
|
114
|
+
{ headers, timeout: params?.timeout !== void 0 ? params.timeout + 5e3 : void 0 }
|
|
115
|
+
);
|
|
116
|
+
if (response.status === 200) {
|
|
117
|
+
const responseData = response.data;
|
|
118
|
+
if (responseData.success) {
|
|
119
|
+
return {
|
|
120
|
+
success: true,
|
|
121
|
+
warning: responseData.warning,
|
|
122
|
+
error: responseData.error,
|
|
123
|
+
...responseData.data
|
|
124
|
+
};
|
|
125
|
+
} else {
|
|
126
|
+
throw new FirecrawlError(`Failed to scrape URL. Error: ${responseData.error}`, response.status);
|
|
127
|
+
}
|
|
128
|
+
} else {
|
|
129
|
+
this.handleError(response, "scrape URL");
|
|
130
|
+
}
|
|
131
|
+
} catch (error) {
|
|
132
|
+
this.handleError(error.response, "scrape URL");
|
|
133
|
+
}
|
|
134
|
+
return { success: false, error: "Internal server error." };
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Searches using the Firecrawl API and optionally scrapes the results.
|
|
138
|
+
* @param query - The search query string.
|
|
139
|
+
* @param params - Optional parameters for the search request.
|
|
140
|
+
* @returns The response from the search operation.
|
|
141
|
+
*/
|
|
142
|
+
async search(query, params) {
|
|
143
|
+
const headers = {
|
|
144
|
+
"Content-Type": "application/json",
|
|
145
|
+
Authorization: `Bearer ${this.apiKey}`
|
|
146
|
+
};
|
|
147
|
+
let jsonData = {
|
|
148
|
+
query,
|
|
149
|
+
limit: params?.limit ?? 5,
|
|
150
|
+
tbs: params?.tbs,
|
|
151
|
+
filter: params?.filter,
|
|
152
|
+
lang: params?.lang ?? "en",
|
|
153
|
+
country: params?.country ?? "us",
|
|
154
|
+
location: params?.location,
|
|
155
|
+
origin: params?.origin ?? "api",
|
|
156
|
+
timeout: params?.timeout ?? 6e4,
|
|
157
|
+
scrapeOptions: params?.scrapeOptions ?? { formats: [] }
|
|
158
|
+
};
|
|
159
|
+
if (jsonData?.scrapeOptions?.extract?.schema) {
|
|
160
|
+
let schema = jsonData.scrapeOptions.extract.schema;
|
|
161
|
+
try {
|
|
162
|
+
schema = (0, import_zod_to_json_schema.zodToJsonSchema)(schema);
|
|
163
|
+
} catch (error) {
|
|
164
|
+
}
|
|
165
|
+
jsonData = {
|
|
166
|
+
...jsonData,
|
|
167
|
+
scrapeOptions: {
|
|
168
|
+
...jsonData.scrapeOptions,
|
|
169
|
+
extract: {
|
|
170
|
+
...jsonData.scrapeOptions.extract,
|
|
171
|
+
schema
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
try {
|
|
177
|
+
const response = await this.postRequest(
|
|
178
|
+
this.apiUrl + `/v1/search`,
|
|
179
|
+
jsonData,
|
|
180
|
+
headers
|
|
181
|
+
);
|
|
182
|
+
if (response.status === 200) {
|
|
183
|
+
const responseData = response.data;
|
|
184
|
+
if (responseData.success) {
|
|
185
|
+
return {
|
|
186
|
+
success: true,
|
|
187
|
+
data: responseData.data,
|
|
188
|
+
warning: responseData.warning
|
|
189
|
+
};
|
|
190
|
+
} else {
|
|
191
|
+
throw new FirecrawlError(`Failed to search. Error: ${responseData.error}`, response.status);
|
|
192
|
+
}
|
|
193
|
+
} else {
|
|
194
|
+
this.handleError(response, "search");
|
|
195
|
+
}
|
|
196
|
+
} catch (error) {
|
|
197
|
+
if (error.response?.data?.error) {
|
|
198
|
+
throw new FirecrawlError(`Request failed with status code ${error.response.status}. Error: ${error.response.data.error} ${error.response.data.details ? ` - ${JSON.stringify(error.response.data.details)}` : ""}`, error.response.status);
|
|
199
|
+
} else {
|
|
200
|
+
throw new FirecrawlError(error.message, 500);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return { success: false, error: "Internal server error.", data: [] };
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Initiates a crawl job for a URL using the Firecrawl API.
|
|
207
|
+
* @param url - The URL to crawl.
|
|
208
|
+
* @param params - Additional parameters for the crawl request.
|
|
209
|
+
* @param pollInterval - Time in seconds for job status checks.
|
|
210
|
+
* @param idempotencyKey - Optional idempotency key for the request.
|
|
211
|
+
* @returns The response from the crawl operation.
|
|
212
|
+
*/
|
|
213
|
+
async crawlUrl(url, params, pollInterval = 2, idempotencyKey) {
|
|
214
|
+
const headers = this.prepareHeaders(idempotencyKey);
|
|
215
|
+
let jsonData = { url, ...params };
|
|
216
|
+
try {
|
|
217
|
+
const response = await this.postRequest(
|
|
218
|
+
this.apiUrl + `/v1/crawl`,
|
|
219
|
+
jsonData,
|
|
220
|
+
headers
|
|
221
|
+
);
|
|
222
|
+
if (response.status === 200) {
|
|
223
|
+
const id = response.data.id;
|
|
224
|
+
return this.monitorJobStatus(id, headers, pollInterval);
|
|
225
|
+
} else {
|
|
226
|
+
this.handleError(response, "start crawl job");
|
|
227
|
+
}
|
|
228
|
+
} catch (error) {
|
|
229
|
+
if (error.response?.data?.error) {
|
|
230
|
+
throw new FirecrawlError(`Request failed with status code ${error.response.status}. Error: ${error.response.data.error} ${error.response.data.details ? ` - ${JSON.stringify(error.response.data.details)}` : ""}`, error.response.status);
|
|
231
|
+
} else {
|
|
232
|
+
throw new FirecrawlError(error.message, 500);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
return { success: false, error: "Internal server error." };
|
|
236
|
+
}
|
|
237
|
+
async asyncCrawlUrl(url, params, idempotencyKey) {
|
|
238
|
+
const headers = this.prepareHeaders(idempotencyKey);
|
|
239
|
+
let jsonData = { url, ...params };
|
|
240
|
+
try {
|
|
241
|
+
const response = await this.postRequest(
|
|
242
|
+
this.apiUrl + `/v1/crawl`,
|
|
243
|
+
jsonData,
|
|
244
|
+
headers
|
|
245
|
+
);
|
|
246
|
+
if (response.status === 200) {
|
|
247
|
+
return response.data;
|
|
248
|
+
} else {
|
|
249
|
+
this.handleError(response, "start crawl job");
|
|
250
|
+
}
|
|
251
|
+
} catch (error) {
|
|
252
|
+
if (error.response?.data?.error) {
|
|
253
|
+
throw new FirecrawlError(`Request failed with status code ${error.response.status}. Error: ${error.response.data.error} ${error.response.data.details ? ` - ${JSON.stringify(error.response.data.details)}` : ""}`, error.response.status);
|
|
254
|
+
} else {
|
|
255
|
+
throw new FirecrawlError(error.message, 500);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
return { success: false, error: "Internal server error." };
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* Checks the status of a crawl job using the Firecrawl API.
|
|
262
|
+
* @param id - The ID of the crawl operation.
|
|
263
|
+
* @param getAllData - Paginate through all the pages of documents, returning the full list of all documents. (default: `false`)
|
|
264
|
+
* @param nextURL - The `next` URL from the previous crawl status. Only required if you're not manually increasing `skip`. Only used when `getAllData = false`.
|
|
265
|
+
* @param skip - How many entries to skip to paginate. Only required if you're not providing `nextURL`. Only used when `getAllData = false`.
|
|
266
|
+
* @param limit - How many entries to return. Only used when `getAllData = false`.
|
|
267
|
+
* @returns The response containing the job status.
|
|
268
|
+
*/
|
|
269
|
+
async checkCrawlStatus(id, getAllData = false, nextURL, skip, limit) {
|
|
270
|
+
if (!id) {
|
|
271
|
+
throw new FirecrawlError("No crawl ID provided", 400);
|
|
272
|
+
}
|
|
273
|
+
const headers = this.prepareHeaders();
|
|
274
|
+
const targetURL = new URL(nextURL ?? `${this.apiUrl}/v1/crawl/${id}`);
|
|
275
|
+
if (skip !== void 0) {
|
|
276
|
+
targetURL.searchParams.set("skip", skip.toString());
|
|
277
|
+
}
|
|
278
|
+
if (limit !== void 0) {
|
|
279
|
+
targetURL.searchParams.set("limit", limit.toString());
|
|
280
|
+
}
|
|
281
|
+
try {
|
|
282
|
+
const response = await this.getRequest(
|
|
283
|
+
targetURL.href,
|
|
284
|
+
headers
|
|
285
|
+
);
|
|
286
|
+
if (response.status === 200) {
|
|
287
|
+
let allData = response.data.data;
|
|
288
|
+
if (getAllData && response.data.status === "completed") {
|
|
289
|
+
let statusData = response.data;
|
|
290
|
+
if ("data" in statusData) {
|
|
291
|
+
let data = statusData.data;
|
|
292
|
+
while (typeof statusData === "object" && "next" in statusData) {
|
|
293
|
+
if (data.length === 0) {
|
|
294
|
+
break;
|
|
295
|
+
}
|
|
296
|
+
statusData = (await this.getRequest(statusData.next, headers)).data;
|
|
297
|
+
data = data.concat(statusData.data);
|
|
298
|
+
}
|
|
299
|
+
allData = data;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
let resp = {
|
|
303
|
+
success: response.data.success,
|
|
304
|
+
status: response.data.status,
|
|
305
|
+
total: response.data.total,
|
|
306
|
+
completed: response.data.completed,
|
|
307
|
+
creditsUsed: response.data.creditsUsed,
|
|
308
|
+
next: getAllData ? void 0 : response.data.next,
|
|
309
|
+
expiresAt: new Date(response.data.expiresAt),
|
|
310
|
+
data: allData
|
|
311
|
+
};
|
|
312
|
+
if (!response.data.success && response.data.error) {
|
|
313
|
+
resp = {
|
|
314
|
+
...resp,
|
|
315
|
+
success: false,
|
|
316
|
+
error: response.data.error
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
if (response.data.next) {
|
|
320
|
+
resp.next = response.data.next;
|
|
321
|
+
}
|
|
322
|
+
return resp;
|
|
323
|
+
} else {
|
|
324
|
+
this.handleError(response, "check crawl status");
|
|
325
|
+
}
|
|
326
|
+
} catch (error) {
|
|
327
|
+
throw new FirecrawlError(error.message, 500);
|
|
328
|
+
}
|
|
329
|
+
return { success: false, error: "Internal server error." };
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* Returns information about crawl errors.
|
|
333
|
+
* @param id - The ID of the crawl operation.
|
|
334
|
+
* @returns Information about crawl errors.
|
|
335
|
+
*/
|
|
336
|
+
async checkCrawlErrors(id) {
|
|
337
|
+
const headers = this.prepareHeaders();
|
|
338
|
+
try {
|
|
339
|
+
const response = await this.deleteRequest(
|
|
340
|
+
`${this.apiUrl}/v1/crawl/${id}/errors`,
|
|
341
|
+
headers
|
|
342
|
+
);
|
|
343
|
+
if (response.status === 200) {
|
|
344
|
+
return response.data;
|
|
345
|
+
} else {
|
|
346
|
+
this.handleError(response, "check crawl errors");
|
|
347
|
+
}
|
|
348
|
+
} catch (error) {
|
|
349
|
+
throw new FirecrawlError(error.message, 500);
|
|
350
|
+
}
|
|
351
|
+
return { success: false, error: "Internal server error." };
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* Cancels a crawl job using the Firecrawl API.
|
|
355
|
+
* @param id - The ID of the crawl operation.
|
|
356
|
+
* @returns The response from the cancel crawl operation.
|
|
357
|
+
*/
|
|
358
|
+
async cancelCrawl(id) {
|
|
359
|
+
const headers = this.prepareHeaders();
|
|
360
|
+
try {
|
|
361
|
+
const response = await this.deleteRequest(
|
|
362
|
+
`${this.apiUrl}/v1/crawl/${id}`,
|
|
363
|
+
headers
|
|
364
|
+
);
|
|
365
|
+
if (response.status === 200) {
|
|
366
|
+
return response.data;
|
|
367
|
+
} else {
|
|
368
|
+
this.handleError(response, "cancel crawl job");
|
|
369
|
+
}
|
|
370
|
+
} catch (error) {
|
|
371
|
+
throw new FirecrawlError(error.message, 500);
|
|
372
|
+
}
|
|
373
|
+
return { success: false, error: "Internal server error." };
|
|
374
|
+
}
|
|
375
|
+
/**
|
|
376
|
+
* Initiates a crawl job and returns a CrawlWatcher to monitor the job via WebSocket.
|
|
377
|
+
* @param url - The URL to crawl.
|
|
378
|
+
* @param params - Additional parameters for the crawl request.
|
|
379
|
+
* @param idempotencyKey - Optional idempotency key for the request.
|
|
380
|
+
* @returns A CrawlWatcher instance to monitor the crawl job.
|
|
381
|
+
*/
|
|
382
|
+
async crawlUrlAndWatch(url, params, idempotencyKey) {
|
|
383
|
+
const crawl = await this.asyncCrawlUrl(url, params, idempotencyKey);
|
|
384
|
+
if (crawl.success && crawl.id) {
|
|
385
|
+
const id = crawl.id;
|
|
386
|
+
return new CrawlWatcher(id, this);
|
|
387
|
+
}
|
|
388
|
+
throw new FirecrawlError("Crawl job failed to start", 400);
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* Maps a URL using the Firecrawl API.
|
|
392
|
+
* @param url - The URL to map.
|
|
393
|
+
* @param params - Additional parameters for the map request.
|
|
394
|
+
* @returns The response from the map operation.
|
|
395
|
+
*/
|
|
396
|
+
async mapUrl(url, params) {
|
|
397
|
+
const headers = this.prepareHeaders();
|
|
398
|
+
let jsonData = { url, ...params };
|
|
399
|
+
try {
|
|
400
|
+
const response = await this.postRequest(
|
|
401
|
+
this.apiUrl + `/v1/map`,
|
|
402
|
+
jsonData,
|
|
403
|
+
headers
|
|
404
|
+
);
|
|
405
|
+
if (response.status === 200) {
|
|
406
|
+
return response.data;
|
|
407
|
+
} else {
|
|
408
|
+
this.handleError(response, "map");
|
|
409
|
+
}
|
|
410
|
+
} catch (error) {
|
|
411
|
+
throw new FirecrawlError(error.message, 500);
|
|
412
|
+
}
|
|
413
|
+
return { success: false, error: "Internal server error." };
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* Initiates a batch scrape job for multiple URLs using the Firecrawl API.
|
|
417
|
+
* @param url - The URLs to scrape.
|
|
418
|
+
* @param params - Additional parameters for the scrape request.
|
|
419
|
+
* @param pollInterval - Time in seconds for job status checks.
|
|
420
|
+
* @param idempotencyKey - Optional idempotency key for the request.
|
|
421
|
+
* @param webhook - Optional webhook for the batch scrape.
|
|
422
|
+
* @returns The response from the crawl operation.
|
|
423
|
+
*/
|
|
424
|
+
async batchScrapeUrls(urls, params, pollInterval = 2, idempotencyKey, webhook, ignoreInvalidURLs) {
|
|
425
|
+
const headers = this.prepareHeaders(idempotencyKey);
|
|
426
|
+
let jsonData = { urls, webhook, ignoreInvalidURLs, ...params };
|
|
427
|
+
if (jsonData?.extract?.schema) {
|
|
428
|
+
let schema = jsonData.extract.schema;
|
|
429
|
+
try {
|
|
430
|
+
schema = (0, import_zod_to_json_schema.zodToJsonSchema)(schema);
|
|
431
|
+
} catch (error) {
|
|
432
|
+
}
|
|
433
|
+
jsonData = {
|
|
434
|
+
...jsonData,
|
|
435
|
+
extract: {
|
|
436
|
+
...jsonData.extract,
|
|
437
|
+
schema
|
|
438
|
+
}
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
if (jsonData?.jsonOptions?.schema) {
|
|
442
|
+
let schema = jsonData.jsonOptions.schema;
|
|
443
|
+
try {
|
|
444
|
+
schema = (0, import_zod_to_json_schema.zodToJsonSchema)(schema);
|
|
445
|
+
} catch (error) {
|
|
446
|
+
}
|
|
447
|
+
jsonData = {
|
|
448
|
+
...jsonData,
|
|
449
|
+
jsonOptions: {
|
|
450
|
+
...jsonData.jsonOptions,
|
|
451
|
+
schema
|
|
452
|
+
}
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
try {
|
|
456
|
+
const response = await this.postRequest(
|
|
457
|
+
this.apiUrl + `/v1/batch/scrape`,
|
|
458
|
+
jsonData,
|
|
459
|
+
headers
|
|
460
|
+
);
|
|
461
|
+
if (response.status === 200) {
|
|
462
|
+
const id = response.data.id;
|
|
463
|
+
return this.monitorJobStatus(id, headers, pollInterval);
|
|
464
|
+
} else {
|
|
465
|
+
this.handleError(response, "start batch scrape job");
|
|
466
|
+
}
|
|
467
|
+
} catch (error) {
|
|
468
|
+
if (error.response?.data?.error) {
|
|
469
|
+
throw new FirecrawlError(`Request failed with status code ${error.response.status}. Error: ${error.response.data.error} ${error.response.data.details ? ` - ${JSON.stringify(error.response.data.details)}` : ""}`, error.response.status);
|
|
470
|
+
} else {
|
|
471
|
+
throw new FirecrawlError(error.message, 500);
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
return { success: false, error: "Internal server error." };
|
|
475
|
+
}
|
|
476
|
+
async asyncBatchScrapeUrls(urls, params, idempotencyKey, webhook, ignoreInvalidURLs) {
|
|
477
|
+
const headers = this.prepareHeaders(idempotencyKey);
|
|
478
|
+
let jsonData = { urls, webhook, ignoreInvalidURLs, ...params ?? {} };
|
|
479
|
+
try {
|
|
480
|
+
const response = await this.postRequest(
|
|
481
|
+
this.apiUrl + `/v1/batch/scrape`,
|
|
482
|
+
jsonData,
|
|
483
|
+
headers
|
|
484
|
+
);
|
|
485
|
+
if (response.status === 200) {
|
|
486
|
+
return response.data;
|
|
487
|
+
} else {
|
|
488
|
+
this.handleError(response, "start batch scrape job");
|
|
489
|
+
}
|
|
490
|
+
} catch (error) {
|
|
491
|
+
if (error.response?.data?.error) {
|
|
492
|
+
throw new FirecrawlError(`Request failed with status code ${error.response.status}. Error: ${error.response.data.error} ${error.response.data.details ? ` - ${JSON.stringify(error.response.data.details)}` : ""}`, error.response.status);
|
|
493
|
+
} else {
|
|
494
|
+
throw new FirecrawlError(error.message, 500);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
return { success: false, error: "Internal server error." };
|
|
498
|
+
}
|
|
499
|
+
/**
|
|
500
|
+
* Initiates a batch scrape job and returns a CrawlWatcher to monitor the job via WebSocket.
|
|
501
|
+
* @param urls - The URL to scrape.
|
|
502
|
+
* @param params - Additional parameters for the scrape request.
|
|
503
|
+
* @param idempotencyKey - Optional idempotency key for the request.
|
|
504
|
+
* @returns A CrawlWatcher instance to monitor the crawl job.
|
|
505
|
+
*/
|
|
506
|
+
async batchScrapeUrlsAndWatch(urls, params, idempotencyKey, webhook, ignoreInvalidURLs) {
|
|
507
|
+
const crawl = await this.asyncBatchScrapeUrls(urls, params, idempotencyKey, webhook, ignoreInvalidURLs);
|
|
508
|
+
if (crawl.success && crawl.id) {
|
|
509
|
+
const id = crawl.id;
|
|
510
|
+
return new CrawlWatcher(id, this);
|
|
511
|
+
}
|
|
512
|
+
throw new FirecrawlError("Batch scrape job failed to start", 400);
|
|
513
|
+
}
|
|
514
|
+
/**
|
|
515
|
+
* Checks the status of a batch scrape job using the Firecrawl API.
|
|
516
|
+
* @param id - The ID of the batch scrape operation.
|
|
517
|
+
* @param getAllData - Paginate through all the pages of documents, returning the full list of all documents. (default: `false`)
|
|
518
|
+
* @param nextURL - The `next` URL from the previous batch scrape status. Only required if you're not manually increasing `skip`. Only used when `getAllData = false`.
|
|
519
|
+
* @param skip - How many entries to skip to paginate. Only used when `getAllData = false`.
|
|
520
|
+
* @param limit - How many entries to return. Only used when `getAllData = false`.
|
|
521
|
+
* @returns The response containing the job status.
|
|
522
|
+
*/
|
|
523
|
+
async checkBatchScrapeStatus(id, getAllData = false, nextURL, skip, limit) {
|
|
524
|
+
if (!id) {
|
|
525
|
+
throw new FirecrawlError("No batch scrape ID provided", 400);
|
|
526
|
+
}
|
|
527
|
+
const headers = this.prepareHeaders();
|
|
528
|
+
const targetURL = new URL(nextURL ?? `${this.apiUrl}/v1/batch/scrape/${id}`);
|
|
529
|
+
if (skip !== void 0) {
|
|
530
|
+
targetURL.searchParams.set("skip", skip.toString());
|
|
531
|
+
}
|
|
532
|
+
if (limit !== void 0) {
|
|
533
|
+
targetURL.searchParams.set("limit", limit.toString());
|
|
534
|
+
}
|
|
535
|
+
try {
|
|
536
|
+
const response = await this.getRequest(
|
|
537
|
+
targetURL.href,
|
|
538
|
+
headers
|
|
539
|
+
);
|
|
540
|
+
if (response.status === 200) {
|
|
541
|
+
let allData = response.data.data;
|
|
542
|
+
if (getAllData && response.data.status === "completed") {
|
|
543
|
+
let statusData = response.data;
|
|
544
|
+
if ("data" in statusData) {
|
|
545
|
+
let data = statusData.data;
|
|
546
|
+
while (typeof statusData === "object" && "next" in statusData) {
|
|
547
|
+
if (data.length === 0) {
|
|
548
|
+
break;
|
|
549
|
+
}
|
|
550
|
+
statusData = (await this.getRequest(statusData.next, headers)).data;
|
|
551
|
+
data = data.concat(statusData.data);
|
|
552
|
+
}
|
|
553
|
+
allData = data;
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
let resp = {
|
|
557
|
+
success: response.data.success,
|
|
558
|
+
status: response.data.status,
|
|
559
|
+
total: response.data.total,
|
|
560
|
+
completed: response.data.completed,
|
|
561
|
+
creditsUsed: response.data.creditsUsed,
|
|
562
|
+
next: getAllData ? void 0 : response.data.next,
|
|
563
|
+
expiresAt: new Date(response.data.expiresAt),
|
|
564
|
+
data: allData
|
|
565
|
+
};
|
|
566
|
+
if (!response.data.success && response.data.error) {
|
|
567
|
+
resp = {
|
|
568
|
+
...resp,
|
|
569
|
+
success: false,
|
|
570
|
+
error: response.data.error
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
if (response.data.next) {
|
|
574
|
+
resp.next = response.data.next;
|
|
575
|
+
}
|
|
576
|
+
return resp;
|
|
577
|
+
} else {
|
|
578
|
+
this.handleError(response, "check batch scrape status");
|
|
579
|
+
}
|
|
580
|
+
} catch (error) {
|
|
581
|
+
throw new FirecrawlError(error.message, 500);
|
|
582
|
+
}
|
|
583
|
+
return { success: false, error: "Internal server error." };
|
|
584
|
+
}
|
|
585
|
+
/**
|
|
586
|
+
* Returns information about batch scrape errors.
|
|
587
|
+
* @param id - The ID of the batch scrape operation.
|
|
588
|
+
* @returns Information about batch scrape errors.
|
|
589
|
+
*/
|
|
590
|
+
async checkBatchScrapeErrors(id) {
|
|
591
|
+
const headers = this.prepareHeaders();
|
|
592
|
+
try {
|
|
593
|
+
const response = await this.deleteRequest(
|
|
594
|
+
`${this.apiUrl}/v1/batch/scrape/${id}/errors`,
|
|
595
|
+
headers
|
|
596
|
+
);
|
|
597
|
+
if (response.status === 200) {
|
|
598
|
+
return response.data;
|
|
599
|
+
} else {
|
|
600
|
+
this.handleError(response, "check batch scrape errors");
|
|
601
|
+
}
|
|
602
|
+
} catch (error) {
|
|
603
|
+
throw new FirecrawlError(error.message, 500);
|
|
604
|
+
}
|
|
605
|
+
return { success: false, error: "Internal server error." };
|
|
606
|
+
}
|
|
607
|
+
/**
|
|
608
|
+
* Extracts information from URLs using the Firecrawl API.
|
|
609
|
+
* Currently in Beta. Expect breaking changes on future minor versions.
|
|
610
|
+
* @param url - The URL to extract information from.
|
|
611
|
+
* @param params - Additional parameters for the extract request.
|
|
612
|
+
* @returns The response from the extract operation.
|
|
613
|
+
*/
|
|
614
|
+
async extract(urls, params) {
|
|
615
|
+
const headers = this.prepareHeaders();
|
|
616
|
+
let jsonData = { urls, ...params };
|
|
617
|
+
let jsonSchema;
|
|
618
|
+
try {
|
|
619
|
+
if (!params?.schema) {
|
|
620
|
+
jsonSchema = void 0;
|
|
621
|
+
} else if (params.schema instanceof zt.ZodType) {
|
|
622
|
+
jsonSchema = (0, import_zod_to_json_schema.zodToJsonSchema)(params.schema);
|
|
623
|
+
} else {
|
|
624
|
+
jsonSchema = params.schema;
|
|
625
|
+
}
|
|
626
|
+
} catch (error) {
|
|
627
|
+
throw new FirecrawlError("Invalid schema. Schema must be either a valid Zod schema or JSON schema object.", 400);
|
|
628
|
+
}
|
|
629
|
+
try {
|
|
630
|
+
const response = await this.postRequest(
|
|
631
|
+
this.apiUrl + `/v1/extract`,
|
|
632
|
+
{ ...jsonData, schema: jsonSchema, origin: params?.origin || "api-sdk" },
|
|
633
|
+
headers
|
|
634
|
+
);
|
|
635
|
+
if (response.status === 200) {
|
|
636
|
+
const jobId = response.data.id;
|
|
637
|
+
let extractStatus;
|
|
638
|
+
do {
|
|
639
|
+
const statusResponse = await this.getRequest(
|
|
640
|
+
`${this.apiUrl}/v1/extract/${jobId}`,
|
|
641
|
+
headers
|
|
642
|
+
);
|
|
643
|
+
extractStatus = statusResponse.data;
|
|
644
|
+
if (extractStatus.status === "completed") {
|
|
645
|
+
if (extractStatus.success) {
|
|
646
|
+
return {
|
|
647
|
+
success: true,
|
|
648
|
+
data: extractStatus.data,
|
|
649
|
+
warning: extractStatus.warning,
|
|
650
|
+
error: extractStatus.error,
|
|
651
|
+
sources: extractStatus?.sources || void 0
|
|
652
|
+
};
|
|
653
|
+
} else {
|
|
654
|
+
throw new FirecrawlError(`Failed to extract data. Error: ${extractStatus.error}`, statusResponse.status);
|
|
655
|
+
}
|
|
656
|
+
} else if (extractStatus.status === "failed" || extractStatus.status === "cancelled") {
|
|
657
|
+
throw new FirecrawlError(`Extract job ${extractStatus.status}. Error: ${extractStatus.error}`, statusResponse.status);
|
|
658
|
+
}
|
|
659
|
+
await new Promise((resolve) => setTimeout(resolve, 1e3));
|
|
660
|
+
} while (extractStatus.status !== "completed");
|
|
661
|
+
} else {
|
|
662
|
+
this.handleError(response, "extract");
|
|
663
|
+
}
|
|
664
|
+
} catch (error) {
|
|
665
|
+
throw new FirecrawlError(error.message, 500, error.response?.data?.details);
|
|
666
|
+
}
|
|
667
|
+
return { success: false, error: "Internal server error." };
|
|
668
|
+
}
|
|
669
|
+
/**
|
|
670
|
+
* Initiates an asynchronous extract job for a URL using the Firecrawl API.
|
|
671
|
+
* @param url - The URL to extract data from.
|
|
672
|
+
* @param params - Additional parameters for the extract request.
|
|
673
|
+
* @param idempotencyKey - Optional idempotency key for the request.
|
|
674
|
+
* @returns The response from the extract operation.
|
|
675
|
+
*/
|
|
676
|
+
async asyncExtract(urls, params, idempotencyKey) {
|
|
677
|
+
const headers = this.prepareHeaders(idempotencyKey);
|
|
678
|
+
let jsonData = { urls, ...params };
|
|
679
|
+
let jsonSchema;
|
|
680
|
+
try {
|
|
681
|
+
if (params?.schema instanceof zt.ZodType) {
|
|
682
|
+
jsonSchema = (0, import_zod_to_json_schema.zodToJsonSchema)(params.schema);
|
|
683
|
+
} else {
|
|
684
|
+
jsonSchema = params?.schema;
|
|
685
|
+
}
|
|
686
|
+
} catch (error) {
|
|
687
|
+
throw new FirecrawlError("Invalid schema. Schema must be either a valid Zod schema or JSON schema object.", 400);
|
|
688
|
+
}
|
|
689
|
+
try {
|
|
690
|
+
const response = await this.postRequest(
|
|
691
|
+
this.apiUrl + `/v1/extract`,
|
|
692
|
+
{ ...jsonData, schema: jsonSchema },
|
|
693
|
+
headers
|
|
694
|
+
);
|
|
695
|
+
if (response.status === 200) {
|
|
696
|
+
return response.data;
|
|
697
|
+
} else {
|
|
698
|
+
this.handleError(response, "start extract job");
|
|
699
|
+
}
|
|
700
|
+
} catch (error) {
|
|
701
|
+
throw new FirecrawlError(error.message, 500, error.response?.data?.details);
|
|
702
|
+
}
|
|
703
|
+
return { success: false, error: "Internal server error." };
|
|
704
|
+
}
|
|
705
|
+
/**
|
|
706
|
+
* Retrieves the status of an extract job.
|
|
707
|
+
* @param jobId - The ID of the extract job.
|
|
708
|
+
* @returns The status of the extract job.
|
|
709
|
+
*/
|
|
710
|
+
async getExtractStatus(jobId) {
|
|
711
|
+
try {
|
|
712
|
+
const response = await this.getRequest(
|
|
713
|
+
`${this.apiUrl}/v1/extract/${jobId}`,
|
|
714
|
+
this.prepareHeaders()
|
|
715
|
+
);
|
|
716
|
+
if (response.status === 200) {
|
|
717
|
+
return response.data;
|
|
718
|
+
} else {
|
|
719
|
+
this.handleError(response, "get extract status");
|
|
720
|
+
}
|
|
721
|
+
} catch (error) {
|
|
722
|
+
throw new FirecrawlError(error.message, 500);
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
/**
|
|
726
|
+
* Prepares the headers for an API request.
|
|
727
|
+
* @param idempotencyKey - Optional key to ensure idempotency.
|
|
728
|
+
* @returns The prepared headers.
|
|
729
|
+
*/
|
|
730
|
+
prepareHeaders(idempotencyKey) {
|
|
731
|
+
return {
|
|
732
|
+
"Content-Type": "application/json",
|
|
733
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
734
|
+
...idempotencyKey ? { "x-idempotency-key": idempotencyKey } : {}
|
|
735
|
+
};
|
|
736
|
+
}
|
|
737
|
+
/**
|
|
738
|
+
* Sends a POST request to the specified URL.
|
|
739
|
+
* @param url - The URL to send the request to.
|
|
740
|
+
* @param data - The data to send in the request.
|
|
741
|
+
* @param headers - The headers for the request.
|
|
742
|
+
* @returns The response from the POST request.
|
|
743
|
+
*/
|
|
744
|
+
postRequest(url, data, headers) {
|
|
745
|
+
return import_axios.default.post(url, data, { headers, timeout: data?.timeout ? data.timeout + 5e3 : void 0 });
|
|
746
|
+
}
|
|
747
|
+
/**
|
|
748
|
+
* Sends a GET request to the specified URL.
|
|
749
|
+
* @param url - The URL to send the request to.
|
|
750
|
+
* @param headers - The headers for the request.
|
|
751
|
+
* @returns The response from the GET request.
|
|
752
|
+
*/
|
|
753
|
+
async getRequest(url, headers) {
|
|
754
|
+
try {
|
|
755
|
+
return await import_axios.default.get(url, { headers });
|
|
756
|
+
} catch (error) {
|
|
757
|
+
if (error instanceof import_axios.AxiosError && error.response) {
|
|
758
|
+
return error.response;
|
|
759
|
+
} else {
|
|
760
|
+
throw error;
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
/**
|
|
765
|
+
* Sends a DELETE request to the specified URL.
|
|
766
|
+
* @param url - The URL to send the request to.
|
|
767
|
+
* @param headers - The headers for the request.
|
|
768
|
+
* @returns The response from the DELETE request.
|
|
769
|
+
*/
|
|
770
|
+
async deleteRequest(url, headers) {
|
|
771
|
+
try {
|
|
772
|
+
return await import_axios.default.delete(url, { headers });
|
|
773
|
+
} catch (error) {
|
|
774
|
+
if (error instanceof import_axios.AxiosError && error.response) {
|
|
775
|
+
return error.response;
|
|
776
|
+
} else {
|
|
777
|
+
throw error;
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
/**
|
|
782
|
+
* Monitors the status of a crawl job until completion or failure.
|
|
783
|
+
* @param id - The ID of the crawl operation.
|
|
784
|
+
* @param headers - The headers for the request.
|
|
785
|
+
* @param checkInterval - Interval in seconds for job status checks.
|
|
786
|
+
* @param checkUrl - Optional URL to check the status (used for v1 API)
|
|
787
|
+
* @returns The final job status or data.
|
|
788
|
+
*/
|
|
789
|
+
async monitorJobStatus(id, headers, checkInterval) {
|
|
790
|
+
try {
|
|
791
|
+
while (true) {
|
|
792
|
+
let statusResponse = await this.getRequest(
|
|
793
|
+
`${this.apiUrl}/v1/crawl/${id}`,
|
|
794
|
+
headers
|
|
795
|
+
);
|
|
796
|
+
if (statusResponse.status === 200) {
|
|
797
|
+
let statusData = statusResponse.data;
|
|
798
|
+
if (statusData.status === "completed") {
|
|
799
|
+
if ("data" in statusData) {
|
|
800
|
+
let data = statusData.data;
|
|
801
|
+
while (typeof statusData === "object" && "next" in statusData) {
|
|
802
|
+
if (data.length === 0) {
|
|
803
|
+
break;
|
|
804
|
+
}
|
|
805
|
+
statusResponse = await this.getRequest(statusData.next, headers);
|
|
806
|
+
statusData = statusResponse.data;
|
|
807
|
+
data = data.concat(statusData.data);
|
|
808
|
+
}
|
|
809
|
+
statusData.data = data;
|
|
810
|
+
return statusData;
|
|
811
|
+
} else {
|
|
812
|
+
throw new FirecrawlError("Crawl job completed but no data was returned", 500);
|
|
813
|
+
}
|
|
814
|
+
} else if (["active", "paused", "pending", "queued", "waiting", "scraping"].includes(statusData.status)) {
|
|
815
|
+
checkInterval = Math.max(checkInterval, 2);
|
|
816
|
+
await new Promise(
|
|
817
|
+
(resolve) => setTimeout(resolve, checkInterval * 1e3)
|
|
818
|
+
);
|
|
819
|
+
} else {
|
|
820
|
+
throw new FirecrawlError(
|
|
821
|
+
`Crawl job failed or was stopped. Status: ${statusData.status}`,
|
|
822
|
+
500
|
|
823
|
+
);
|
|
824
|
+
}
|
|
825
|
+
} else {
|
|
826
|
+
this.handleError(statusResponse, "check crawl status");
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
} catch (error) {
|
|
830
|
+
throw new FirecrawlError(error, 500);
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
/**
|
|
834
|
+
* Handles errors from API responses.
|
|
835
|
+
* @param {AxiosResponse} response - The response from the API.
|
|
836
|
+
* @param {string} action - The action being performed when the error occurred.
|
|
837
|
+
*/
|
|
838
|
+
handleError(response, action) {
|
|
839
|
+
if ([400, 402, 408, 409, 500].includes(response.status)) {
|
|
840
|
+
const errorMessage = response.data.error || "Unknown error occurred";
|
|
841
|
+
const details = response.data.details ? ` - ${JSON.stringify(response.data.details)}` : "";
|
|
842
|
+
throw new FirecrawlError(
|
|
843
|
+
`Failed to ${action}. Status code: ${response.status}. Error: ${errorMessage}${details}`,
|
|
844
|
+
response.status,
|
|
845
|
+
response?.data?.details
|
|
846
|
+
);
|
|
847
|
+
} else {
|
|
848
|
+
throw new FirecrawlError(
|
|
849
|
+
`Unexpected error occurred while trying to ${action}. Status code: ${response.status}`,
|
|
850
|
+
response.status
|
|
851
|
+
);
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
/**
|
|
855
|
+
* Initiates a deep research operation on a given topic and polls until completion.
|
|
856
|
+
* @param topic - The topic to research.
|
|
857
|
+
* @param params - Parameters for the deep research operation.
|
|
858
|
+
* @param onActivity - Optional callback to receive activity updates in real-time.
|
|
859
|
+
* @returns The final research results.
|
|
860
|
+
*/
|
|
861
|
+
async __deepResearch(topic, params, onActivity) {
|
|
862
|
+
try {
|
|
863
|
+
const response = await this.__asyncDeepResearch(topic, params);
|
|
864
|
+
if (!response.success || "error" in response) {
|
|
865
|
+
return { success: false, error: "error" in response ? response.error : "Unknown error" };
|
|
866
|
+
}
|
|
867
|
+
if (!response.id) {
|
|
868
|
+
throw new FirecrawlError(`Failed to start research. No job ID returned.`, 500);
|
|
869
|
+
}
|
|
870
|
+
const jobId = response.id;
|
|
871
|
+
let researchStatus;
|
|
872
|
+
let lastActivityCount = 0;
|
|
873
|
+
while (true) {
|
|
874
|
+
researchStatus = await this.__checkDeepResearchStatus(jobId);
|
|
875
|
+
if ("error" in researchStatus && !researchStatus.success) {
|
|
876
|
+
return researchStatus;
|
|
877
|
+
}
|
|
878
|
+
if (onActivity && researchStatus.activities) {
|
|
879
|
+
const newActivities = researchStatus.activities.slice(lastActivityCount);
|
|
880
|
+
for (const activity of newActivities) {
|
|
881
|
+
onActivity(activity);
|
|
882
|
+
}
|
|
883
|
+
lastActivityCount = researchStatus.activities.length;
|
|
884
|
+
}
|
|
885
|
+
if (researchStatus.status === "completed") {
|
|
886
|
+
return researchStatus;
|
|
887
|
+
}
|
|
888
|
+
if (researchStatus.status === "failed") {
|
|
889
|
+
throw new FirecrawlError(
|
|
890
|
+
`Research job ${researchStatus.status}. Error: ${researchStatus.error}`,
|
|
891
|
+
500
|
|
892
|
+
);
|
|
893
|
+
}
|
|
894
|
+
if (researchStatus.status !== "processing") {
|
|
895
|
+
break;
|
|
896
|
+
}
|
|
897
|
+
await new Promise((resolve) => setTimeout(resolve, 2e3));
|
|
898
|
+
}
|
|
899
|
+
return { success: false, error: "Research job terminated unexpectedly" };
|
|
900
|
+
} catch (error) {
|
|
901
|
+
throw new FirecrawlError(error.message, 500, error.response?.data?.details);
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
/**
|
|
905
|
+
* Initiates a deep research operation on a given topic without polling.
|
|
906
|
+
* @param params - Parameters for the deep research operation.
|
|
907
|
+
* @returns The response containing the research job ID.
|
|
908
|
+
*/
|
|
909
|
+
async __asyncDeepResearch(topic, params) {
|
|
910
|
+
const headers = this.prepareHeaders();
|
|
911
|
+
try {
|
|
912
|
+
const response = await this.postRequest(
|
|
913
|
+
`${this.apiUrl}/v1/deep-research`,
|
|
914
|
+
{ topic, ...params },
|
|
915
|
+
headers
|
|
916
|
+
);
|
|
917
|
+
if (response.status === 200) {
|
|
918
|
+
return response.data;
|
|
919
|
+
} else {
|
|
920
|
+
this.handleError(response, "start deep research");
|
|
921
|
+
}
|
|
922
|
+
} catch (error) {
|
|
923
|
+
if (error.response?.data?.error) {
|
|
924
|
+
throw new FirecrawlError(`Request failed with status code ${error.response.status}. Error: ${error.response.data.error} ${error.response.data.details ? ` - ${JSON.stringify(error.response.data.details)}` : ""}`, error.response.status);
|
|
925
|
+
} else {
|
|
926
|
+
throw new FirecrawlError(error.message, 500);
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
return { success: false, error: "Internal server error." };
|
|
930
|
+
}
|
|
931
|
+
/**
|
|
932
|
+
* Checks the status of a deep research operation.
|
|
933
|
+
* @param id - The ID of the deep research operation.
|
|
934
|
+
* @returns The current status and results of the research operation.
|
|
935
|
+
*/
|
|
936
|
+
async __checkDeepResearchStatus(id) {
|
|
937
|
+
const headers = this.prepareHeaders();
|
|
938
|
+
try {
|
|
939
|
+
const response = await this.getRequest(
|
|
940
|
+
`${this.apiUrl}/v1/deep-research/${id}`,
|
|
941
|
+
headers
|
|
942
|
+
);
|
|
943
|
+
if (response.status === 200) {
|
|
944
|
+
return response.data;
|
|
945
|
+
} else if (response.status === 404) {
|
|
946
|
+
throw new FirecrawlError("Deep research job not found", 404);
|
|
947
|
+
} else {
|
|
948
|
+
this.handleError(response, "check deep research status");
|
|
949
|
+
}
|
|
950
|
+
} catch (error) {
|
|
951
|
+
if (error.response?.data?.error) {
|
|
952
|
+
throw new FirecrawlError(`Request failed with status code ${error.response.status}. Error: ${error.response.data.error} ${error.response.data.details ? ` - ${JSON.stringify(error.response.data.details)}` : ""}`, error.response.status);
|
|
953
|
+
} else {
|
|
954
|
+
throw new FirecrawlError(error.message, 500);
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
return { success: false, error: "Internal server error." };
|
|
958
|
+
}
|
|
959
|
+
/**
|
|
960
|
+
* Generates LLMs.txt for a given URL and polls until completion.
|
|
961
|
+
* @param url - The URL to generate LLMs.txt from.
|
|
962
|
+
* @param params - Parameters for the LLMs.txt generation operation.
|
|
963
|
+
* @returns The final generation results.
|
|
964
|
+
*/
|
|
965
|
+
async generateLLMsText(url, params) {
|
|
966
|
+
try {
|
|
967
|
+
const response = await this.asyncGenerateLLMsText(url, params);
|
|
968
|
+
if (!response.success || "error" in response) {
|
|
969
|
+
return { success: false, error: "error" in response ? response.error : "Unknown error" };
|
|
970
|
+
}
|
|
971
|
+
if (!response.id) {
|
|
972
|
+
throw new FirecrawlError(`Failed to start LLMs.txt generation. No job ID returned.`, 500);
|
|
973
|
+
}
|
|
974
|
+
const jobId = response.id;
|
|
975
|
+
let generationStatus;
|
|
976
|
+
while (true) {
|
|
977
|
+
generationStatus = await this.checkGenerateLLMsTextStatus(jobId);
|
|
978
|
+
if ("error" in generationStatus && !generationStatus.success) {
|
|
979
|
+
return generationStatus;
|
|
980
|
+
}
|
|
981
|
+
if (generationStatus.status === "completed") {
|
|
982
|
+
return generationStatus;
|
|
983
|
+
}
|
|
984
|
+
if (generationStatus.status === "failed") {
|
|
985
|
+
throw new FirecrawlError(
|
|
986
|
+
`LLMs.txt generation job ${generationStatus.status}. Error: ${generationStatus.error}`,
|
|
987
|
+
500
|
|
988
|
+
);
|
|
989
|
+
}
|
|
990
|
+
if (generationStatus.status !== "processing") {
|
|
991
|
+
break;
|
|
992
|
+
}
|
|
993
|
+
await new Promise((resolve) => setTimeout(resolve, 2e3));
|
|
994
|
+
}
|
|
995
|
+
return { success: false, error: "LLMs.txt generation job terminated unexpectedly" };
|
|
996
|
+
} catch (error) {
|
|
997
|
+
throw new FirecrawlError(error.message, 500, error.response?.data?.details);
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
/**
|
|
1001
|
+
* Initiates a LLMs.txt generation operation without polling.
|
|
1002
|
+
* @param url - The URL to generate LLMs.txt from.
|
|
1003
|
+
* @param params - Parameters for the LLMs.txt generation operation.
|
|
1004
|
+
* @returns The response containing the generation job ID.
|
|
1005
|
+
*/
|
|
1006
|
+
async asyncGenerateLLMsText(url, params) {
|
|
1007
|
+
const headers = this.prepareHeaders();
|
|
1008
|
+
try {
|
|
1009
|
+
const response = await this.postRequest(
|
|
1010
|
+
`${this.apiUrl}/v1/llmstxt`,
|
|
1011
|
+
{ url, ...params },
|
|
1012
|
+
headers
|
|
1013
|
+
);
|
|
1014
|
+
if (response.status === 200) {
|
|
1015
|
+
return response.data;
|
|
1016
|
+
} else {
|
|
1017
|
+
this.handleError(response, "start LLMs.txt generation");
|
|
1018
|
+
}
|
|
1019
|
+
} catch (error) {
|
|
1020
|
+
if (error.response?.data?.error) {
|
|
1021
|
+
throw new FirecrawlError(`Request failed with status code ${error.response.status}. Error: ${error.response.data.error} ${error.response.data.details ? ` - ${JSON.stringify(error.response.data.details)}` : ""}`, error.response.status);
|
|
1022
|
+
} else {
|
|
1023
|
+
throw new FirecrawlError(error.message, 500);
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
return { success: false, error: "Internal server error." };
|
|
1027
|
+
}
|
|
1028
|
+
/**
|
|
1029
|
+
* Checks the status of a LLMs.txt generation operation.
|
|
1030
|
+
* @param id - The ID of the LLMs.txt generation operation.
|
|
1031
|
+
* @returns The current status and results of the generation operation.
|
|
1032
|
+
*/
|
|
1033
|
+
async checkGenerateLLMsTextStatus(id) {
|
|
1034
|
+
const headers = this.prepareHeaders();
|
|
1035
|
+
try {
|
|
1036
|
+
const response = await this.getRequest(
|
|
1037
|
+
`${this.apiUrl}/v1/llmstxt/${id}`,
|
|
1038
|
+
headers
|
|
1039
|
+
);
|
|
1040
|
+
if (response.status === 200) {
|
|
1041
|
+
return response.data;
|
|
1042
|
+
} else if (response.status === 404) {
|
|
1043
|
+
throw new FirecrawlError("LLMs.txt generation job not found", 404);
|
|
1044
|
+
} else {
|
|
1045
|
+
this.handleError(response, "check LLMs.txt generation status");
|
|
1046
|
+
}
|
|
1047
|
+
} catch (error) {
|
|
1048
|
+
if (error.response?.data?.error) {
|
|
1049
|
+
throw new FirecrawlError(`Request failed with status code ${error.response.status}. Error: ${error.response.data.error} ${error.response.data.details ? ` - ${JSON.stringify(error.response.data.details)}` : ""}`, error.response.status);
|
|
1050
|
+
} else {
|
|
1051
|
+
throw new FirecrawlError(error.message, 500);
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
return { success: false, error: "Internal server error." };
|
|
1055
|
+
}
|
|
1056
|
+
};
|
|
1057
|
+
var CrawlWatcher = class extends import_typescript_event_target.TypedEventTarget {
|
|
1058
|
+
ws;
|
|
1059
|
+
data;
|
|
1060
|
+
status;
|
|
1061
|
+
id;
|
|
1062
|
+
constructor(id, app) {
|
|
1063
|
+
super();
|
|
1064
|
+
this.id = id;
|
|
1065
|
+
const wsUrl = app.apiUrl.replace(/^http/, "ws");
|
|
1066
|
+
this.ws = new import_isows.WebSocket(`${wsUrl}/v1/crawl/${id}`, app.apiKey);
|
|
1067
|
+
this.status = "scraping";
|
|
1068
|
+
this.data = [];
|
|
1069
|
+
const messageHandler = (msg) => {
|
|
1070
|
+
if (msg.type === "done") {
|
|
1071
|
+
this.status = "completed";
|
|
1072
|
+
this.dispatchTypedEvent("done", new CustomEvent("done", {
|
|
1073
|
+
detail: {
|
|
1074
|
+
status: this.status,
|
|
1075
|
+
data: this.data,
|
|
1076
|
+
id: this.id
|
|
1077
|
+
}
|
|
1078
|
+
}));
|
|
1079
|
+
} else if (msg.type === "error") {
|
|
1080
|
+
this.status = "failed";
|
|
1081
|
+
this.dispatchTypedEvent("error", new CustomEvent("error", {
|
|
1082
|
+
detail: {
|
|
1083
|
+
status: this.status,
|
|
1084
|
+
data: this.data,
|
|
1085
|
+
error: msg.error,
|
|
1086
|
+
id: this.id
|
|
1087
|
+
}
|
|
1088
|
+
}));
|
|
1089
|
+
} else if (msg.type === "catchup") {
|
|
1090
|
+
this.status = msg.data.status;
|
|
1091
|
+
this.data.push(...msg.data.data ?? []);
|
|
1092
|
+
for (const doc of this.data) {
|
|
1093
|
+
this.dispatchTypedEvent("document", new CustomEvent("document", {
|
|
1094
|
+
detail: {
|
|
1095
|
+
...doc,
|
|
1096
|
+
id: this.id
|
|
1097
|
+
}
|
|
1098
|
+
}));
|
|
1099
|
+
}
|
|
1100
|
+
} else if (msg.type === "document") {
|
|
1101
|
+
this.dispatchTypedEvent("document", new CustomEvent("document", {
|
|
1102
|
+
detail: {
|
|
1103
|
+
...msg.data,
|
|
1104
|
+
id: this.id
|
|
1105
|
+
}
|
|
1106
|
+
}));
|
|
1107
|
+
}
|
|
1108
|
+
};
|
|
1109
|
+
this.ws.onmessage = ((ev) => {
|
|
1110
|
+
if (typeof ev.data !== "string") {
|
|
1111
|
+
this.ws.close();
|
|
1112
|
+
return;
|
|
1113
|
+
}
|
|
1114
|
+
try {
|
|
1115
|
+
const msg = JSON.parse(ev.data);
|
|
1116
|
+
messageHandler(msg);
|
|
1117
|
+
} catch (error) {
|
|
1118
|
+
console.error("Error on message", error);
|
|
1119
|
+
}
|
|
1120
|
+
}).bind(this);
|
|
1121
|
+
this.ws.onclose = ((ev) => {
|
|
1122
|
+
try {
|
|
1123
|
+
const msg = JSON.parse(ev.reason);
|
|
1124
|
+
messageHandler(msg);
|
|
1125
|
+
} catch (error) {
|
|
1126
|
+
console.error("Error on close", error);
|
|
1127
|
+
}
|
|
1128
|
+
}).bind(this);
|
|
1129
|
+
this.ws.onerror = ((_) => {
|
|
1130
|
+
this.status = "failed";
|
|
1131
|
+
this.dispatchTypedEvent("error", new CustomEvent("error", {
|
|
1132
|
+
detail: {
|
|
1133
|
+
status: this.status,
|
|
1134
|
+
data: this.data,
|
|
1135
|
+
error: "WebSocket error",
|
|
1136
|
+
id: this.id
|
|
1137
|
+
}
|
|
1138
|
+
}));
|
|
1139
|
+
}).bind(this);
|
|
1140
|
+
}
|
|
1141
|
+
close() {
|
|
1142
|
+
this.ws.close();
|
|
1143
|
+
}
|
|
1144
|
+
};
|
|
1145
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
1146
|
+
0 && (module.exports = {
|
|
1147
|
+
CrawlWatcher,
|
|
1148
|
+
FirecrawlError
|
|
1149
|
+
});
|