@howells/fieldwork-sdk 0.3.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -2
- package/dist/{adapter-DGehHCMo.d.ts → adapter-CDY8qczv.d.ts} +16 -2
- package/dist/brave.d.ts +6 -4
- package/dist/brave.js +199 -116
- package/dist/browserbase.d.ts +8 -6
- package/dist/browserbase.js +85 -39
- package/dist/exa.d.ts +23 -19
- package/dist/exa.js +300 -160
- package/dist/{fieldwork-B3x3cxDJ.d.ts → fieldwork-DTNVIOzp.d.ts} +3 -3
- package/dist/firecrawl.d.ts +28 -25
- package/dist/firecrawl.js +589 -305
- package/dist/index.d.ts +4 -3
- package/dist/index.js +25 -11
- package/dist/parallel.d.ts +31 -26
- package/dist/parallel.js +407 -203
- package/dist/parse-CxOri73y.js +441 -0
- package/dist/perplexity.d.ts +13 -9
- package/dist/perplexity.js +145 -77
- package/dist/schema-EZlBkY5B.d.ts +90 -0
- package/dist/schema-teOy7Od-.js +45 -0
- package/dist/serpapi.d.ts +7 -4
- package/dist/serpapi.js +264 -162
- package/dist/tavily.d.ts +15 -12
- package/dist/tavily.js +191 -117
- package/dist/tools.d.ts +2 -2
- package/dist/util-DhYr1OS3.d.ts +1 -0
- package/package.json +4 -1
- package/dist/util-YaZYZDSk.js +0 -287
package/dist/firecrawl.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { t as defineAdapter } from "./adapter-CEAQuT7F.js";
|
|
2
2
|
import { r as withJob, t as FieldworkError } from "./errors-BiIBG9zN.js";
|
|
3
|
-
import { S as requireKey,
|
|
3
|
+
import { C as createRawClient, E as callSettings, I as refuseTogether, L as requireJobId, N as presentPage, P as presentPages, S as withOriginal, T as requireKey, a as looseObject, b as warningEntry, c as optionalArrayOf, d as optionalId, f as optionalNumber, h as optionalString, i as both, j as meta, k as compact, l as optionalBoolean, m as optionalScalar, n as anything, p as optionalObject, r as arrayOf, u as optionalFirstString, v as recordOf, w as poll } from "./parse-CxOri73y.js";
|
|
4
|
+
import { n as jsonSchemaOf, t as checkOutput } from "./schema-teOy7Od-.js";
|
|
5
|
+
import * as z from "zod/mini";
|
|
4
6
|
// src/adapters/firecrawl/shared.ts
|
|
5
7
|
const provider = "firecrawl";
|
|
6
8
|
const invalid = (message) => new FieldworkError("InvalidRequest", message, { provider });
|
|
7
9
|
const segment = (id) => encodeURIComponent(id);
|
|
8
|
-
const warnings = (...values) => values.flatMap((value) => typeof value === "string" ? [value] : list(value).map(String));
|
|
9
10
|
const country = (code) => code?.toUpperCase();
|
|
10
11
|
// src/adapters/firecrawl/schedule.ts
|
|
11
12
|
/** The fewest minutes Firecrawl allows between two checks of a monitor. */
|
|
@@ -40,7 +41,7 @@ const runGaps = (minutes, hours) => {
|
|
|
40
41
|
const gaps = minutes.slice(1).map((minute, index) => minute - (minutes[index] ?? 0));
|
|
41
42
|
const [first] = minutes;
|
|
42
43
|
const last = minutes.at(-1);
|
|
43
|
-
if (hours?.some((hour) => hours.includes((hour + 1) % 24)) && first !== void 0 && last !== void 0) gaps.push(60 - last + first);
|
|
44
|
+
if (hours?.some((hour) => hours.includes((hour + 1) % 24)) === true && first !== void 0 && last !== void 0) gaps.push(60 - last + first);
|
|
44
45
|
return gaps;
|
|
45
46
|
};
|
|
46
47
|
const checkCron = (cron) => {
|
|
@@ -61,11 +62,11 @@ const cronFor = (schedule) => {
|
|
|
61
62
|
if ("cron" in schedule) return checkCron(schedule.cron);
|
|
62
63
|
const every = schedule.every;
|
|
63
64
|
const named = NAMED_CRON.get(every);
|
|
64
|
-
if (named) return named;
|
|
65
|
+
if (named !== void 0) return named;
|
|
65
66
|
const groups = INTERVAL.exec(every)?.groups;
|
|
66
67
|
const count = Number(groups?.count);
|
|
67
68
|
const cron = groups?.unit === "h" ? hourlyCron(count) : DAILY_CRON.get(count);
|
|
68
|
-
if (cron) return cron;
|
|
69
|
+
if (cron !== void 0) return cron;
|
|
69
70
|
throw invalid(`firecrawl cannot run a monitor every "${every}"; use hour, day, week, a number of hours that divides 24, 1d, 7d or a cron expression`);
|
|
70
71
|
};
|
|
71
72
|
// src/adapters/firecrawl/request.ts
|
|
@@ -156,7 +157,7 @@ const timeFilter = (o) => {
|
|
|
156
157
|
};
|
|
157
158
|
const searchBody = (query, o) => {
|
|
158
159
|
refuseTogether(provider, o, "includeDomains", "excludeDomains");
|
|
159
|
-
if (o.categories?.includes("gov") && o.categories.length > 1) throw invalid("firecrawl searches the gov category on its own; do not combine it with another category");
|
|
160
|
+
if (o.categories?.includes("gov") === true && o.categories.length > 1) throw invalid("firecrawl searches the gov category on its own; do not combine it with another category");
|
|
160
161
|
return compact({
|
|
161
162
|
categories: o.categories?.map((type) => ({ type })),
|
|
162
163
|
country: country(o.country),
|
|
@@ -167,7 +168,7 @@ const searchBody = (query, o) => {
|
|
|
167
168
|
location: o.location,
|
|
168
169
|
query,
|
|
169
170
|
safe: o.safe,
|
|
170
|
-
scrapeOptions: o.content ? { formats: ["markdown"] } : void 0,
|
|
171
|
+
scrapeOptions: o.content === true ? { formats: ["markdown"] } : void 0,
|
|
171
172
|
sources: o.sources?.map((type) => ({ type })),
|
|
172
173
|
tbs: timeFilter(o)
|
|
173
174
|
});
|
|
@@ -209,18 +210,18 @@ const crawlBody = (url, o) => compact({
|
|
|
209
210
|
});
|
|
210
211
|
const researchBody = (question, o) => compact({
|
|
211
212
|
effort: o.effort,
|
|
212
|
-
location: o.country ? { country: country(o.country) }
|
|
213
|
+
location: o.country === void 0 || o.country === "" ? void 0 : { country: country(o.country) },
|
|
213
214
|
maxCredits: o.maxCredits,
|
|
214
215
|
model: o.model,
|
|
215
216
|
prompt: question,
|
|
216
|
-
schema: o.schema,
|
|
217
|
+
schema: o.schema === void 0 ? void 0 : jsonSchemaOf(o.schema),
|
|
217
218
|
strictConstrainToURLs: o.strictConstrainToURLs,
|
|
218
219
|
threadId: o.continueFrom,
|
|
219
220
|
urls: o.urls
|
|
220
221
|
});
|
|
221
222
|
const sessionBody = (o) => compact({
|
|
222
223
|
activityTtl: o.activityTtl ?? o.ttl,
|
|
223
|
-
location: o.country ? { country: country(o.country) }
|
|
224
|
+
location: o.country === void 0 || o.country === "" ? void 0 : { country: country(o.country) },
|
|
224
225
|
profile: o.profile,
|
|
225
226
|
ttl: o.ttl
|
|
226
227
|
});
|
|
@@ -248,7 +249,7 @@ const scriptRequest = (code, language, call, seconds) => ({
|
|
|
248
249
|
const parseForm = (document, o) => {
|
|
249
250
|
const extension = document.name.split(".").pop()?.toLowerCase() ?? "";
|
|
250
251
|
const mediaType = MEDIA_TYPES.get(extension);
|
|
251
|
-
if (
|
|
252
|
+
if (mediaType === void 0) throw invalid(`firecrawl parses ${[...MEDIA_TYPES.keys()].join(", ")} files, not "${document.name}"`);
|
|
252
253
|
const size = document.data instanceof Blob ? document.data.size : document.data.byteLength;
|
|
253
254
|
if (size > MAX_PARSE_BYTES) throw invalid(`firecrawl parses files up to 50 MB; ${document.name} is ${(size / 1024 / 1024).toFixed(1)} MB`);
|
|
254
255
|
const parser = compact({
|
|
@@ -264,7 +265,8 @@ const parseForm = (document, o) => {
|
|
|
264
265
|
formats: ["markdown"],
|
|
265
266
|
parsers: [parser]
|
|
266
267
|
}));
|
|
267
|
-
|
|
268
|
+
const part = document.data instanceof Uint8Array ? new Uint8Array(document.data) : document.data;
|
|
269
|
+
form.set("file", new Blob([part], { type: mediaType }), document.name);
|
|
268
270
|
return form;
|
|
269
271
|
};
|
|
270
272
|
const monitorTarget = (o) => {
|
|
@@ -281,7 +283,7 @@ const monitorTarget = (o) => {
|
|
|
281
283
|
urls: o.urls
|
|
282
284
|
};
|
|
283
285
|
}
|
|
284
|
-
if (
|
|
286
|
+
if (o.query === void 0 || o.query === "") throw invalid("firecrawl monitors need urls to watch or a query");
|
|
285
287
|
if (o.query.length > MAX_MONITOR_QUERY) throw invalid(`firecrawl searches queries of up to ${MAX_MONITOR_QUERY} characters; pass urls to watch pages with a longer query`);
|
|
286
288
|
return compact({
|
|
287
289
|
excludeDomains: o.excludeDomains,
|
|
@@ -303,7 +305,7 @@ const monitorBody = (o) => {
|
|
|
303
305
|
timezone: o.timezone
|
|
304
306
|
}),
|
|
305
307
|
targets: [target],
|
|
306
|
-
webhook: o.webhookUrl ? { url: o.webhookUrl }
|
|
308
|
+
webhook: o.webhookUrl === void 0 || o.webhookUrl === "" ? void 0 : { url: o.webhookUrl }
|
|
307
309
|
});
|
|
308
310
|
};
|
|
309
311
|
// src/adapters/firecrawl/response.ts
|
|
@@ -315,84 +317,70 @@ const PAPER_URLS = /* @__PURE__ */ new Map([
|
|
|
315
317
|
["doi", (id) => `https://doi.org/${id}`]
|
|
316
318
|
]);
|
|
317
319
|
const LANGUAGE = /^(?<code>[a-z]{2})(?:[-_]|$)/u;
|
|
318
|
-
|
|
319
|
-
const
|
|
320
|
+
/** The list, or undefined when it is empty. */
|
|
321
|
+
const some = (items) => items.length > 0 ? [...items] : void 0;
|
|
322
|
+
const languageCode = (value) => LANGUAGE.exec(value?.toLowerCase() ?? "")?.groups?.code;
|
|
320
323
|
const excerptsOf = (data) => {
|
|
321
|
-
const
|
|
322
|
-
|
|
323
|
-
const answer = text(data.answer);
|
|
324
|
-
return highlights ?? (answer ? [answer] : void 0);
|
|
325
|
-
};
|
|
326
|
-
const pageMeta = (top, data) => {
|
|
327
|
-
const metadata = record(data.metadata);
|
|
328
|
-
return meta({
|
|
329
|
-
credits: metadata.creditsUsed,
|
|
330
|
-
requestId: metadata.scrapeId,
|
|
331
|
-
warnings: warnings(data.warning, top.warning)
|
|
332
|
-
});
|
|
324
|
+
const { list, text } = data.highlights;
|
|
325
|
+
return (text === void 0 ? some(list) : [text]) ?? (data.answer === void 0 ? void 0 : [data.answer]);
|
|
333
326
|
};
|
|
334
|
-
const
|
|
335
|
-
|
|
327
|
+
const pageMeta = (data, topNotes) => meta({
|
|
328
|
+
credits: data.metadata.creditsUsed,
|
|
329
|
+
requestId: data.metadata.scrapeId,
|
|
330
|
+
warnings: [...data.warning.notes, ...topNotes]
|
|
331
|
+
});
|
|
332
|
+
/** A page from scraped data; the caller adds `raw`. `topNotes` are the warnings of the whole response. */
|
|
333
|
+
const toPage = (data, fallbackUrl, topNotes = []) => {
|
|
334
|
+
const { metadata } = data;
|
|
336
335
|
return compact({
|
|
337
|
-
author:
|
|
338
|
-
description:
|
|
336
|
+
author: metadata.author,
|
|
337
|
+
description: metadata.description,
|
|
339
338
|
excerpts: excerptsOf(data),
|
|
340
|
-
favicon:
|
|
341
|
-
html:
|
|
342
|
-
image:
|
|
343
|
-
images:
|
|
339
|
+
favicon: metadata.favicon,
|
|
340
|
+
html: data.html,
|
|
341
|
+
image: metadata.ogImage ?? metadata["og:image"],
|
|
342
|
+
images: some(data.images),
|
|
344
343
|
language: languageCode(metadata.language),
|
|
345
|
-
links:
|
|
346
|
-
markdown:
|
|
347
|
-
meta: pageMeta(
|
|
348
|
-
publishedAt:
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
url: text(metadata.url) ?? text(metadata.sourceURL) ?? fallbackUrl
|
|
344
|
+
links: some(data.links),
|
|
345
|
+
markdown: data.markdown,
|
|
346
|
+
meta: pageMeta(data, topNotes),
|
|
347
|
+
publishedAt: metadata.publishedTime ?? metadata["article:published_time"],
|
|
348
|
+
rawHtml: data.rawHtml,
|
|
349
|
+
screenshot: data.screenshot,
|
|
350
|
+
statusCode: metadata.statusCode,
|
|
351
|
+
summary: data.summary,
|
|
352
|
+
title: metadata.title,
|
|
353
|
+
url: metadata.url ?? metadata.sourceURL ?? fallbackUrl
|
|
356
354
|
});
|
|
357
355
|
};
|
|
358
|
-
const price = (
|
|
359
|
-
const item = record(value);
|
|
356
|
+
const price = (item) => {
|
|
360
357
|
const result = compact({
|
|
361
|
-
amount:
|
|
362
|
-
currency:
|
|
363
|
-
formatted:
|
|
358
|
+
amount: item.amount,
|
|
359
|
+
currency: item.currency,
|
|
360
|
+
formatted: item.formatted
|
|
364
361
|
});
|
|
365
362
|
return Object.keys(result).length > 0 ? result : void 0;
|
|
366
363
|
};
|
|
367
|
-
const gtin = (variant) =>
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
}
|
|
378
|
-
};
|
|
379
|
-
const toVariant = (value) => {
|
|
380
|
-
const variant = record(value);
|
|
381
|
-
const availability = record(variant.availability);
|
|
382
|
-
const values = Object.fromEntries(Object.entries(record(variant.values)).flatMap(([key, item]) => {
|
|
383
|
-
const option = scalar(item);
|
|
384
|
-
return option === void 0 ? [] : [[key, option]];
|
|
385
|
-
}));
|
|
364
|
+
const gtin = (variant) => [
|
|
365
|
+
variant.gtin,
|
|
366
|
+
variant.gtin14,
|
|
367
|
+
variant.gtin13,
|
|
368
|
+
variant.gtin12,
|
|
369
|
+
variant.gtin8
|
|
370
|
+
].find((value) => value !== void 0 && value !== "");
|
|
371
|
+
const images = (found) => some(found.filter((image) => image !== void 0));
|
|
372
|
+
const toVariant = (variant) => {
|
|
373
|
+
const values = Object.fromEntries(Object.entries(variant.values).flatMap(([key, item]) => item === void 0 ? [] : [[key, item]]));
|
|
386
374
|
return compact({
|
|
387
|
-
availability:
|
|
375
|
+
availability: variant.availability.text,
|
|
388
376
|
gtin: gtin(variant),
|
|
389
|
-
id:
|
|
390
|
-
images:
|
|
391
|
-
inStock:
|
|
392
|
-
originalPrice: price(
|
|
377
|
+
id: variant.id,
|
|
378
|
+
images: images(variant.images),
|
|
379
|
+
inStock: variant.availability.inStock,
|
|
380
|
+
originalPrice: price(variant.sale.originalPrice),
|
|
393
381
|
price: price(variant.price),
|
|
394
|
-
sku:
|
|
395
|
-
title:
|
|
382
|
+
sku: variant.sku,
|
|
383
|
+
title: variant.title,
|
|
396
384
|
values: Object.keys(values).length > 0 ? values : void 0
|
|
397
385
|
});
|
|
398
386
|
};
|
|
@@ -401,224 +389,474 @@ const allImages = (variants) => {
|
|
|
401
389
|
for (const image of variants.flatMap((variant) => variant.images ?? [])) if (!seen.has(image.url)) seen.set(image.url, image);
|
|
402
390
|
return seen.size > 0 ? [...seen.values()] : void 0;
|
|
403
391
|
};
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
provider
|
|
410
|
-
});
|
|
411
|
-
}
|
|
412
|
-
const product = record(data.product);
|
|
413
|
-
const variants = list(product.variants).map((variant) => toVariant(variant));
|
|
392
|
+
/** The product on a scraped page; the caller adds `raw`. Undefined when the page has none. */
|
|
393
|
+
const toProduct = (body) => {
|
|
394
|
+
const { product } = body.data;
|
|
395
|
+
if (product === void 0) return;
|
|
396
|
+
const variants = product.variants.map((variant) => toVariant(variant));
|
|
414
397
|
return compact({
|
|
415
|
-
brand:
|
|
416
|
-
category:
|
|
417
|
-
description:
|
|
418
|
-
images:
|
|
419
|
-
meta: pageMeta(
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
url: text(product.url),
|
|
398
|
+
brand: product.brand,
|
|
399
|
+
category: product.category,
|
|
400
|
+
description: product.description,
|
|
401
|
+
images: images(product.images) ?? allImages(variants),
|
|
402
|
+
meta: pageMeta(body.data, body.warning.notes),
|
|
403
|
+
title: product.title,
|
|
404
|
+
url: product.url,
|
|
423
405
|
variants
|
|
424
406
|
});
|
|
425
407
|
};
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
const
|
|
439
|
-
const
|
|
440
|
-
const paperId = text(paper.paperId) ?? "";
|
|
441
|
-
const primary = text(paper.primaryId) ?? paperId;
|
|
408
|
+
/** Why a page has no product: the warning it carries, if any. */
|
|
409
|
+
const noProductReason = (body) => body.data.warning.text ?? body.warning.text;
|
|
410
|
+
const searchItem = (result, kind) => compact({
|
|
411
|
+
content: result.markdown,
|
|
412
|
+
image: result.imageUrl,
|
|
413
|
+
kind: result.category ?? kind,
|
|
414
|
+
publishedAt: result.date,
|
|
415
|
+
snippet: result.description ?? result.snippet,
|
|
416
|
+
title: result.title,
|
|
417
|
+
url: result.url ?? ""
|
|
418
|
+
});
|
|
419
|
+
const paperItem = (paper) => {
|
|
420
|
+
const paperId = paper.paperId ?? "";
|
|
421
|
+
const primary = paper.primaryId ?? paperId;
|
|
442
422
|
const colon = primary.indexOf(":");
|
|
443
423
|
const resolve = colon > 0 ? PAPER_URLS.get(primary.slice(0, colon)) : void 0;
|
|
444
424
|
return compact({
|
|
445
425
|
kind: "research",
|
|
446
|
-
score:
|
|
447
|
-
snippet:
|
|
448
|
-
title:
|
|
426
|
+
score: paper.score,
|
|
427
|
+
snippet: paper.abstract,
|
|
428
|
+
title: paper.title,
|
|
449
429
|
url: paperId.startsWith("web:") ? paperId.slice(4) : resolve?.(primary.slice(colon + 1)) ?? primary
|
|
450
430
|
});
|
|
451
431
|
};
|
|
452
|
-
const imageItems = (
|
|
453
|
-
const
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
title: text(image.title),
|
|
432
|
+
const imageItems = (found) => found.flatMap((image) => {
|
|
433
|
+
const { imageUrl: url } = image;
|
|
434
|
+
return url === void 0 ? [] : [compact({
|
|
435
|
+
height: image.imageHeight,
|
|
436
|
+
sourceUrl: image.url,
|
|
437
|
+
title: image.title,
|
|
459
438
|
url,
|
|
460
|
-
width:
|
|
461
|
-
})]
|
|
439
|
+
width: image.imageWidth
|
|
440
|
+
})];
|
|
462
441
|
});
|
|
463
|
-
const searchMeta = (
|
|
464
|
-
credits:
|
|
465
|
-
requestId:
|
|
466
|
-
warnings:
|
|
442
|
+
const searchMeta = (body) => meta({
|
|
443
|
+
credits: body.creditsUsed,
|
|
444
|
+
requestId: body.id,
|
|
445
|
+
warnings: [...body.warning, ...body.warnings]
|
|
467
446
|
});
|
|
468
|
-
|
|
469
|
-
|
|
447
|
+
/** The results of a search; the caller adds `raw`. */
|
|
448
|
+
const searchResult = (body) => {
|
|
449
|
+
const { data } = body;
|
|
470
450
|
return compact({
|
|
471
|
-
images:
|
|
472
|
-
meta: searchMeta(
|
|
473
|
-
raw: response,
|
|
451
|
+
images: data.images === void 0 ? void 0 : imageItems(data.images),
|
|
452
|
+
meta: searchMeta(body),
|
|
474
453
|
results: [
|
|
475
|
-
...
|
|
476
|
-
...
|
|
477
|
-
...
|
|
454
|
+
...data.web.map((item) => searchItem(item, "web")),
|
|
455
|
+
...data.news.map((item) => searchItem(item, "news")),
|
|
456
|
+
...data.research.map((item) => paperItem(item))
|
|
478
457
|
]
|
|
479
458
|
});
|
|
480
459
|
};
|
|
481
|
-
const imagesResult = (
|
|
482
|
-
meta: searchMeta(
|
|
483
|
-
|
|
484
|
-
results: imageItems(record(response.data).images)
|
|
460
|
+
const imagesResult = (body) => compact({
|
|
461
|
+
meta: searchMeta(body),
|
|
462
|
+
results: imageItems(body.data.images ?? [])
|
|
485
463
|
});
|
|
486
|
-
const failedPages = (errors) =>
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
const researchState = (id, status) => {
|
|
494
|
-
const state = text(status.status);
|
|
464
|
+
const failedPages = (errors) => errors.value.errors.map((entry) => ({
|
|
465
|
+
error: entry.error ?? "unknown error",
|
|
466
|
+
url: entry.url ?? ""
|
|
467
|
+
}));
|
|
468
|
+
const researchState = (id, entry) => {
|
|
469
|
+
const status = entry.value;
|
|
470
|
+
const state = status.status;
|
|
495
471
|
const hasPartial = status.partial !== void 0 && status.partial !== null;
|
|
496
472
|
const done = state === "completed" || state === "failed" && hasPartial;
|
|
497
|
-
if (!done && (state === "failed" || state === "cancelled")) throw new FieldworkError("JobFailed", `firecrawl research run ${id} ${state}: ${
|
|
498
|
-
cause:
|
|
473
|
+
if (!done && (state === "failed" || state === "cancelled")) throw new FieldworkError("JobFailed", `firecrawl research run ${id} ${state}: ${status.error ?? status.stopReason ?? "no reason given"}`, {
|
|
474
|
+
cause: entry.original,
|
|
499
475
|
provider
|
|
500
476
|
});
|
|
501
|
-
return done ?
|
|
477
|
+
return done ? entry : void 0;
|
|
502
478
|
};
|
|
503
|
-
const researchResult = (id, started,
|
|
479
|
+
const researchResult = (id, started, entry) => {
|
|
480
|
+
const run = entry.value;
|
|
504
481
|
const stopped = run.status === "failed";
|
|
505
482
|
const status = stopped ? "partial" : "completed";
|
|
506
483
|
return compact({
|
|
507
|
-
continuationId:
|
|
484
|
+
continuationId: run.threadId ?? started.value.threadId,
|
|
508
485
|
id,
|
|
509
486
|
meta: meta({
|
|
510
487
|
credits: run.creditsUsed,
|
|
511
488
|
requestId: id,
|
|
512
|
-
warnings: stopped ? [run.message, run.partialSchemaValid === false ? "the partial output does not match the schema" : void 0] : void 0
|
|
489
|
+
warnings: stopped ? [run.message.note, run.partialSchemaValid === false ? "the partial output does not match the schema" : void 0].filter((note) => note !== void 0) : void 0
|
|
513
490
|
}),
|
|
514
|
-
output: stopped ? run.partial : run.data ?? run.message,
|
|
515
|
-
raw:
|
|
491
|
+
output: stopped ? run.partial : run.data ?? run.message.value,
|
|
492
|
+
raw: entry.original,
|
|
516
493
|
sources: [],
|
|
517
494
|
status,
|
|
518
|
-
stopReason: stopped ?
|
|
495
|
+
stopReason: stopped ? run.stopReason ?? run.error ?? "failed" : void 0
|
|
519
496
|
});
|
|
520
497
|
};
|
|
521
|
-
const actResult = (
|
|
522
|
-
const
|
|
498
|
+
const actResult = (entry, sessionId, closed) => {
|
|
499
|
+
const result = entry.value;
|
|
500
|
+
const stdout = result.stdout ?? "";
|
|
523
501
|
const failure = result.success === false ? "firecrawl reported that the script did not succeed" : void 0;
|
|
524
502
|
const repeated = result.result === "" || result.result === null || result.result === stdout;
|
|
525
503
|
return compact({
|
|
526
|
-
error:
|
|
527
|
-
exitCode:
|
|
528
|
-
killed:
|
|
504
|
+
error: result.error ?? failure,
|
|
505
|
+
exitCode: result.exitCode,
|
|
506
|
+
killed: result.killed,
|
|
529
507
|
meta: meta({ credits: closed?.creditsBilled }),
|
|
530
|
-
raw:
|
|
508
|
+
raw: entry.original,
|
|
531
509
|
result: repeated ? void 0 : result.result,
|
|
532
510
|
sessionId,
|
|
533
|
-
stderr:
|
|
511
|
+
stderr: result.stderr ?? "",
|
|
534
512
|
stdout
|
|
535
513
|
});
|
|
536
514
|
};
|
|
537
|
-
const browserSession = (
|
|
538
|
-
|
|
539
|
-
expiresAt: text(response.expiresAt),
|
|
540
|
-
id: requireId(provider, response.id),
|
|
541
|
-
liveViewUrl: text(response.liveViewUrl),
|
|
542
|
-
raw: response
|
|
543
|
-
});
|
|
544
|
-
const parseResult = (response) => {
|
|
545
|
-
const data = record(response.data);
|
|
546
|
-
const metadata = record(data.metadata);
|
|
515
|
+
const browserSession = (entry) => {
|
|
516
|
+
const session = entry.value;
|
|
547
517
|
return compact({
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
518
|
+
cdpUrl: session.cdpUrl,
|
|
519
|
+
expiresAt: session.expiresAt,
|
|
520
|
+
id: requireJobId(provider, session.id),
|
|
521
|
+
liveViewUrl: session.liveViewUrl,
|
|
522
|
+
raw: entry.original
|
|
523
|
+
});
|
|
524
|
+
};
|
|
525
|
+
/** A parsed document; the caller adds `raw`. */
|
|
526
|
+
const parseResult = (body) => {
|
|
527
|
+
const { data } = body;
|
|
528
|
+
return compact({
|
|
529
|
+
markdown: data.markdown ?? "",
|
|
530
|
+
pages: data.pages?.map((page) => ({
|
|
531
|
+
markdown: page.markdown ?? "",
|
|
532
|
+
pageNumber: Number(page.pageNumber)
|
|
533
|
+
})),
|
|
534
|
+
blocks: data.blocks,
|
|
535
|
+
pageCount: data.metadata.totalPages ?? data.metadata.numPages,
|
|
536
|
+
meta: pageMeta(data, body.warning.notes)
|
|
557
537
|
});
|
|
558
538
|
};
|
|
559
539
|
const watching = (monitor) => {
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
if (target.type === "
|
|
564
|
-
|
|
565
|
-
return strings(target.queries) ?? [];
|
|
540
|
+
if (monitor.goal !== void 0) return monitor.goal;
|
|
541
|
+
return monitor.targets.flatMap((target) => {
|
|
542
|
+
if (target.type === "scrape") return target.urls;
|
|
543
|
+
if (target.type === "crawl") return [target.url];
|
|
544
|
+
return target.queries;
|
|
566
545
|
}).filter((item) => item !== void 0).join(", ") || void 0;
|
|
567
546
|
};
|
|
568
|
-
const monitorInfo = (
|
|
569
|
-
const monitor =
|
|
570
|
-
const schedule = record(monitor.schedule);
|
|
547
|
+
const monitorInfo = (entry) => {
|
|
548
|
+
const monitor = entry.value;
|
|
571
549
|
return compact({
|
|
572
|
-
createdAt:
|
|
573
|
-
id:
|
|
574
|
-
raw:
|
|
575
|
-
schedule:
|
|
576
|
-
status:
|
|
550
|
+
createdAt: monitor.createdAt,
|
|
551
|
+
id: requireJobId(provider, monitor.id),
|
|
552
|
+
raw: entry.original,
|
|
553
|
+
schedule: monitor.schedule.cron ?? monitor.schedule.text,
|
|
554
|
+
status: monitor.status,
|
|
577
555
|
watch: watching(monitor),
|
|
578
|
-
webhookUrl:
|
|
556
|
+
webhookUrl: monitor.webhook.url
|
|
579
557
|
});
|
|
580
558
|
};
|
|
581
|
-
const checkEvent = (
|
|
582
|
-
const
|
|
559
|
+
const checkEvent = (entry) => {
|
|
560
|
+
const check = entry.value;
|
|
561
|
+
const { summary } = check;
|
|
583
562
|
const counts = [
|
|
584
563
|
"changed",
|
|
585
564
|
"new",
|
|
586
565
|
"removed",
|
|
587
566
|
"error"
|
|
588
567
|
].flatMap((key) => {
|
|
589
|
-
const count =
|
|
568
|
+
const count = summary[key];
|
|
590
569
|
return count === void 0 ? [] : [`${count} ${key}`];
|
|
591
570
|
});
|
|
592
|
-
const pages =
|
|
571
|
+
const pages = summary.totalPages;
|
|
593
572
|
const of = pages === void 0 ? "" : ` of ${pages} pages`;
|
|
594
573
|
return compact({
|
|
595
|
-
at:
|
|
596
|
-
id:
|
|
597
|
-
raw:
|
|
574
|
+
at: check.finishedAt ?? check.startedAt ?? check.scheduledFor ?? check.createdAt,
|
|
575
|
+
id: check.id,
|
|
576
|
+
raw: entry.original,
|
|
598
577
|
summary: [
|
|
599
|
-
|
|
578
|
+
check.status,
|
|
600
579
|
counts.length > 0 ? `${counts.join(", ")}${of}` : void 0,
|
|
601
|
-
|
|
580
|
+
check.error
|
|
602
581
|
].filter((part) => part !== void 0).join(": ")
|
|
603
582
|
});
|
|
604
583
|
};
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
584
|
+
/** One page of a monitor's checks; the caller adds `raw`. */
|
|
585
|
+
const monitorEvents = (checks, offset) => compact({
|
|
586
|
+
events: checks.map((check) => checkEvent(check)),
|
|
587
|
+
next: checks.length === 100 ? String(offset + checks.length) : void 0
|
|
588
|
+
});
|
|
589
|
+
/** The account's credit usage; the caller adds `raw`. */
|
|
590
|
+
const usageResult = (body) => compact({
|
|
591
|
+
limit: body.data.planCredits,
|
|
592
|
+
periodEnd: body.data.billingPeriodEnd,
|
|
593
|
+
remaining: body.data.remainingCredits
|
|
594
|
+
});
|
|
595
|
+
// src/adapters/firecrawl/shapes.ts
|
|
596
|
+
/**
|
|
597
|
+
* Warnings as text: a string is one warning (an empty one too); an array gives
|
|
598
|
+
* every entry as a string, whatever it is; anything else gives none.
|
|
599
|
+
*/
|
|
600
|
+
const Notes = z.union([z.pipe(z.string(), z.transform((note) => [note])), arrayOf(z.pipe(z.unknown(), z.transform(String)))]);
|
|
601
|
+
/** A warning, as its text when it is a non-empty string and as the list of warnings it amounts to. */
|
|
602
|
+
const Warning = z.pipe(both(optionalString, Notes), z.transform(({ first, second }) => ({
|
|
603
|
+
notes: second,
|
|
604
|
+
text: first
|
|
605
|
+
})));
|
|
606
|
+
/** A product image: a bare URL, or an object with a URL (or `src`) and a description. One without a URL reads as undefined. */
|
|
607
|
+
const Image = z.union([z.pipe(z.string(), z.transform((url) => url === "" ? void 0 : { url })), z.pipe(looseObject({
|
|
608
|
+
alt: optionalString,
|
|
609
|
+
src: optionalString,
|
|
610
|
+
url: optionalString
|
|
611
|
+
}), z.transform((image) => {
|
|
612
|
+
const url = image.url ?? image.src;
|
|
613
|
+
return url === void 0 ? void 0 : compact({
|
|
614
|
+
alt: image.alt,
|
|
615
|
+
url
|
|
620
616
|
});
|
|
617
|
+
}))]);
|
|
618
|
+
/** A price. The amount is a string or a number, read as a string. */
|
|
619
|
+
const Price = looseObject({
|
|
620
|
+
amount: optionalId,
|
|
621
|
+
currency: optionalString,
|
|
622
|
+
formatted: optionalString
|
|
623
|
+
});
|
|
624
|
+
const Variant = looseObject({
|
|
625
|
+
availability: looseObject({
|
|
626
|
+
inStock: optionalBoolean,
|
|
627
|
+
text: optionalString
|
|
628
|
+
}),
|
|
629
|
+
gtin: optionalScalar,
|
|
630
|
+
gtin12: optionalScalar,
|
|
631
|
+
gtin13: optionalScalar,
|
|
632
|
+
gtin14: optionalScalar,
|
|
633
|
+
gtin8: optionalScalar,
|
|
634
|
+
id: optionalString,
|
|
635
|
+
images: arrayOf(Image),
|
|
636
|
+
price: Price,
|
|
637
|
+
sale: looseObject({ originalPrice: Price }),
|
|
638
|
+
sku: optionalString,
|
|
639
|
+
title: optionalString,
|
|
640
|
+
values: recordOf(optionalScalar)
|
|
641
|
+
});
|
|
642
|
+
/** The metadata of a scraped page, and of a parsed document. */
|
|
643
|
+
const metadataShape = {
|
|
644
|
+
"article:published_time": optionalString,
|
|
645
|
+
author: optionalFirstString,
|
|
646
|
+
creditsUsed: optionalNumber,
|
|
647
|
+
description: optionalFirstString,
|
|
648
|
+
favicon: optionalString,
|
|
649
|
+
language: optionalFirstString,
|
|
650
|
+
numPages: optionalNumber,
|
|
651
|
+
"og:image": optionalFirstString,
|
|
652
|
+
ogImage: optionalFirstString,
|
|
653
|
+
publishedTime: optionalString,
|
|
654
|
+
scrapeId: optionalScalar,
|
|
655
|
+
sourceURL: optionalString,
|
|
656
|
+
statusCode: optionalNumber,
|
|
657
|
+
title: optionalFirstString,
|
|
658
|
+
totalPages: optionalNumber,
|
|
659
|
+
url: optionalString
|
|
621
660
|
};
|
|
661
|
+
/** What a scrape returns for one page. `json` is kept as it arrived. */
|
|
662
|
+
const PageData = looseObject({
|
|
663
|
+
answer: optionalString,
|
|
664
|
+
highlights: z.pipe(both(optionalString, arrayOf(z.string())), z.transform(({ first, second }) => ({
|
|
665
|
+
list: second,
|
|
666
|
+
text: first
|
|
667
|
+
}))),
|
|
668
|
+
html: optionalString,
|
|
669
|
+
images: arrayOf(z.string()),
|
|
670
|
+
json: anything,
|
|
671
|
+
links: arrayOf(z.string()),
|
|
672
|
+
markdown: optionalString,
|
|
673
|
+
metadata: looseObject(metadataShape),
|
|
674
|
+
product: optionalObject({
|
|
675
|
+
brand: optionalString,
|
|
676
|
+
category: optionalString,
|
|
677
|
+
description: optionalString,
|
|
678
|
+
images: arrayOf(Image),
|
|
679
|
+
title: optionalString,
|
|
680
|
+
url: optionalString,
|
|
681
|
+
variants: arrayOf(Variant)
|
|
682
|
+
}),
|
|
683
|
+
rawHtml: optionalString,
|
|
684
|
+
screenshot: optionalString,
|
|
685
|
+
summary: optionalString,
|
|
686
|
+
warning: Warning
|
|
687
|
+
});
|
|
688
|
+
/** `/scrape`. */
|
|
689
|
+
const ScrapeResponse = looseObject({
|
|
690
|
+
data: PageData,
|
|
691
|
+
warning: Warning
|
|
692
|
+
});
|
|
693
|
+
/** A page of a crawl or batch, beside the entry as it arrived. */
|
|
694
|
+
const PageEntry = withOriginal(PageData);
|
|
695
|
+
/** A crawl or batch while it runs, and each batch of its pages, beside the response as it arrived. */
|
|
696
|
+
const Batch = withOriginal(looseObject({
|
|
697
|
+
creditsUsed: optionalNumber,
|
|
698
|
+
data: arrayOf(PageEntry),
|
|
699
|
+
next: optionalString,
|
|
700
|
+
status: optionalString,
|
|
701
|
+
total: optionalNumber
|
|
702
|
+
}));
|
|
703
|
+
/** The pages a crawl or batch could not read. */
|
|
704
|
+
const BatchErrors = withOriginal(looseObject({
|
|
705
|
+
errors: arrayOf(looseObject({
|
|
706
|
+
error: optionalString,
|
|
707
|
+
url: optionalString
|
|
708
|
+
})),
|
|
709
|
+
robotsBlocked: arrayOf(z.string())
|
|
710
|
+
}));
|
|
711
|
+
/** The reply to starting a crawl. */
|
|
712
|
+
const CrawlStart = looseObject({ id: withOriginal(optionalId) });
|
|
713
|
+
/** The reply to starting a batch scrape or an agent run, beside the response as it arrived. */
|
|
714
|
+
const RunStart = withOriginal(looseObject({
|
|
715
|
+
id: withOriginal(optionalId),
|
|
716
|
+
invalidURLs: arrayOf(z.string()),
|
|
717
|
+
threadId: optionalString
|
|
718
|
+
}));
|
|
719
|
+
/** An agent run while it is polled. */
|
|
720
|
+
const AgentRun = withOriginal(looseObject({
|
|
721
|
+
creditsUsed: optionalNumber,
|
|
722
|
+
data: anything,
|
|
723
|
+
error: optionalString,
|
|
724
|
+
message: z.pipe(both(anything, warningEntry), z.transform(({ first, second }) => ({
|
|
725
|
+
note: second,
|
|
726
|
+
value: first
|
|
727
|
+
}))),
|
|
728
|
+
partial: anything,
|
|
729
|
+
partialSchemaValid: optionalBoolean,
|
|
730
|
+
status: optionalString,
|
|
731
|
+
stopReason: optionalString,
|
|
732
|
+
threadId: optionalString
|
|
733
|
+
}));
|
|
734
|
+
/** A browser session as opened, beside the response as it arrived. */
|
|
735
|
+
const Session = withOriginal(looseObject({
|
|
736
|
+
cdpUrl: optionalString,
|
|
737
|
+
expiresAt: optionalString,
|
|
738
|
+
id: withOriginal(optionalId),
|
|
739
|
+
liveViewUrl: optionalString
|
|
740
|
+
}));
|
|
741
|
+
/** A script's outcome, beside the response as it arrived. */
|
|
742
|
+
const Execution = withOriginal(looseObject({
|
|
743
|
+
error: optionalString,
|
|
744
|
+
exitCode: optionalNumber,
|
|
745
|
+
killed: optionalBoolean,
|
|
746
|
+
result: anything,
|
|
747
|
+
stderr: optionalString,
|
|
748
|
+
stdout: optionalString,
|
|
749
|
+
success: optionalBoolean
|
|
750
|
+
}));
|
|
751
|
+
/** What closing a session billed. */
|
|
752
|
+
const Closed = looseObject({ creditsBilled: optionalNumber });
|
|
753
|
+
const WebItem = looseObject({
|
|
754
|
+
category: optionalString,
|
|
755
|
+
date: optionalString,
|
|
756
|
+
description: optionalString,
|
|
757
|
+
imageUrl: optionalString,
|
|
758
|
+
markdown: optionalString,
|
|
759
|
+
snippet: optionalString,
|
|
760
|
+
title: optionalString,
|
|
761
|
+
url: optionalString
|
|
762
|
+
});
|
|
763
|
+
const Paper = looseObject({
|
|
764
|
+
abstract: optionalString,
|
|
765
|
+
paperId: optionalString,
|
|
766
|
+
primaryId: optionalString,
|
|
767
|
+
score: optionalNumber,
|
|
768
|
+
title: optionalString
|
|
769
|
+
});
|
|
770
|
+
const ImageItem = looseObject({
|
|
771
|
+
imageHeight: optionalNumber,
|
|
772
|
+
imageUrl: optionalString,
|
|
773
|
+
imageWidth: optionalNumber,
|
|
774
|
+
title: optionalString,
|
|
775
|
+
url: optionalString
|
|
776
|
+
});
|
|
777
|
+
/** `/search`. */
|
|
778
|
+
const SearchResponse = looseObject({
|
|
779
|
+
creditsUsed: optionalNumber,
|
|
780
|
+
data: looseObject({
|
|
781
|
+
images: optionalArrayOf(ImageItem),
|
|
782
|
+
news: arrayOf(WebItem),
|
|
783
|
+
research: arrayOf(Paper),
|
|
784
|
+
web: arrayOf(WebItem)
|
|
785
|
+
}),
|
|
786
|
+
id: optionalScalar,
|
|
787
|
+
warning: Notes,
|
|
788
|
+
warnings: Notes
|
|
789
|
+
});
|
|
790
|
+
/** `/map`: each link is a bare URL or an object. */
|
|
791
|
+
const MapResponse = looseObject({ links: arrayOf(z.union([z.pipe(z.string(), z.transform((url) => ({ url }))), z.pipe(looseObject({
|
|
792
|
+
description: optionalString,
|
|
793
|
+
title: optionalString,
|
|
794
|
+
url: optionalString
|
|
795
|
+
}), z.transform((link) => compact({
|
|
796
|
+
description: link.description,
|
|
797
|
+
title: link.title,
|
|
798
|
+
url: link.url ?? ""
|
|
799
|
+
})))])) });
|
|
800
|
+
const Monitor = looseObject({
|
|
801
|
+
createdAt: optionalString,
|
|
802
|
+
goal: optionalString,
|
|
803
|
+
id: withOriginal(optionalId),
|
|
804
|
+
schedule: looseObject({
|
|
805
|
+
cron: optionalString,
|
|
806
|
+
text: optionalString
|
|
807
|
+
}),
|
|
808
|
+
status: optionalString,
|
|
809
|
+
targets: arrayOf(looseObject({
|
|
810
|
+
queries: arrayOf(z.string()),
|
|
811
|
+
type: optionalString,
|
|
812
|
+
url: optionalString,
|
|
813
|
+
urls: arrayOf(z.string())
|
|
814
|
+
})),
|
|
815
|
+
webhook: looseObject({ url: optionalString })
|
|
816
|
+
});
|
|
817
|
+
/** A monitor beside the entry as it arrived. */
|
|
818
|
+
const MonitorEntry = withOriginal(Monitor);
|
|
819
|
+
/** The reply to creating or getting a monitor. */
|
|
820
|
+
const MonitorResponse = looseObject({ data: MonitorEntry });
|
|
821
|
+
/** One page of monitors. */
|
|
822
|
+
const MonitorsResponse = looseObject({ data: arrayOf(MonitorEntry) });
|
|
823
|
+
/** One page of a monitor's checks, each beside its entry as it arrived. */
|
|
824
|
+
const ChecksResponse = looseObject({ data: arrayOf(withOriginal(looseObject({
|
|
825
|
+
createdAt: optionalString,
|
|
826
|
+
error: optionalString,
|
|
827
|
+
finishedAt: optionalString,
|
|
828
|
+
id: optionalString,
|
|
829
|
+
scheduledFor: optionalString,
|
|
830
|
+
startedAt: optionalString,
|
|
831
|
+
status: optionalString,
|
|
832
|
+
summary: looseObject({
|
|
833
|
+
changed: optionalNumber,
|
|
834
|
+
error: optionalNumber,
|
|
835
|
+
new: optionalNumber,
|
|
836
|
+
removed: optionalNumber,
|
|
837
|
+
totalPages: optionalNumber
|
|
838
|
+
})
|
|
839
|
+
}))) });
|
|
840
|
+
/** `/parse`. */
|
|
841
|
+
const ParseResponse = looseObject({
|
|
842
|
+
data: looseObject({
|
|
843
|
+
blocks: optionalArrayOf(anything),
|
|
844
|
+
markdown: optionalString,
|
|
845
|
+
metadata: looseObject(metadataShape),
|
|
846
|
+
pages: optionalArrayOf(looseObject({
|
|
847
|
+
markdown: optionalString,
|
|
848
|
+
pageNumber: anything
|
|
849
|
+
})),
|
|
850
|
+
warning: Warning
|
|
851
|
+
}),
|
|
852
|
+
warning: Warning
|
|
853
|
+
});
|
|
854
|
+
/** `/team/credit-usage`. */
|
|
855
|
+
const UsageResponse = looseObject({ data: looseObject({
|
|
856
|
+
billingPeriodEnd: optionalString,
|
|
857
|
+
planCredits: optionalNumber,
|
|
858
|
+
remainingCredits: optionalNumber
|
|
859
|
+
}) });
|
|
622
860
|
// src/adapters/firecrawl.ts
|
|
623
861
|
const firecrawl = (config = {}) => {
|
|
624
862
|
const baseUrl = config.baseUrl ?? "https://api.firecrawl.dev/v2";
|
|
@@ -626,19 +864,22 @@ const firecrawl = (config = {}) => {
|
|
|
626
864
|
baseUrl,
|
|
627
865
|
fetch: config.fetch,
|
|
628
866
|
headers: { authorization: `Bearer ${requireKey(provider, config.apiKey, "FIRECRAWL_API_KEY")}` },
|
|
629
|
-
provider
|
|
867
|
+
provider,
|
|
868
|
+
retries: config.retries
|
|
630
869
|
});
|
|
631
870
|
const scrape = async (url, formats, settings, call) => {
|
|
632
|
-
const response =
|
|
871
|
+
const response = await raw.request("POST", "/scrape", {
|
|
633
872
|
...call,
|
|
634
873
|
body: {
|
|
635
874
|
formats,
|
|
636
875
|
url,
|
|
637
876
|
...pageBody(settings)
|
|
638
877
|
}
|
|
639
|
-
})
|
|
878
|
+
});
|
|
879
|
+
const body = z.parse(ScrapeResponse, response);
|
|
640
880
|
return {
|
|
641
|
-
|
|
881
|
+
body,
|
|
882
|
+
data: body.data,
|
|
642
883
|
response
|
|
643
884
|
};
|
|
644
885
|
};
|
|
@@ -649,18 +890,18 @@ const firecrawl = (config = {}) => {
|
|
|
649
890
|
};
|
|
650
891
|
const finished = async (kind, id, call, interval) => {
|
|
651
892
|
const path = `/${kind}/${segment(id)}`;
|
|
652
|
-
const get = async (to) => {
|
|
893
|
+
const get = async (schema, to) => {
|
|
653
894
|
try {
|
|
654
|
-
return
|
|
895
|
+
return z.parse(schema, await raw.request("GET", to, { signal: call.signal }));
|
|
655
896
|
} catch (error) {
|
|
656
897
|
throw withJob(error, id);
|
|
657
898
|
}
|
|
658
899
|
};
|
|
659
900
|
const first = await poll(provider, id, async () => {
|
|
660
|
-
const status =
|
|
661
|
-
const state =
|
|
901
|
+
const status = z.parse(Batch, await raw.request("GET", path, { signal: call.signal }));
|
|
902
|
+
const state = status.value.status;
|
|
662
903
|
if (state === "failed" || state === "cancelled") throw new FieldworkError("JobFailed", `firecrawl ${kind} ${id} ended ${state}`, {
|
|
663
|
-
cause: status,
|
|
904
|
+
cause: status.original,
|
|
664
905
|
provider
|
|
665
906
|
});
|
|
666
907
|
return state === "completed" ? status : void 0;
|
|
@@ -669,13 +910,13 @@ const firecrawl = (config = {}) => {
|
|
|
669
910
|
interval
|
|
670
911
|
});
|
|
671
912
|
const batches = [first];
|
|
672
|
-
let next =
|
|
673
|
-
while (next) {
|
|
674
|
-
const batch = await get(pathOf(next));
|
|
913
|
+
let { next } = first.value;
|
|
914
|
+
while (next !== void 0) {
|
|
915
|
+
const batch = await get(Batch, pathOf(next));
|
|
675
916
|
batches.push(batch);
|
|
676
|
-
next =
|
|
917
|
+
({next} = batch.value);
|
|
677
918
|
}
|
|
678
|
-
const errors = await get(`${path}/errors`);
|
|
919
|
+
const errors = await get(BatchErrors, `${path}/errors`);
|
|
679
920
|
return {
|
|
680
921
|
batches,
|
|
681
922
|
errors,
|
|
@@ -684,18 +925,19 @@ const firecrawl = (config = {}) => {
|
|
|
684
925
|
};
|
|
685
926
|
};
|
|
686
927
|
const openSession = async (o, call) => {
|
|
687
|
-
const
|
|
928
|
+
const session = z.parse(Session, await raw.request("POST", "/interact", {
|
|
688
929
|
body: sessionBody(o),
|
|
930
|
+
creates: true,
|
|
689
931
|
signal: call.signal
|
|
690
932
|
}));
|
|
691
933
|
return {
|
|
692
|
-
id:
|
|
693
|
-
|
|
934
|
+
id: requireJobId(provider, session.value.id),
|
|
935
|
+
session
|
|
694
936
|
};
|
|
695
937
|
};
|
|
696
938
|
const closeQuietly = async (id, call) => {
|
|
697
939
|
try {
|
|
698
|
-
return
|
|
940
|
+
return z.parse(Closed, await raw.request("DELETE", `/interact/${segment(id)}`, { signal: call.signal }));
|
|
699
941
|
} catch {
|
|
700
942
|
return null;
|
|
701
943
|
}
|
|
@@ -710,7 +952,10 @@ const firecrawl = (config = {}) => {
|
|
|
710
952
|
const keep = o.keepSession ?? !created;
|
|
711
953
|
const { id } = o.session === void 0 ? await openSession(o, call) : { id: o.session };
|
|
712
954
|
try {
|
|
713
|
-
const result =
|
|
955
|
+
const result = z.parse(Execution, await raw.request("POST", `/interact/${segment(id)}/execute`, {
|
|
956
|
+
...scriptRequest(code, o.language, call, seconds),
|
|
957
|
+
creates: true
|
|
958
|
+
}));
|
|
714
959
|
const closed = keep ? null : await closeQuietly(id, call);
|
|
715
960
|
return actResult(result, keep ? id : void 0, closed);
|
|
716
961
|
} catch (error) {
|
|
@@ -725,85 +970,86 @@ const firecrawl = (config = {}) => {
|
|
|
725
970
|
},
|
|
726
971
|
async open(options) {
|
|
727
972
|
const { call, rest: o } = callSettings(options);
|
|
728
|
-
const {
|
|
729
|
-
return browserSession(
|
|
973
|
+
const { session } = await openSession(o, call);
|
|
974
|
+
return browserSession(session);
|
|
730
975
|
}
|
|
731
976
|
},
|
|
732
977
|
async crawl(url, options) {
|
|
733
978
|
const { call, rest: o } = callSettings(options);
|
|
734
|
-
const id = o.resume ??
|
|
979
|
+
const id = o.resume ?? requireJobId("firecrawl", z.parse(CrawlStart, await raw.request("POST", "/crawl", {
|
|
980
|
+
creates: true,
|
|
735
981
|
...call,
|
|
736
982
|
body: crawlBody(url, o)
|
|
737
983
|
})).id);
|
|
738
984
|
const job = await finished("crawl", id, call, o.interval);
|
|
985
|
+
const { robotsBlocked } = job.errors.value;
|
|
739
986
|
return compact({
|
|
740
987
|
failed: job.failed,
|
|
741
988
|
id,
|
|
742
989
|
meta: meta({
|
|
743
|
-
credits: job.first.creditsUsed,
|
|
990
|
+
credits: job.first.value.creditsUsed,
|
|
744
991
|
requestId: id
|
|
745
992
|
}),
|
|
746
|
-
pages: job.batches.flatMap((batch) =>
|
|
993
|
+
pages: job.batches.flatMap((batch) => batch.value.data.map((item) => ({
|
|
994
|
+
...toPage(item.value, url),
|
|
995
|
+
raw: item.original
|
|
996
|
+
}))),
|
|
747
997
|
raw: {
|
|
748
|
-
batches: job.batches,
|
|
749
|
-
errors: job.errors
|
|
998
|
+
batches: job.batches.map((batch) => batch.original),
|
|
999
|
+
errors: job.errors.original
|
|
750
1000
|
},
|
|
751
|
-
robotsBlocked:
|
|
752
|
-
total:
|
|
1001
|
+
robotsBlocked: robotsBlocked.length > 0 ? robotsBlocked : void 0,
|
|
1002
|
+
total: job.first.value.total
|
|
753
1003
|
});
|
|
754
1004
|
},
|
|
755
1005
|
async extract(url, options) {
|
|
756
1006
|
const { call, rest: o } = callSettings(options);
|
|
757
1007
|
const { schema, prompt, ...page } = o;
|
|
758
|
-
const { response, data } = await scrape(url, [compact({
|
|
1008
|
+
const { body, response, data } = await scrape(url, [compact({
|
|
759
1009
|
prompt,
|
|
760
|
-
schema,
|
|
1010
|
+
schema: jsonSchemaOf(schema),
|
|
761
1011
|
type: "json"
|
|
762
1012
|
})], page, call);
|
|
763
1013
|
if (data.json === void 0) {
|
|
764
|
-
const why =
|
|
765
|
-
throw new FieldworkError("ProviderError", `firecrawl returned no JSON for ${url}${why ? `: ${why}`
|
|
1014
|
+
const why = data.warning.text;
|
|
1015
|
+
throw new FieldworkError("ProviderError", `firecrawl returned no JSON for ${url}${why === void 0 ? "" : `: ${why}`}`, {
|
|
766
1016
|
cause: response,
|
|
767
1017
|
provider
|
|
768
1018
|
});
|
|
769
1019
|
}
|
|
770
1020
|
return compact({
|
|
771
|
-
data: data.json,
|
|
772
|
-
meta: pageMeta(
|
|
1021
|
+
data: await checkOutput(schema, data.json, { provider }),
|
|
1022
|
+
meta: pageMeta(data, body.warning.notes),
|
|
773
1023
|
raw: response
|
|
774
1024
|
});
|
|
775
1025
|
},
|
|
776
1026
|
async images(query, options) {
|
|
777
1027
|
const { call, rest: o } = callSettings(options);
|
|
778
|
-
const response =
|
|
1028
|
+
const response = await raw.request("POST", "/search", {
|
|
779
1029
|
...call,
|
|
780
1030
|
body: imagesBody(query, o)
|
|
781
|
-
})
|
|
782
|
-
return
|
|
1031
|
+
});
|
|
1032
|
+
return {
|
|
1033
|
+
...imagesResult(z.parse(SearchResponse, response)),
|
|
1034
|
+
raw: response
|
|
1035
|
+
};
|
|
783
1036
|
},
|
|
784
1037
|
async map(url, options) {
|
|
785
1038
|
const { call, rest: o } = callSettings(options);
|
|
786
|
-
const response =
|
|
1039
|
+
const response = await raw.request("POST", "/map", {
|
|
787
1040
|
...call,
|
|
788
1041
|
body: mapBody(url, o)
|
|
789
|
-
})
|
|
1042
|
+
});
|
|
790
1043
|
return {
|
|
791
|
-
links:
|
|
792
|
-
if (typeof item === "string") return { url: item };
|
|
793
|
-
const link = record(item);
|
|
794
|
-
return compact({
|
|
795
|
-
description: text(link.description),
|
|
796
|
-
title: text(link.title),
|
|
797
|
-
url: text(link.url) ?? ""
|
|
798
|
-
});
|
|
799
|
-
}),
|
|
1044
|
+
links: z.parse(MapResponse, response).links,
|
|
800
1045
|
raw: response
|
|
801
1046
|
};
|
|
802
1047
|
},
|
|
803
1048
|
monitor: {
|
|
804
1049
|
async create(options) {
|
|
805
1050
|
const { call, rest: o } = callSettings(options);
|
|
806
|
-
const response =
|
|
1051
|
+
const response = z.parse(MonitorResponse, await raw.request("POST", "/monitor", {
|
|
1052
|
+
creates: true,
|
|
807
1053
|
...call,
|
|
808
1054
|
body: monitorBody(o)
|
|
809
1055
|
}));
|
|
@@ -817,33 +1063,35 @@ const firecrawl = (config = {}) => {
|
|
|
817
1063
|
const { call, rest: o } = callSettings(options);
|
|
818
1064
|
const offset = Number(o.cursor ?? 0);
|
|
819
1065
|
if (!Number.isInteger(offset) || offset < 0) throw invalid(`firecrawl events cursor "${o.cursor}" is not valid`);
|
|
820
|
-
const response =
|
|
1066
|
+
const response = await raw.request("GET", `/monitor/${segment(id)}/checks`, {
|
|
821
1067
|
...call,
|
|
822
1068
|
query: {
|
|
823
1069
|
limit: 100,
|
|
824
1070
|
offset
|
|
825
1071
|
}
|
|
826
|
-
})
|
|
827
|
-
return
|
|
1072
|
+
});
|
|
1073
|
+
return {
|
|
1074
|
+
...monitorEvents(z.parse(ChecksResponse, response).data, offset),
|
|
1075
|
+
raw: response
|
|
1076
|
+
};
|
|
828
1077
|
},
|
|
829
1078
|
async get(id, options) {
|
|
830
1079
|
const { call } = callSettings(options);
|
|
831
|
-
const response =
|
|
1080
|
+
const response = z.parse(MonitorResponse, await raw.request("GET", `/monitor/${segment(id)}`, call));
|
|
832
1081
|
return monitorInfo(response.data);
|
|
833
1082
|
},
|
|
834
1083
|
async list(options) {
|
|
835
1084
|
const { call } = callSettings(options);
|
|
836
1085
|
const monitors = [];
|
|
837
1086
|
for (;;) {
|
|
838
|
-
const
|
|
1087
|
+
const page = z.parse(MonitorsResponse, await raw.request("GET", "/monitor", {
|
|
839
1088
|
...call,
|
|
840
1089
|
query: {
|
|
841
1090
|
limit: 100,
|
|
842
1091
|
offset: monitors.length
|
|
843
1092
|
}
|
|
844
|
-
}));
|
|
845
|
-
|
|
846
|
-
monitors.push(...page.map((item) => monitorInfo(item)));
|
|
1093
|
+
})).data;
|
|
1094
|
+
monitors.push(...page.map((entry) => monitorInfo(entry)));
|
|
847
1095
|
if (page.length < 100) return monitors;
|
|
848
1096
|
}
|
|
849
1097
|
}
|
|
@@ -851,26 +1099,44 @@ const firecrawl = (config = {}) => {
|
|
|
851
1099
|
async parse(document, options) {
|
|
852
1100
|
const { call, rest: o } = callSettings(options);
|
|
853
1101
|
const form = parseForm(document, o);
|
|
854
|
-
const response =
|
|
1102
|
+
const response = await raw.request("POST", "/parse", {
|
|
855
1103
|
...call,
|
|
856
1104
|
form
|
|
857
|
-
})
|
|
858
|
-
return
|
|
1105
|
+
});
|
|
1106
|
+
return {
|
|
1107
|
+
...parseResult(z.parse(ParseResponse, response)),
|
|
1108
|
+
raw: response
|
|
1109
|
+
};
|
|
859
1110
|
},
|
|
860
1111
|
async product(url, options) {
|
|
861
1112
|
const { call, rest: o } = callSettings(options);
|
|
862
|
-
const {
|
|
863
|
-
|
|
1113
|
+
const { body, response } = await scrape(url, ["product"], o, call);
|
|
1114
|
+
const product = toProduct(body);
|
|
1115
|
+
if (product === void 0) {
|
|
1116
|
+
const why = noProductReason(body);
|
|
1117
|
+
throw new FieldworkError("NotFound", `firecrawl found no product on ${url}${why === void 0 ? "" : `: ${why}`}`, {
|
|
1118
|
+
cause: response,
|
|
1119
|
+
provider
|
|
1120
|
+
});
|
|
1121
|
+
}
|
|
1122
|
+
return {
|
|
1123
|
+
...product,
|
|
1124
|
+
raw: response
|
|
1125
|
+
};
|
|
864
1126
|
},
|
|
865
1127
|
async read(url, options) {
|
|
866
1128
|
const { call, rest: o } = callSettings(options);
|
|
867
|
-
const {
|
|
868
|
-
return presentPage(provider,
|
|
1129
|
+
const { body, data, response } = await scrape(url, readFormats(o), o, call);
|
|
1130
|
+
return presentPage(provider, {
|
|
1131
|
+
...toPage(data, url, body.warning.notes),
|
|
1132
|
+
raw: response
|
|
1133
|
+
});
|
|
869
1134
|
},
|
|
870
1135
|
async readMany(urls, options) {
|
|
871
1136
|
const { call, rest: o } = callSettings(options);
|
|
872
1137
|
const { interval, resume, maxConcurrency, ignoreInvalidURLs, ...read } = o;
|
|
873
|
-
const started = resume === void 0 ?
|
|
1138
|
+
const started = z.parse(RunStart, resume === void 0 ? await raw.request("POST", "/batch/scrape", {
|
|
1139
|
+
creates: true,
|
|
874
1140
|
...call,
|
|
875
1141
|
body: compact({
|
|
876
1142
|
urls,
|
|
@@ -878,14 +1144,17 @@ const firecrawl = (config = {}) => {
|
|
|
878
1144
|
maxConcurrency,
|
|
879
1145
|
ignoreInvalidURLs
|
|
880
1146
|
})
|
|
881
|
-
})
|
|
882
|
-
const id = resume ??
|
|
1147
|
+
}) : {});
|
|
1148
|
+
const id = resume ?? requireJobId("firecrawl", started.value.id);
|
|
883
1149
|
const job = await finished("batch/scrape", id, call, interval);
|
|
884
|
-
const rejected =
|
|
1150
|
+
const rejected = started.value.invalidURLs.map((url) => ({
|
|
885
1151
|
error: "invalid URL",
|
|
886
1152
|
url
|
|
887
1153
|
}));
|
|
888
|
-
const { pages, gone } = presentPages(job.batches.flatMap((batch) =>
|
|
1154
|
+
const { pages, gone } = presentPages(job.batches.flatMap((batch) => batch.value.data.map((item) => ({
|
|
1155
|
+
...toPage(item.value, ""),
|
|
1156
|
+
raw: item.original
|
|
1157
|
+
}))));
|
|
889
1158
|
return compact({
|
|
890
1159
|
failed: [
|
|
891
1160
|
...job.failed,
|
|
@@ -894,41 +1163,56 @@ const firecrawl = (config = {}) => {
|
|
|
894
1163
|
],
|
|
895
1164
|
id,
|
|
896
1165
|
meta: meta({
|
|
897
|
-
credits: job.first.creditsUsed,
|
|
1166
|
+
credits: job.first.value.creditsUsed,
|
|
898
1167
|
requestId: id
|
|
899
1168
|
}),
|
|
900
1169
|
pages,
|
|
901
1170
|
raw: {
|
|
902
|
-
batches: job.batches,
|
|
903
|
-
errors: job.errors,
|
|
904
|
-
started
|
|
1171
|
+
batches: job.batches.map((batch) => batch.original),
|
|
1172
|
+
errors: job.errors.original,
|
|
1173
|
+
started: started.original
|
|
905
1174
|
}
|
|
906
1175
|
});
|
|
907
1176
|
},
|
|
908
1177
|
async research(question, options) {
|
|
909
1178
|
const { call, rest: o } = callSettings(options);
|
|
910
|
-
const started = o.resume === void 0 ?
|
|
1179
|
+
const started = z.parse(RunStart, o.resume === void 0 ? await raw.request("POST", "/agent", {
|
|
1180
|
+
creates: true,
|
|
911
1181
|
...call,
|
|
912
1182
|
body: researchBody(question, o)
|
|
913
|
-
})
|
|
914
|
-
const id = o.resume ??
|
|
915
|
-
const run = await poll(provider, id, async () => researchState(id,
|
|
1183
|
+
}) : {});
|
|
1184
|
+
const id = o.resume ?? requireJobId("firecrawl", started.value.id);
|
|
1185
|
+
const run = await poll(provider, id, async () => researchState(id, z.parse(AgentRun, await raw.request("GET", `/agent/${segment(id)}`, { signal: call.signal }))), {
|
|
916
1186
|
...call,
|
|
917
1187
|
interval: o.interval
|
|
918
1188
|
});
|
|
919
|
-
|
|
1189
|
+
const result = researchResult(id, started, run);
|
|
1190
|
+
return {
|
|
1191
|
+
...result,
|
|
1192
|
+
output: await checkOutput(o.schema, result.output, {
|
|
1193
|
+
jobId: id,
|
|
1194
|
+
provider
|
|
1195
|
+
})
|
|
1196
|
+
};
|
|
920
1197
|
},
|
|
921
1198
|
async search(query, options) {
|
|
922
1199
|
const { call, rest: o } = callSettings(options);
|
|
923
|
-
const response =
|
|
1200
|
+
const response = await raw.request("POST", "/search", {
|
|
924
1201
|
...call,
|
|
925
1202
|
body: searchBody(query, o)
|
|
926
|
-
})
|
|
927
|
-
return
|
|
1203
|
+
});
|
|
1204
|
+
return {
|
|
1205
|
+
...searchResult(z.parse(SearchResponse, response)),
|
|
1206
|
+
raw: response
|
|
1207
|
+
};
|
|
928
1208
|
},
|
|
929
1209
|
async usage(options) {
|
|
930
1210
|
const { call } = callSettings(options);
|
|
931
|
-
|
|
1211
|
+
const response = await raw.request("GET", "/team/credit-usage", call);
|
|
1212
|
+
return {
|
|
1213
|
+
...usageResult(z.parse(UsageResponse, response)),
|
|
1214
|
+
raw: response
|
|
1215
|
+
};
|
|
932
1216
|
}
|
|
933
1217
|
},
|
|
934
1218
|
raw
|