@mendable/firecrawl 1.2.2
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/.env.example +3 -0
- package/LICENSE +21 -0
- package/README.md +160 -0
- package/build/cjs/index.js +354 -0
- package/build/cjs/package.json +1 -0
- package/build/esm/index.js +346 -0
- package/build/esm/package.json +1 -0
- package/jest.config.js +16 -0
- package/package.json +64 -0
- package/src/__tests__/e2e_withAuth/index.test.ts +330 -0
- package/src/__tests__/fixtures/scrape.json +22 -0
- package/src/__tests__/index.test.ts +48 -0
- package/src/__tests__/v1/e2e_withAuth/index.test.ts +312 -0
- package/src/index.ts +620 -0
- package/tsconfig.json +111 -0
- package/types/index.d.ts +260 -0
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
import axios from "axios";
|
|
2
|
+
import { zodToJsonSchema } from "zod-to-json-schema";
|
|
3
|
+
import { WebSocket } from "isows";
|
|
4
|
+
import { TypedEventTarget } from "typescript-event-target";
|
|
5
|
+
/**
|
|
6
|
+
* Main class for interacting with the Firecrawl API.
|
|
7
|
+
* Provides methods for scraping, searching, crawling, and mapping web content.
|
|
8
|
+
*/
|
|
9
|
+
export default class FirecrawlApp {
|
|
10
|
+
/**
|
|
11
|
+
* Initializes a new instance of the FirecrawlApp class.
|
|
12
|
+
* @param config - Configuration options for the FirecrawlApp instance.
|
|
13
|
+
*/
|
|
14
|
+
constructor({ apiKey = null, apiUrl = null }) {
|
|
15
|
+
this.apiKey = apiKey || "";
|
|
16
|
+
this.apiUrl = apiUrl || "https://api.firecrawl.dev";
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Scrapes a URL using the Firecrawl API.
|
|
20
|
+
* @param url - The URL to scrape.
|
|
21
|
+
* @param params - Additional parameters for the scrape request.
|
|
22
|
+
* @returns The response from the scrape operation.
|
|
23
|
+
*/
|
|
24
|
+
async scrapeUrl(url, params) {
|
|
25
|
+
const headers = {
|
|
26
|
+
"Content-Type": "application/json",
|
|
27
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
28
|
+
};
|
|
29
|
+
let jsonData = { url, ...params };
|
|
30
|
+
if (jsonData?.extract?.schema) {
|
|
31
|
+
let schema = jsonData.extract.schema;
|
|
32
|
+
// Try parsing the schema as a Zod schema
|
|
33
|
+
try {
|
|
34
|
+
schema = zodToJsonSchema(schema);
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
}
|
|
38
|
+
jsonData = {
|
|
39
|
+
...jsonData,
|
|
40
|
+
extract: {
|
|
41
|
+
...jsonData.extract,
|
|
42
|
+
schema: schema,
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
try {
|
|
47
|
+
const response = await axios.post(this.apiUrl + `/v1/scrape`, jsonData, { headers });
|
|
48
|
+
if (response.status === 200) {
|
|
49
|
+
const responseData = response.data;
|
|
50
|
+
if (responseData.success) {
|
|
51
|
+
return {
|
|
52
|
+
success: true,
|
|
53
|
+
warning: responseData.warning,
|
|
54
|
+
error: responseData.error,
|
|
55
|
+
...responseData.data
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
else {
|
|
59
|
+
throw new Error(`Failed to scrape URL. Error: ${responseData.error}`);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
else {
|
|
63
|
+
this.handleError(response, "scrape URL");
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
throw new Error(error.message);
|
|
68
|
+
}
|
|
69
|
+
return { success: false, error: "Internal server error." };
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* This method is intended to search for a query using the Firecrawl API. However, it is not supported in version 1 of the API.
|
|
73
|
+
* @param query - The search query string.
|
|
74
|
+
* @param params - Additional parameters for the search.
|
|
75
|
+
* @returns Throws an error advising to use version 0 of the API.
|
|
76
|
+
*/
|
|
77
|
+
async search(query, params) {
|
|
78
|
+
throw new Error("Search is not supported in v1, please update FirecrawlApp() initialization to use v0.");
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Initiates a crawl job for a URL using the Firecrawl API.
|
|
82
|
+
* @param url - The URL to crawl.
|
|
83
|
+
* @param params - Additional parameters for the crawl request.
|
|
84
|
+
* @param pollInterval - Time in seconds for job status checks.
|
|
85
|
+
* @param idempotencyKey - Optional idempotency key for the request.
|
|
86
|
+
* @returns The response from the crawl operation.
|
|
87
|
+
*/
|
|
88
|
+
async crawlUrl(url, params, pollInterval = 2, idempotencyKey) {
|
|
89
|
+
const headers = this.prepareHeaders(idempotencyKey);
|
|
90
|
+
let jsonData = { url, ...params };
|
|
91
|
+
try {
|
|
92
|
+
const response = await this.postRequest(this.apiUrl + `/v1/crawl`, jsonData, headers);
|
|
93
|
+
if (response.status === 200) {
|
|
94
|
+
const id = response.data.id;
|
|
95
|
+
return this.monitorJobStatus(id, headers, pollInterval);
|
|
96
|
+
}
|
|
97
|
+
else {
|
|
98
|
+
this.handleError(response, "start crawl job");
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
if (error.response?.data?.error) {
|
|
103
|
+
throw new Error(`Request failed with status code ${error.response.status}. Error: ${error.response.data.error} ${error.response.data.details ? ` - ${JSON.stringify(error.response.data.details)}` : ''}`);
|
|
104
|
+
}
|
|
105
|
+
else {
|
|
106
|
+
throw new Error(error.message);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return { success: false, error: "Internal server error." };
|
|
110
|
+
}
|
|
111
|
+
async asyncCrawlUrl(url, params, idempotencyKey) {
|
|
112
|
+
const headers = this.prepareHeaders(idempotencyKey);
|
|
113
|
+
let jsonData = { url, ...params };
|
|
114
|
+
try {
|
|
115
|
+
const response = await this.postRequest(this.apiUrl + `/v1/crawl`, jsonData, headers);
|
|
116
|
+
if (response.status === 200) {
|
|
117
|
+
return response.data;
|
|
118
|
+
}
|
|
119
|
+
else {
|
|
120
|
+
this.handleError(response, "start crawl job");
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
if (error.response?.data?.error) {
|
|
125
|
+
throw new Error(`Request failed with status code ${error.response.status}. Error: ${error.response.data.error} ${error.response.data.details ? ` - ${JSON.stringify(error.response.data.details)}` : ''}`);
|
|
126
|
+
}
|
|
127
|
+
else {
|
|
128
|
+
throw new Error(error.message);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return { success: false, error: "Internal server error." };
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Checks the status of a crawl job using the Firecrawl API.
|
|
135
|
+
* @param id - The ID of the crawl operation.
|
|
136
|
+
* @returns The response containing the job status.
|
|
137
|
+
*/
|
|
138
|
+
async checkCrawlStatus(id) {
|
|
139
|
+
if (!id) {
|
|
140
|
+
throw new Error("No crawl ID provided");
|
|
141
|
+
}
|
|
142
|
+
const headers = this.prepareHeaders();
|
|
143
|
+
try {
|
|
144
|
+
const response = await this.getRequest(`${this.apiUrl}/v1/crawl/${id}`, headers);
|
|
145
|
+
if (response.status === 200) {
|
|
146
|
+
return ({
|
|
147
|
+
success: true,
|
|
148
|
+
status: response.data.status,
|
|
149
|
+
total: response.data.total,
|
|
150
|
+
completed: response.data.completed,
|
|
151
|
+
creditsUsed: response.data.creditsUsed,
|
|
152
|
+
expiresAt: new Date(response.data.expiresAt),
|
|
153
|
+
next: response.data.next,
|
|
154
|
+
data: response.data.data,
|
|
155
|
+
error: response.data.error
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
else {
|
|
159
|
+
this.handleError(response, "check crawl status");
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
catch (error) {
|
|
163
|
+
throw new Error(error.message);
|
|
164
|
+
}
|
|
165
|
+
return { success: false, error: "Internal server error." };
|
|
166
|
+
}
|
|
167
|
+
async crawlUrlAndWatch(url, params, idempotencyKey) {
|
|
168
|
+
const crawl = await this.asyncCrawlUrl(url, params, idempotencyKey);
|
|
169
|
+
if (crawl.success && crawl.id) {
|
|
170
|
+
const id = crawl.id;
|
|
171
|
+
return new CrawlWatcher(id, this);
|
|
172
|
+
}
|
|
173
|
+
throw new Error("Crawl job failed to start");
|
|
174
|
+
}
|
|
175
|
+
async mapUrl(url, params) {
|
|
176
|
+
const headers = this.prepareHeaders();
|
|
177
|
+
let jsonData = { url, ...params };
|
|
178
|
+
try {
|
|
179
|
+
const response = await this.postRequest(this.apiUrl + `/v1/map`, jsonData, headers);
|
|
180
|
+
if (response.status === 200) {
|
|
181
|
+
return response.data;
|
|
182
|
+
}
|
|
183
|
+
else {
|
|
184
|
+
this.handleError(response, "map");
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
catch (error) {
|
|
188
|
+
throw new Error(error.message);
|
|
189
|
+
}
|
|
190
|
+
return { success: false, error: "Internal server error." };
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Prepares the headers for an API request.
|
|
194
|
+
* @param idempotencyKey - Optional key to ensure idempotency.
|
|
195
|
+
* @returns The prepared headers.
|
|
196
|
+
*/
|
|
197
|
+
prepareHeaders(idempotencyKey) {
|
|
198
|
+
return {
|
|
199
|
+
"Content-Type": "application/json",
|
|
200
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
201
|
+
...(idempotencyKey ? { "x-idempotency-key": idempotencyKey } : {}),
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Sends a POST request to the specified URL.
|
|
206
|
+
* @param url - The URL to send the request to.
|
|
207
|
+
* @param data - The data to send in the request.
|
|
208
|
+
* @param headers - The headers for the request.
|
|
209
|
+
* @returns The response from the POST request.
|
|
210
|
+
*/
|
|
211
|
+
postRequest(url, data, headers) {
|
|
212
|
+
return axios.post(url, data, { headers });
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Sends a GET request to the specified URL.
|
|
216
|
+
* @param url - The URL to send the request to.
|
|
217
|
+
* @param headers - The headers for the request.
|
|
218
|
+
* @returns The response from the GET request.
|
|
219
|
+
*/
|
|
220
|
+
getRequest(url, headers) {
|
|
221
|
+
return axios.get(url, { headers });
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Monitors the status of a crawl job until completion or failure.
|
|
225
|
+
* @param id - The ID of the crawl operation.
|
|
226
|
+
* @param headers - The headers for the request.
|
|
227
|
+
* @param checkInterval - Interval in seconds for job status checks.
|
|
228
|
+
* @param checkUrl - Optional URL to check the status (used for v1 API)
|
|
229
|
+
* @returns The final job status or data.
|
|
230
|
+
*/
|
|
231
|
+
async monitorJobStatus(id, headers, checkInterval) {
|
|
232
|
+
while (true) {
|
|
233
|
+
let statusResponse = await this.getRequest(`${this.apiUrl}/v1/crawl/${id}`, headers);
|
|
234
|
+
if (statusResponse.status === 200) {
|
|
235
|
+
let statusData = statusResponse.data;
|
|
236
|
+
if (statusData.status === "completed") {
|
|
237
|
+
if ("data" in statusData) {
|
|
238
|
+
let data = statusData.data;
|
|
239
|
+
while ('next' in statusData) {
|
|
240
|
+
statusResponse = await this.getRequest(statusData.next, headers);
|
|
241
|
+
statusData = statusResponse.data;
|
|
242
|
+
data = data.concat(statusData.data);
|
|
243
|
+
}
|
|
244
|
+
statusData.data = data;
|
|
245
|
+
return statusData;
|
|
246
|
+
}
|
|
247
|
+
else {
|
|
248
|
+
throw new Error("Crawl job completed but no data was returned");
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
else if (["active", "paused", "pending", "queued", "waiting", "scraping"].includes(statusData.status)) {
|
|
252
|
+
checkInterval = Math.max(checkInterval, 2);
|
|
253
|
+
await new Promise((resolve) => setTimeout(resolve, checkInterval * 1000));
|
|
254
|
+
}
|
|
255
|
+
else {
|
|
256
|
+
throw new Error(`Crawl job failed or was stopped. Status: ${statusData.status}`);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
else {
|
|
260
|
+
this.handleError(statusResponse, "check crawl status");
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* Handles errors from API responses.
|
|
266
|
+
* @param {AxiosResponse} response - The response from the API.
|
|
267
|
+
* @param {string} action - The action being performed when the error occurred.
|
|
268
|
+
*/
|
|
269
|
+
handleError(response, action) {
|
|
270
|
+
if ([402, 408, 409, 500].includes(response.status)) {
|
|
271
|
+
const errorMessage = response.data.error || "Unknown error occurred";
|
|
272
|
+
throw new Error(`Failed to ${action}. Status code: ${response.status}. Error: ${errorMessage}`);
|
|
273
|
+
}
|
|
274
|
+
else {
|
|
275
|
+
throw new Error(`Unexpected error occurred while trying to ${action}. Status code: ${response.status}`);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
export class CrawlWatcher extends TypedEventTarget {
|
|
280
|
+
constructor(id, app) {
|
|
281
|
+
super();
|
|
282
|
+
this.ws = new WebSocket(`${app.apiUrl}/v1/crawl/${id}`, app.apiKey);
|
|
283
|
+
this.status = "scraping";
|
|
284
|
+
this.data = [];
|
|
285
|
+
const messageHandler = (msg) => {
|
|
286
|
+
if (msg.type === "done") {
|
|
287
|
+
this.status = "completed";
|
|
288
|
+
this.dispatchTypedEvent("done", new CustomEvent("done", {
|
|
289
|
+
detail: {
|
|
290
|
+
status: this.status,
|
|
291
|
+
data: this.data,
|
|
292
|
+
},
|
|
293
|
+
}));
|
|
294
|
+
}
|
|
295
|
+
else if (msg.type === "error") {
|
|
296
|
+
this.status = "failed";
|
|
297
|
+
this.dispatchTypedEvent("error", new CustomEvent("error", {
|
|
298
|
+
detail: {
|
|
299
|
+
status: this.status,
|
|
300
|
+
data: this.data,
|
|
301
|
+
error: msg.error,
|
|
302
|
+
},
|
|
303
|
+
}));
|
|
304
|
+
}
|
|
305
|
+
else if (msg.type === "catchup") {
|
|
306
|
+
this.status = msg.data.status;
|
|
307
|
+
this.data.push(...(msg.data.data ?? []));
|
|
308
|
+
for (const doc of this.data) {
|
|
309
|
+
this.dispatchTypedEvent("document", new CustomEvent("document", {
|
|
310
|
+
detail: doc,
|
|
311
|
+
}));
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
else if (msg.type === "document") {
|
|
315
|
+
this.dispatchTypedEvent("document", new CustomEvent("document", {
|
|
316
|
+
detail: msg.data,
|
|
317
|
+
}));
|
|
318
|
+
}
|
|
319
|
+
};
|
|
320
|
+
this.ws.onmessage = ((ev) => {
|
|
321
|
+
if (typeof ev.data !== "string") {
|
|
322
|
+
this.ws.close();
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
const msg = JSON.parse(ev.data);
|
|
326
|
+
messageHandler(msg);
|
|
327
|
+
}).bind(this);
|
|
328
|
+
this.ws.onclose = ((ev) => {
|
|
329
|
+
const msg = JSON.parse(ev.reason);
|
|
330
|
+
messageHandler(msg);
|
|
331
|
+
}).bind(this);
|
|
332
|
+
this.ws.onerror = ((_) => {
|
|
333
|
+
this.status = "failed";
|
|
334
|
+
this.dispatchTypedEvent("error", new CustomEvent("error", {
|
|
335
|
+
detail: {
|
|
336
|
+
status: this.status,
|
|
337
|
+
data: this.data,
|
|
338
|
+
error: "WebSocket error",
|
|
339
|
+
},
|
|
340
|
+
}));
|
|
341
|
+
}).bind(this);
|
|
342
|
+
}
|
|
343
|
+
close() {
|
|
344
|
+
this.ws.close();
|
|
345
|
+
}
|
|
346
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"type": "module"}
|
package/jest.config.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** @type {import('ts-jest').JestConfigWithTsJest} **/
|
|
2
|
+
export default {
|
|
3
|
+
testEnvironment: "node",
|
|
4
|
+
"moduleNameMapper": {
|
|
5
|
+
"^(\\.{1,2}/.*)\\.js$": "$1",
|
|
6
|
+
},
|
|
7
|
+
"extensionsToTreatAsEsm": [".ts"],
|
|
8
|
+
"transform": {
|
|
9
|
+
"^.+\\.(mt|t|cj|j)s$": [
|
|
10
|
+
"ts-jest",
|
|
11
|
+
{
|
|
12
|
+
"useESM": true
|
|
13
|
+
}
|
|
14
|
+
]
|
|
15
|
+
},
|
|
16
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@mendable/firecrawl",
|
|
3
|
+
"version": "1.2.2",
|
|
4
|
+
"description": "JavaScript SDK for Firecrawl API",
|
|
5
|
+
"main": "build/cjs/index.js",
|
|
6
|
+
"types": "types/index.d.ts",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"exports": {
|
|
9
|
+
"require": {
|
|
10
|
+
"types": "./types/index.d.ts",
|
|
11
|
+
"default": "./build/cjs/index.js"
|
|
12
|
+
},
|
|
13
|
+
"import": {
|
|
14
|
+
"types": "./types/index.d.ts",
|
|
15
|
+
"default": "./build/esm/index.js"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"scripts": {
|
|
19
|
+
"build": "tsc --module commonjs --moduleResolution node10 --outDir build/cjs/ && echo '{\"type\": \"commonjs\"}' > build/cjs/package.json && npx tsc --module NodeNext --moduleResolution NodeNext --outDir build/esm/ && echo '{\"type\": \"module\"}' > build/esm/package.json",
|
|
20
|
+
"build-and-publish": "npm run build && npm publish --access public",
|
|
21
|
+
"publish-beta": "npm run build && npm publish --access public --tag beta",
|
|
22
|
+
"test": "NODE_OPTIONS=--experimental-vm-modules jest --verbose src/__tests__/v1/**/*.test.ts"
|
|
23
|
+
},
|
|
24
|
+
"repository": {
|
|
25
|
+
"type": "git",
|
|
26
|
+
"url": "git+https://github.com/mendableai/firecrawl.git"
|
|
27
|
+
},
|
|
28
|
+
"author": "Mendable.ai",
|
|
29
|
+
"license": "MIT",
|
|
30
|
+
"dependencies": {
|
|
31
|
+
"axios": "^1.6.8",
|
|
32
|
+
"dotenv": "^16.4.5",
|
|
33
|
+
"isows": "^1.0.4",
|
|
34
|
+
"typescript-event-target": "^1.1.1",
|
|
35
|
+
"uuid": "^9.0.1",
|
|
36
|
+
"zod": "^3.23.8",
|
|
37
|
+
"zod-to-json-schema": "^3.23.0"
|
|
38
|
+
},
|
|
39
|
+
"bugs": {
|
|
40
|
+
"url": "https://github.com/mendableai/firecrawl/issues"
|
|
41
|
+
},
|
|
42
|
+
"homepage": "https://github.com/mendableai/firecrawl#readme",
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@jest/globals": "^29.7.0",
|
|
45
|
+
"@types/axios": "^0.14.0",
|
|
46
|
+
"@types/dotenv": "^8.2.0",
|
|
47
|
+
"@types/jest": "^29.5.12",
|
|
48
|
+
"@types/mocha": "^10.0.6",
|
|
49
|
+
"@types/node": "^20.12.12",
|
|
50
|
+
"@types/uuid": "^9.0.8",
|
|
51
|
+
"jest": "^29.7.0",
|
|
52
|
+
"ts-jest": "^29.2.2",
|
|
53
|
+
"typescript": "^5.4.5"
|
|
54
|
+
},
|
|
55
|
+
"keywords": [
|
|
56
|
+
"firecrawl",
|
|
57
|
+
"mendable",
|
|
58
|
+
"crawler",
|
|
59
|
+
"web",
|
|
60
|
+
"scraper",
|
|
61
|
+
"api",
|
|
62
|
+
"sdk"
|
|
63
|
+
]
|
|
64
|
+
}
|