@howells/fieldwork-sdk 0.5.1 → 0.6.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 +25 -24
- package/dist/{adapter-BgdfLBs-.d.ts → adapter-Bh8EIrNe.d.ts} +20 -6
- package/dist/brave.d.ts +22 -4
- package/dist/brave.js +71 -2
- package/dist/browserbase.d.ts +29 -4
- package/dist/browserbase.js +9 -4
- package/dist/{document-Dpj01mGx.js → document-Clmi51Sf.js} +5 -2
- package/dist/{errors-Yvk42oZH.js → errors-DROZyb9T.js} +13 -0
- package/dist/exa.d.ts +49 -7
- package/dist/exa.js +80 -13
- package/dist/{fieldwork-CXNIcqSN.d.ts → fieldwork-BaWqUNI3.d.ts} +20 -4
- package/dist/firecrawl.d.ts +64 -4
- package/dist/firecrawl.js +181 -54
- package/dist/index.d.ts +3 -3
- package/dist/index.js +26 -2
- package/dist/job-CWHOfhP_.js +102 -0
- package/dist/kernel.d.ts +99 -0
- package/dist/kernel.js +313 -0
- package/dist/llamaparse.d.ts +7 -2
- package/dist/llamaparse.js +23 -12
- package/dist/parallel.d.ts +83 -7
- package/dist/parallel.js +186 -26
- package/dist/{parse-n8MmaK1x.js → parse-COHKvfH9.js} +115 -17
- package/dist/perplexity.d.ts +37 -5
- package/dist/perplexity.js +146 -36
- package/dist/reducto.d.ts +16 -2
- package/dist/reducto.js +28 -15
- package/dist/{schema-Cupy7-7q.d.ts → schema-BWWiMvkg.d.ts} +1 -1
- package/dist/{schema-DbSIABP0.js → schema-BYcXgfuZ.js} +8 -4
- package/dist/serpapi.d.ts +25 -5
- package/dist/serpapi.js +99 -2
- package/dist/tavily.d.ts +44 -4
- package/dist/tavily.js +45 -13
- package/dist/tools.d.ts +16 -18
- package/dist/tools.js +150 -16
- package/package.json +9 -2
- package/dist/job-BGTwH3F-.js +0 -41
package/dist/firecrawl.js
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import { t as defineAdapter } from "./adapter-DWYJys20.js";
|
|
2
|
-
import { r as invalidRequest, t as FieldworkError } from "./errors-
|
|
3
|
-
import { B as requireJobId, C as createRawClient, E as segment, I as presentPage, L as presentPages, M as compact, P as meta, 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, k as callSettings, l as optionalBoolean, m as optionalScalar, n as anything, p as optionalObject, r as arrayOf, s as optionalAnyString, u as optionalFirstString, v as recordOf, z as refuseTogether } from "./parse-
|
|
4
|
-
import {
|
|
5
|
-
import { n as jsonSchemaOf, t as checkOutput } from "./schema-
|
|
6
|
-
import { a as refuseLarger, i as mediaTypeOf, n as documentPart, t as MEDIA_TYPES } from "./document-
|
|
2
|
+
import { r as invalidRequest, t as FieldworkError } from "./errors-DROZyb9T.js";
|
|
3
|
+
import { B as requireJobId, C as createRawClient, E as segment, I as presentPage, L as presentPages, M as compact, P as meta, 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, k as callSettings, l as optionalBoolean, m as optionalScalar, n as anything, p as optionalObject, r as arrayOf, s as optionalAnyString, u as optionalFirstString, v as recordOf, z as refuseTogether } from "./parse-COHKvfH9.js";
|
|
4
|
+
import { i as startJob, n as requireOutput, r as runJob, t as jobState } from "./job-CWHOfhP_.js";
|
|
5
|
+
import { n as jsonSchemaOf, t as checkOutput } from "./schema-BYcXgfuZ.js";
|
|
6
|
+
import { a as refuseLarger, i as mediaTypeOf, n as documentPart, t as MEDIA_TYPES } from "./document-Clmi51Sf.js";
|
|
7
7
|
import * as z from "zod/mini";
|
|
8
8
|
// src/adapters/firecrawl/shared.ts
|
|
9
9
|
const provider = "firecrawl";
|
|
10
|
+
/** A country code in upper case, as sent to Firecrawl. */
|
|
10
11
|
const country = (code) => code?.toUpperCase();
|
|
11
12
|
// src/adapters/firecrawl/schedule.ts
|
|
12
13
|
/** The fewest minutes Firecrawl allows between two checks of a monitor. */
|
|
@@ -16,6 +17,7 @@ const NAMED_CRON = /* @__PURE__ */ new Map([
|
|
|
16
17
|
["day", "0 0 * * *"],
|
|
17
18
|
["week", "0 0 * * 0"]
|
|
18
19
|
]);
|
|
20
|
+
/** The day counts that have a cron: every day, and every seven days (Sunday). */
|
|
19
21
|
const DAILY_CRON = /* @__PURE__ */ new Map([[1, "0 0 * * *"], [7, "0 0 * * 0"]]);
|
|
20
22
|
const CRON_PART = /^(?:\*|(?<from>\d+)(?:-(?<to>\d+))?)(?:\/(?<step>\d+))?$/u;
|
|
21
23
|
const INTERVAL = /^(?<count>\d+)(?<unit>[hd])$/u;
|
|
@@ -23,6 +25,7 @@ const rangeEnd = (groups, wildcard, from, max) => {
|
|
|
23
25
|
if (wildcard || groups.to === void 0 && groups.step !== void 0) return max;
|
|
24
26
|
return groups.to === void 0 ? from : Number(groups.to);
|
|
25
27
|
};
|
|
28
|
+
/** The sorted values a minute or hour field matches (lists, ranges and steps), or undefined for a field it cannot read, such as one with names. */
|
|
26
29
|
const cronValues = (field, max) => {
|
|
27
30
|
const values = /* @__PURE__ */ new Set();
|
|
28
31
|
for (const part of field.split(",")) {
|
|
@@ -37,6 +40,7 @@ const cronValues = (field, max) => {
|
|
|
37
40
|
}
|
|
38
41
|
return [...values].toSorted((a, b) => a - b);
|
|
39
42
|
};
|
|
43
|
+
/** The minutes between runs within an hour, and across the hour boundary when two consecutive hours both run. */
|
|
40
44
|
const runGaps = (minutes, hours) => {
|
|
41
45
|
const gaps = minutes.slice(1).map((minute, index) => minute - (minutes[index] ?? 0));
|
|
42
46
|
const [first] = minutes;
|
|
@@ -44,6 +48,11 @@ const runGaps = (minutes, hours) => {
|
|
|
44
48
|
if (hours?.some((hour) => hours.includes((hour + 1) % 24)) === true && first !== void 0 && last !== void 0) gaps.push(60 - last + first);
|
|
45
49
|
return gaps;
|
|
46
50
|
};
|
|
51
|
+
/**
|
|
52
|
+
* Refuses an expression that is not five fields, or that can run less than
|
|
53
|
+
* `MIN_MINUTES` apart. A minute or hour field `cronValues` cannot read is not
|
|
54
|
+
* checked.
|
|
55
|
+
*/
|
|
47
56
|
const checkCron = (cron) => {
|
|
48
57
|
const fields = cron.trim().split(/\s+/u);
|
|
49
58
|
if (fields.length !== 5) throw invalidRequest(provider, `needs a five-field cron expression, got "${cron}"`);
|
|
@@ -53,11 +62,18 @@ const checkCron = (cron) => {
|
|
|
53
62
|
if (minutes && runGaps(minutes, hours).some((gap) => gap < MIN_MINUTES)) throw invalidRequest(provider, `monitors run at most every ${MIN_MINUTES} minutes, got "${cron}"`);
|
|
54
63
|
return cron.trim();
|
|
55
64
|
};
|
|
65
|
+
/** The cron for every `count` hours. Only counts that divide 24 have one. */
|
|
56
66
|
const hourlyCron = (count) => {
|
|
57
67
|
if (!Number.isInteger(count) || count < 1 || 24 % count !== 0) return;
|
|
58
68
|
if (count === 1) return "0 * * * *";
|
|
59
69
|
return count === 24 ? "0 0 * * *" : `0 */${count} * * *`;
|
|
60
70
|
};
|
|
71
|
+
/**
|
|
72
|
+
* The cron expression for a schedule. A cron is checked and passed through. A
|
|
73
|
+
* named interval becomes a cron: `hour` (on the hour), `day`, `1d` (midnight),
|
|
74
|
+
* `week`, `7d` (midnight on Sunday), or `Nh` for an N that divides 24. Throws
|
|
75
|
+
* `InvalidRequest` for any other interval.
|
|
76
|
+
*/
|
|
61
77
|
const cronFor = (schedule) => {
|
|
62
78
|
if ("cron" in schedule) return checkCron(schedule.cron);
|
|
63
79
|
const every = schedule.every;
|
|
@@ -80,6 +96,7 @@ const MAX_PARSE_MS = 3e5;
|
|
|
80
96
|
const REPORT_GRACE_MS = 1e4;
|
|
81
97
|
/** The longest query a search monitor takes. */
|
|
82
98
|
const MAX_MONITOR_QUERY = 256;
|
|
99
|
+
/** Firecrawl's `qdr:` units, for each named recency window. */
|
|
83
100
|
const RECENCY = {
|
|
84
101
|
day: "d",
|
|
85
102
|
hour: "h",
|
|
@@ -88,6 +105,7 @@ const RECENCY = {
|
|
|
88
105
|
year: "y"
|
|
89
106
|
};
|
|
90
107
|
const DATE = /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/u;
|
|
108
|
+
/** The page-fetching fields every scrape takes. `maxAge` goes out in milliseconds, and the rest as they are. */
|
|
91
109
|
const pageBody = (o) => compact({
|
|
92
110
|
actions: o.actions,
|
|
93
111
|
excludeTags: o.excludeTags,
|
|
@@ -100,6 +118,7 @@ const pageBody = (o) => compact({
|
|
|
100
118
|
proxy: o.proxy,
|
|
101
119
|
waitFor: o.waitFor
|
|
102
120
|
});
|
|
121
|
+
/** The formats a read asks for: Markdown always, then `include`, then `query` as highlights (the default) or a question. */
|
|
103
122
|
const readFormats = (o) => {
|
|
104
123
|
const query = o.query === void 0 ? [] : [o.queryFormat === "question" ? {
|
|
105
124
|
question: o.query,
|
|
@@ -114,15 +133,22 @@ const readFormats = (o) => {
|
|
|
114
133
|
...query
|
|
115
134
|
];
|
|
116
135
|
};
|
|
136
|
+
/** The scrape body for a read: its formats and page settings. */
|
|
117
137
|
const readBody = (o) => ({
|
|
118
138
|
formats: readFormats(o),
|
|
119
139
|
...pageBody(o)
|
|
120
140
|
});
|
|
141
|
+
/** Firecrawl's date filter takes MM/DD/YYYY; the options take YYYY-MM-DD. */
|
|
121
142
|
const usDate = (value) => {
|
|
122
143
|
const groups = DATE.exec(value)?.groups;
|
|
123
144
|
if (!groups) throw invalidRequest(provider, `needs dates as YYYY-MM-DD, got "${value}"`);
|
|
124
145
|
return `${groups.month}/${groups.day}/${groups.year}`;
|
|
125
146
|
};
|
|
147
|
+
/**
|
|
148
|
+
* The `tbs` time filter: `tbs` as given, else `recency` as `qdr:`, else the
|
|
149
|
+
* published dates as a `cdr:1` range with `cd_min` and `cd_max`. Refuses
|
|
150
|
+
* `tbs`, `recency` and the dates in combination.
|
|
151
|
+
*/
|
|
126
152
|
const timeFilter = (o) => {
|
|
127
153
|
refuseTogether(provider, o, "tbs", "recency", "publishedAfter");
|
|
128
154
|
refuseTogether(provider, o, "tbs", "recency", "publishedBefore");
|
|
@@ -135,6 +161,7 @@ const timeFilter = (o) => {
|
|
|
135
161
|
o.publishedBefore === void 0 ? void 0 : `cd_max:${usDate(o.publishedBefore)}`
|
|
136
162
|
].filter((part) => part !== void 0).join(",");
|
|
137
163
|
};
|
|
164
|
+
/** The `/search` body. `content` asks for each result's Markdown. Refuses `includeDomains` with `excludeDomains`, and `gov` with another category. */
|
|
138
165
|
const searchBody = (query, o) => {
|
|
139
166
|
refuseTogether(provider, o, "includeDomains", "excludeDomains");
|
|
140
167
|
if (o.categories?.includes("gov") === true && o.categories.length > 1) throw invalidRequest(provider, "searches the gov category on its own; do not combine it with another category");
|
|
@@ -153,6 +180,7 @@ const searchBody = (query, o) => {
|
|
|
153
180
|
tbs: timeFilter(o)
|
|
154
181
|
});
|
|
155
182
|
};
|
|
183
|
+
/** The `/search` body for images: the `images` source alone. */
|
|
156
184
|
const imagesBody = (query, o) => compact({
|
|
157
185
|
country: country(o.country),
|
|
158
186
|
limit: o.limit,
|
|
@@ -171,6 +199,7 @@ const mapBody = (url, o) => compact({
|
|
|
171
199
|
sitemap: o.sitemap,
|
|
172
200
|
url
|
|
173
201
|
});
|
|
202
|
+
/** The `/crawl` body. `scrapeOptions` is built like a read's body. */
|
|
174
203
|
const crawlBody = (url, o) => compact({
|
|
175
204
|
allowExternalLinks: o.allowExternalLinks,
|
|
176
205
|
allowSubdomains: o.allowSubdomains,
|
|
@@ -188,6 +217,7 @@ const crawlBody = (url, o) => compact({
|
|
|
188
217
|
sitemap: o.sitemap,
|
|
189
218
|
url
|
|
190
219
|
});
|
|
220
|
+
/** The `/agent` body. `continueFrom` is sent as `threadId`, and `country` as `location`. */
|
|
191
221
|
const researchBody = (question, o) => compact({
|
|
192
222
|
effort: o.effort,
|
|
193
223
|
location: o.country === void 0 || o.country === "" ? void 0 : { country: country(o.country) },
|
|
@@ -199,12 +229,18 @@ const researchBody = (question, o) => compact({
|
|
|
199
229
|
threadId: o.continueFrom,
|
|
200
230
|
urls: o.urls
|
|
201
231
|
});
|
|
232
|
+
/** The body that opens a browser session. `activityTtl` falls back to `ttl`. */
|
|
202
233
|
const sessionBody = (o) => compact({
|
|
203
234
|
activityTtl: o.activityTtl ?? o.ttl,
|
|
204
235
|
location: o.country === void 0 || o.country === "" ? void 0 : { country: country(o.country) },
|
|
205
236
|
profile: o.profile,
|
|
206
237
|
ttl: o.ttl
|
|
207
238
|
});
|
|
239
|
+
/**
|
|
240
|
+
* Refuses session settings given together with `session`, since that session
|
|
241
|
+
* is already open. Returns the call's `timeout` as whole seconds for the
|
|
242
|
+
* script's limit (at least 1), and refuses one over `MAX_SCRIPT_SECONDS`.
|
|
243
|
+
*/
|
|
208
244
|
const checkAct = (o, timeout) => {
|
|
209
245
|
for (const name of [
|
|
210
246
|
"ttl",
|
|
@@ -217,6 +253,11 @@ const checkAct = (o, timeout) => {
|
|
|
217
253
|
if (seconds > MAX_SCRIPT_SECONDS) throw invalidRequest(provider, `runs a script for at most ${MAX_SCRIPT_SECONDS} seconds`);
|
|
218
254
|
return seconds;
|
|
219
255
|
};
|
|
256
|
+
/**
|
|
257
|
+
* The request that runs a script. The request waits `REPORT_GRACE_MS` longer
|
|
258
|
+
* than the script's own limit, so Firecrawl reports a timeout before the client
|
|
259
|
+
* gives up.
|
|
260
|
+
*/
|
|
220
261
|
const scriptRequest = (code, language, call, seconds) => ({
|
|
221
262
|
body: compact({
|
|
222
263
|
code,
|
|
@@ -227,6 +268,10 @@ const scriptRequest = (code, language, call, seconds) => ({
|
|
|
227
268
|
signal: call.signal,
|
|
228
269
|
timeout: call.timeout === void 0 ? void 0 : call.timeout + REPORT_GRACE_MS
|
|
229
270
|
});
|
|
271
|
+
/**
|
|
272
|
+
* The multipart body of a `/parse` call. Refuses a file type it does not know,
|
|
273
|
+
* a file over `MAX_PARSE_MB` and a `timeout` over `MAX_PARSE_MS`.
|
|
274
|
+
*/
|
|
230
275
|
const parseForm = (document, o, timeout) => {
|
|
231
276
|
if (timeout !== void 0 && timeout > MAX_PARSE_MS) throw invalidRequest(provider, `parses for at most ${MAX_PARSE_MS / 1e3} seconds`);
|
|
232
277
|
if (mediaTypeOf(document.name) === void 0) throw invalidRequest(provider, `parses ${[...MEDIA_TYPES.keys()].join(", ")} files, not "${document.name}"`);
|
|
@@ -248,6 +293,11 @@ const parseForm = (document, o, timeout) => {
|
|
|
248
293
|
form.set("file", documentPart(document), document.name);
|
|
249
294
|
return form;
|
|
250
295
|
};
|
|
296
|
+
/**
|
|
297
|
+
* A monitor's target: a scrape of `urls`, or a search for `query`. Refuses
|
|
298
|
+
* search-only options with `urls`, no `urls` and no `query`, and a search query
|
|
299
|
+
* over `MAX_MONITOR_QUERY` characters.
|
|
300
|
+
*/
|
|
251
301
|
const monitorTarget = (o) => {
|
|
252
302
|
const searchOnly = [
|
|
253
303
|
o.searchWindow,
|
|
@@ -273,6 +323,7 @@ const monitorTarget = (o) => {
|
|
|
273
323
|
type: "search"
|
|
274
324
|
});
|
|
275
325
|
};
|
|
326
|
+
/** The `/monitor` body. `query` is also the monitor's `goal`, and the name defaults to the query or first URL, cut to 256 characters. */
|
|
276
327
|
const monitorBody = (o) => {
|
|
277
328
|
const target = monitorTarget(o);
|
|
278
329
|
return compact({
|
|
@@ -298,11 +349,14 @@ const PAPER_URLS = /* @__PURE__ */ new Map([
|
|
|
298
349
|
const LANGUAGE = /^(?<code>[a-z]{2})(?:[-_]|$)/u;
|
|
299
350
|
/** The list, or undefined when it is empty. */
|
|
300
351
|
const some = (items) => items.length > 0 ? [...items] : void 0;
|
|
352
|
+
/** The two-letter code of a locale such as `en-GB` or `en_GB`. */
|
|
301
353
|
const languageCode = (value) => LANGUAGE.exec(value?.toLowerCase() ?? "")?.groups?.code;
|
|
354
|
+
/** The passages for a page: the `highlights` text, else the highlight list, else the written `answer` of a `question` query. */
|
|
302
355
|
const excerptsOf = (data) => {
|
|
303
356
|
const { list, text } = data.highlights;
|
|
304
357
|
return (text === void 0 ? some(list) : [text]) ?? (data.answer === void 0 ? void 0 : [data.answer]);
|
|
305
358
|
};
|
|
359
|
+
/** The credits and scrape id of a page, with its warnings and those of the whole response. */
|
|
306
360
|
const pageMeta = (data, topNotes) => meta({
|
|
307
361
|
credits: data.metadata.creditsUsed,
|
|
308
362
|
requestId: data.metadata.scrapeId,
|
|
@@ -332,6 +386,7 @@ const toPage = (data, fallbackUrl, topNotes = []) => {
|
|
|
332
386
|
url: metadata.url ?? metadata.sourceURL ?? fallbackUrl
|
|
333
387
|
});
|
|
334
388
|
};
|
|
389
|
+
/** A price; undefined when Firecrawl gave none of its fields. */
|
|
335
390
|
const price = (item) => {
|
|
336
391
|
const result = compact({
|
|
337
392
|
amount: item.amount,
|
|
@@ -340,6 +395,7 @@ const price = (item) => {
|
|
|
340
395
|
});
|
|
341
396
|
return Object.keys(result).length > 0 ? result : void 0;
|
|
342
397
|
};
|
|
398
|
+
/** The first non-empty GTIN, from `gtin` then the 14, 13, 12 and 8 digit forms. */
|
|
343
399
|
const gtin = (variant) => [
|
|
344
400
|
variant.gtin,
|
|
345
401
|
variant.gtin14,
|
|
@@ -363,6 +419,7 @@ const toVariant = (variant) => {
|
|
|
363
419
|
values: Object.keys(values).length > 0 ? values : void 0
|
|
364
420
|
});
|
|
365
421
|
};
|
|
422
|
+
/** The variants' images without repeats, by URL. Used when the product lists none of its own. */
|
|
366
423
|
const allImages = (variants) => {
|
|
367
424
|
const seen = /* @__PURE__ */ new Map();
|
|
368
425
|
for (const image of variants.flatMap((variant) => variant.images ?? [])) if (!seen.has(image.url)) seen.set(image.url, image);
|
|
@@ -386,6 +443,7 @@ const toProduct = (body) => {
|
|
|
386
443
|
};
|
|
387
444
|
/** Why a page has no product: the warning it carries, if any. */
|
|
388
445
|
const noProductReason = (body) => body.data.warning.text ?? body.warning.text;
|
|
446
|
+
/** A web or news result. `kind` is the result's own category, else its source; `snippet` is its description, else its snippet. */
|
|
389
447
|
const searchItem = (result, kind) => compact({
|
|
390
448
|
content: result.markdown,
|
|
391
449
|
image: result.imageUrl,
|
|
@@ -395,6 +453,11 @@ const searchItem = (result, kind) => compact({
|
|
|
395
453
|
title: result.title,
|
|
396
454
|
url: result.url ?? ""
|
|
397
455
|
});
|
|
456
|
+
/**
|
|
457
|
+
* A research result. Papers carry ids rather than URLs: a `web:` id holds the
|
|
458
|
+
* URL itself, and an `arxiv`, `pmid`, `pmcid` or `doi` id resolves through
|
|
459
|
+
* `PAPER_URLS`. Any other id is used as it is.
|
|
460
|
+
*/
|
|
398
461
|
const paperItem = (paper) => {
|
|
399
462
|
const paperId = paper.paperId ?? "";
|
|
400
463
|
const primary = paper.primaryId ?? paperId;
|
|
@@ -408,6 +471,7 @@ const paperItem = (paper) => {
|
|
|
408
471
|
url: paperId.startsWith("web:") ? paperId.slice(4) : resolve?.(primary.slice(colon + 1)) ?? primary
|
|
409
472
|
});
|
|
410
473
|
};
|
|
474
|
+
/** Image results. `sourceUrl` is the page the image is on; an item without an image URL is dropped. */
|
|
411
475
|
const imageItems = (found) => found.flatMap((image) => {
|
|
412
476
|
const { imageUrl: url } = image;
|
|
413
477
|
return url === void 0 ? [] : [compact({
|
|
@@ -418,12 +482,13 @@ const imageItems = (found) => found.flatMap((image) => {
|
|
|
418
482
|
width: image.imageWidth
|
|
419
483
|
})];
|
|
420
484
|
});
|
|
485
|
+
/** The credits, request id and warnings of a search. */
|
|
421
486
|
const searchMeta = (body) => meta({
|
|
422
487
|
credits: body.creditsUsed,
|
|
423
488
|
requestId: body.id,
|
|
424
489
|
warnings: [...body.warning, ...body.warnings]
|
|
425
490
|
});
|
|
426
|
-
/** The results of a search; the caller adds `raw`. */
|
|
491
|
+
/** The results of a search, web then news then research; the caller adds `raw`. Images are kept apart in `images`. */
|
|
427
492
|
const searchResult = (body) => {
|
|
428
493
|
const { data } = body;
|
|
429
494
|
return compact({
|
|
@@ -436,25 +501,65 @@ const searchResult = (body) => {
|
|
|
436
501
|
]
|
|
437
502
|
});
|
|
438
503
|
};
|
|
504
|
+
/** The image results of a search for images; the caller adds `raw`. */
|
|
439
505
|
const imagesResult = (body) => compact({
|
|
440
506
|
meta: searchMeta(body),
|
|
441
507
|
results: imageItems(body.data.images ?? [])
|
|
442
508
|
});
|
|
509
|
+
/** The pages a crawl or batch could not read. */
|
|
443
510
|
const failedPages = (errors) => errors.value.errors.map((entry) => ({
|
|
444
511
|
error: entry.error ?? "unknown error",
|
|
445
512
|
url: entry.url ?? ""
|
|
446
513
|
}));
|
|
514
|
+
const BATCH_STATES = {
|
|
515
|
+
done: ["completed"],
|
|
516
|
+
failed: ["failed", "cancelled"],
|
|
517
|
+
missingIsRunning: true,
|
|
518
|
+
running: ["scraping"]
|
|
519
|
+
};
|
|
520
|
+
const AGENT_STATES = {
|
|
521
|
+
done: ["completed"],
|
|
522
|
+
failed: ["failed", "cancelled"],
|
|
523
|
+
missingIsRunning: true,
|
|
524
|
+
running: ["processing"]
|
|
525
|
+
};
|
|
526
|
+
/** A crawl or batch scrape when it has finished, undefined while it runs; throws `JobFailed` when it failed or was cancelled. */
|
|
527
|
+
const batchState = (kind, id, entry) => {
|
|
528
|
+
const { status } = entry.value;
|
|
529
|
+
const state = jobState(provider, id, BATCH_STATES, {
|
|
530
|
+
original: entry.original,
|
|
531
|
+
value: status
|
|
532
|
+
});
|
|
533
|
+
if (state === "failed") throw new FieldworkError("JobFailed", `firecrawl ${kind} ${id} ended ${status}`, {
|
|
534
|
+
cause: entry.original,
|
|
535
|
+
provider
|
|
536
|
+
});
|
|
537
|
+
return state === "done" ? entry : void 0;
|
|
538
|
+
};
|
|
539
|
+
/**
|
|
540
|
+
* The run when it has finished, undefined while it runs. A `failed` run that
|
|
541
|
+
* left partial output counts as finished; any other `failed` or `cancelled`
|
|
542
|
+
* run throws `JobFailed`.
|
|
543
|
+
*/
|
|
447
544
|
const researchState = (id, entry) => {
|
|
448
545
|
const status = entry.value;
|
|
449
|
-
const state =
|
|
546
|
+
const state = jobState(provider, id, AGENT_STATES, {
|
|
547
|
+
original: entry.original,
|
|
548
|
+
value: status.status
|
|
549
|
+
});
|
|
450
550
|
const hasPartial = status.partial !== void 0 && status.partial !== null;
|
|
451
|
-
|
|
452
|
-
if (!done && (state === "failed" || state === "cancelled")) throw new FieldworkError("JobFailed", `firecrawl research run ${id} ${state}: ${status.error ?? status.stopReason ?? "no reason given"}`, {
|
|
551
|
+
if (state === "failed" && !(status.status === "failed" && hasPartial)) throw new FieldworkError("JobFailed", `firecrawl research run ${id} ${status.status}: ${status.error ?? status.stopReason ?? "no reason given"}`, {
|
|
453
552
|
cause: entry.original,
|
|
454
553
|
provider
|
|
455
554
|
});
|
|
456
|
-
return
|
|
555
|
+
return state === "running" ? void 0 : entry;
|
|
457
556
|
};
|
|
557
|
+
/**
|
|
558
|
+
* The result of a finished run. A `failed` run with partial output is
|
|
559
|
+
* `partial`, with that output and a `stopReason`; any other is `completed`
|
|
560
|
+
* with `data`, else the message, and throws `JobFailed` when it has neither.
|
|
561
|
+
* `sources` is always empty. The continuation id is the run's thread.
|
|
562
|
+
*/
|
|
458
563
|
const researchResult = (id, started, entry) => {
|
|
459
564
|
const run = entry.value;
|
|
460
565
|
const stopped = run.status === "failed";
|
|
@@ -467,13 +572,20 @@ const researchResult = (id, started, entry) => {
|
|
|
467
572
|
requestId: id,
|
|
468
573
|
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
|
|
469
574
|
}),
|
|
470
|
-
output: stopped ? run.partial :
|
|
575
|
+
output: stopped ? run.partial : requireOutput(provider, id, {
|
|
576
|
+
original: entry.original,
|
|
577
|
+
value: run.data ?? run.message.value
|
|
578
|
+
}),
|
|
471
579
|
raw: entry.original,
|
|
472
580
|
sources: [],
|
|
473
581
|
status,
|
|
474
582
|
stopReason: stopped ? run.stopReason ?? run.error ?? "failed" : void 0
|
|
475
583
|
});
|
|
476
584
|
};
|
|
585
|
+
/**
|
|
586
|
+
* The outcome of a script. `sessionId` is set only when the session is still
|
|
587
|
+
* open or could not be closed; `close` is what closing it returned.
|
|
588
|
+
*/
|
|
477
589
|
const actResult = (entry, sessionId, close) => {
|
|
478
590
|
const result = entry.value;
|
|
479
591
|
const stdout = result.stdout ?? "";
|
|
@@ -494,6 +606,7 @@ const actResult = (entry, sessionId, close) => {
|
|
|
494
606
|
stdout
|
|
495
607
|
});
|
|
496
608
|
};
|
|
609
|
+
/** An open browser session. Throws `ProviderError` when Firecrawl returned no id. */
|
|
497
610
|
const browserSession = (entry) => {
|
|
498
611
|
const session = entry.value;
|
|
499
612
|
return compact({
|
|
@@ -504,7 +617,7 @@ const browserSession = (entry) => {
|
|
|
504
617
|
raw: entry.original
|
|
505
618
|
});
|
|
506
619
|
};
|
|
507
|
-
/** Firecrawl's blocks, a page at a time; a page without a number is left out. */
|
|
620
|
+
/** Firecrawl's blocks, a page at a time; a page without a number is left out. `box` is set only when `bbox` has four numbers. */
|
|
508
621
|
const documentBlocks = (pages) => pages.flatMap((entry) => {
|
|
509
622
|
const page = entry.pageNumber;
|
|
510
623
|
if (page === void 0) return [];
|
|
@@ -537,6 +650,7 @@ const parseResult = (body) => {
|
|
|
537
650
|
meta: pageMeta(data, body.warning.notes)
|
|
538
651
|
});
|
|
539
652
|
};
|
|
653
|
+
/** What a monitor watches: its goal, else its target URLs or queries joined with commas. */
|
|
540
654
|
const watching = (monitor) => {
|
|
541
655
|
if (monitor.goal !== void 0) return monitor.goal;
|
|
542
656
|
return monitor.targets.flatMap((target) => {
|
|
@@ -545,6 +659,7 @@ const watching = (monitor) => {
|
|
|
545
659
|
return target.queries;
|
|
546
660
|
}).filter((item) => item !== void 0).join(", ") || void 0;
|
|
547
661
|
};
|
|
662
|
+
/** A monitor. `schedule` is its cron expression, else Firecrawl's text for it. */
|
|
548
663
|
const monitorInfo = (entry) => {
|
|
549
664
|
const monitor = entry.value;
|
|
550
665
|
return compact({
|
|
@@ -557,6 +672,11 @@ const monitorInfo = (entry) => {
|
|
|
557
672
|
webhookUrl: monitor.webhook.url
|
|
558
673
|
});
|
|
559
674
|
};
|
|
675
|
+
/**
|
|
676
|
+
* One check of a monitor as an event. The summary reads like
|
|
677
|
+
* `completed: 2 changed, 1 new of 40 pages`, and the time is when the check
|
|
678
|
+
* finished, else started, was scheduled or was created.
|
|
679
|
+
*/
|
|
560
680
|
const checkEvent = (entry) => {
|
|
561
681
|
const check = entry.value;
|
|
562
682
|
const { summary } = check;
|
|
@@ -582,7 +702,12 @@ const checkEvent = (entry) => {
|
|
|
582
702
|
].filter((part) => part !== void 0).join(": ")
|
|
583
703
|
});
|
|
584
704
|
};
|
|
585
|
-
/**
|
|
705
|
+
/**
|
|
706
|
+
* One page of a monitor's checks; the caller adds `raw`. The cursor is the
|
|
707
|
+
* offset of the next page, set only when this page is full. Firecrawl caps a
|
|
708
|
+
* page at 100 and reports no total, so when the checks end exactly on a page
|
|
709
|
+
* boundary the cursor leads to an empty page.
|
|
710
|
+
*/
|
|
586
711
|
const monitorEvents = (checks, offset) => compact({
|
|
587
712
|
events: checks.map((check) => checkEvent(check)),
|
|
588
713
|
next: checks.length === 100 ? String(offset + checks.length) : void 0
|
|
@@ -622,6 +747,7 @@ const Price = looseObject({
|
|
|
622
747
|
currency: optionalString,
|
|
623
748
|
formatted: optionalString
|
|
624
749
|
});
|
|
750
|
+
/** A product variant. GTINs arrive in several widths, so each is read apart; `values` maps option names to values. */
|
|
625
751
|
const Variant = looseObject({
|
|
626
752
|
availability: looseObject({
|
|
627
753
|
inStock: optionalBoolean,
|
|
@@ -751,6 +877,7 @@ const Execution = withOriginal(looseObject({
|
|
|
751
877
|
}));
|
|
752
878
|
/** What closing a session billed. */
|
|
753
879
|
const Closed = looseObject({ creditsBilled: optionalNumber });
|
|
880
|
+
/** A web or news search result. */
|
|
754
881
|
const WebItem = looseObject({
|
|
755
882
|
category: optionalString,
|
|
756
883
|
date: optionalString,
|
|
@@ -761,6 +888,7 @@ const WebItem = looseObject({
|
|
|
761
888
|
title: optionalString,
|
|
762
889
|
url: optionalString
|
|
763
890
|
});
|
|
891
|
+
/** A research search result. It carries ids, not a URL. */
|
|
764
892
|
const Paper = looseObject({
|
|
765
893
|
abstract: optionalString,
|
|
766
894
|
paperId: optionalString,
|
|
@@ -768,6 +896,7 @@ const Paper = looseObject({
|
|
|
768
896
|
score: optionalNumber,
|
|
769
897
|
title: optionalString
|
|
770
898
|
});
|
|
899
|
+
/** An image search result: `imageUrl` is the image and `url` the page it is on. */
|
|
771
900
|
const ImageItem = looseObject({
|
|
772
901
|
imageHeight: optionalNumber,
|
|
773
902
|
imageUrl: optionalString,
|
|
@@ -798,6 +927,7 @@ const MapResponse = looseObject({ links: arrayOf(z.union([z.pipe(z.string(), z.t
|
|
|
798
927
|
title: link.title,
|
|
799
928
|
url: link.url ?? ""
|
|
800
929
|
})))])) });
|
|
930
|
+
/** A monitor. Its targets are a scrape (`urls`), a crawl (`url`) or a search (`queries`). */
|
|
801
931
|
const Monitor = looseObject({
|
|
802
932
|
createdAt: optionalString,
|
|
803
933
|
goal: optionalString,
|
|
@@ -884,6 +1014,7 @@ const firecrawl = (config = {}) => {
|
|
|
884
1014
|
provider,
|
|
885
1015
|
retries: config.retries
|
|
886
1016
|
});
|
|
1017
|
+
/** Scrapes one URL with the formats and page settings given. */
|
|
887
1018
|
const scrape = async (url, formats, settings, call) => {
|
|
888
1019
|
const response = await raw.request("POST", "/scrape", {
|
|
889
1020
|
...call,
|
|
@@ -900,25 +1031,18 @@ const firecrawl = (config = {}) => {
|
|
|
900
1031
|
response
|
|
901
1032
|
};
|
|
902
1033
|
};
|
|
1034
|
+
/** The path of a `next` link, absolute or relative to the base URL, so the next page of results goes through the same client. */
|
|
903
1035
|
const pathOf = (link) => {
|
|
904
|
-
const
|
|
905
|
-
const
|
|
906
|
-
return next.pathname.slice(base.length) + next.search;
|
|
1036
|
+
const base = new URL(`${baseUrl.replace(/\/$/u, "")}/`);
|
|
1037
|
+
const next = new URL(link, base);
|
|
1038
|
+
return next.pathname.slice(base.pathname.length - 1) + next.search;
|
|
907
1039
|
};
|
|
908
1040
|
/**
|
|
909
1041
|
* Runs a crawl or batch scrape: waits for it, then reads every page of its
|
|
910
1042
|
* results and the pages that failed.
|
|
911
1043
|
*/
|
|
912
1044
|
const batchJob = async (kind, start, settings, finish) => await runJob(provider, {
|
|
913
|
-
check: async (id, request) => {
|
|
914
|
-
const status = z.parse(Batch, await raw.request("GET", `/${kind}/${segment(id)}`, request));
|
|
915
|
-
const state = status.value.status;
|
|
916
|
-
if (state === "failed" || state === "cancelled") throw new FieldworkError("JobFailed", `firecrawl ${kind} ${id} ended ${state}`, {
|
|
917
|
-
cause: status.original,
|
|
918
|
-
provider
|
|
919
|
-
});
|
|
920
|
-
return state === "completed" ? status : void 0;
|
|
921
|
-
},
|
|
1045
|
+
check: async (id, request) => batchState(kind, id, z.parse(Batch, await raw.request("GET", `/${kind}/${segment(id)}`, request))),
|
|
922
1046
|
finish: async (first, id) => {
|
|
923
1047
|
const path = `/${kind}/${segment(id)}`;
|
|
924
1048
|
const request = {
|
|
@@ -942,6 +1066,7 @@ const firecrawl = (config = {}) => {
|
|
|
942
1066
|
},
|
|
943
1067
|
start
|
|
944
1068
|
}, settings);
|
|
1069
|
+
/** Opens a browser session. Only a rate limit is retried, since after any other failure the session may already be open and billing. */
|
|
945
1070
|
const openSession = async (o, call) => {
|
|
946
1071
|
const session = z.parse(Session, await raw.request("POST", "/interact", {
|
|
947
1072
|
body: sessionBody(o),
|
|
@@ -1017,27 +1142,27 @@ const firecrawl = (config = {}) => {
|
|
|
1017
1142
|
},
|
|
1018
1143
|
async crawl(url, options) {
|
|
1019
1144
|
const { call, rest: o } = callSettings(options);
|
|
1020
|
-
return await batchJob("crawl", async () =>
|
|
1021
|
-
creates: true,
|
|
1145
|
+
return await batchJob("crawl", async () => await startJob(raw, "/crawl", {
|
|
1022
1146
|
...call,
|
|
1023
1147
|
body: crawlBody(url, o)
|
|
1024
|
-
})
|
|
1148
|
+
}, CrawlStart, (reply) => reply.id), {
|
|
1025
1149
|
...call,
|
|
1026
1150
|
interval: o.interval,
|
|
1027
1151
|
resume: o.resume
|
|
1028
1152
|
}, (job, id) => {
|
|
1029
1153
|
const { robotsBlocked } = job.errors.value;
|
|
1154
|
+
const { pages, gone } = presentPages(job.batches.flatMap((batch) => batch.value.data.map((item) => ({
|
|
1155
|
+
...toPage(item.value, url),
|
|
1156
|
+
raw: item.original
|
|
1157
|
+
}))));
|
|
1030
1158
|
return compact({
|
|
1031
|
-
failed: job.failed,
|
|
1159
|
+
failed: [...job.failed, ...gone],
|
|
1032
1160
|
id,
|
|
1033
1161
|
meta: meta({
|
|
1034
1162
|
credits: job.first.value.creditsUsed,
|
|
1035
1163
|
requestId: id
|
|
1036
1164
|
}),
|
|
1037
|
-
pages
|
|
1038
|
-
...toPage(item.value, url),
|
|
1039
|
-
raw: item.original
|
|
1040
|
-
}))),
|
|
1165
|
+
pages,
|
|
1041
1166
|
raw: {
|
|
1042
1167
|
batches: job.batches.map((batch) => batch.original),
|
|
1043
1168
|
errors: job.errors.original
|
|
@@ -1055,6 +1180,10 @@ const firecrawl = (config = {}) => {
|
|
|
1055
1180
|
schema: jsonSchemaOf(schema),
|
|
1056
1181
|
type: "json"
|
|
1057
1182
|
})], page, call);
|
|
1183
|
+
presentPage(provider, {
|
|
1184
|
+
...toPage(data, url),
|
|
1185
|
+
raw: response
|
|
1186
|
+
});
|
|
1058
1187
|
if (data.json === void 0) {
|
|
1059
1188
|
const why = data.warning.text;
|
|
1060
1189
|
throw new FieldworkError("ProviderError", `firecrawl returned no JSON for ${url}${why === void 0 ? "" : `: ${why}`}`, {
|
|
@@ -1182,19 +1311,18 @@ const firecrawl = (config = {}) => {
|
|
|
1182
1311
|
const { call, rest: o } = callSettings(options);
|
|
1183
1312
|
const { interval, resume, maxConcurrency, ignoreInvalidURLs, ...read } = o;
|
|
1184
1313
|
let started = z.parse(RunStart, {});
|
|
1185
|
-
return await batchJob("batch/scrape", async () => {
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
}, {
|
|
1314
|
+
return await batchJob("batch/scrape", async () => await startJob(raw, "/batch/scrape", {
|
|
1315
|
+
...call,
|
|
1316
|
+
body: compact({
|
|
1317
|
+
urls,
|
|
1318
|
+
...readBody(read),
|
|
1319
|
+
maxConcurrency,
|
|
1320
|
+
ignoreInvalidURLs
|
|
1321
|
+
})
|
|
1322
|
+
}, RunStart, (reply) => {
|
|
1323
|
+
started = reply;
|
|
1324
|
+
return reply.value.id;
|
|
1325
|
+
}), {
|
|
1198
1326
|
...call,
|
|
1199
1327
|
interval,
|
|
1200
1328
|
resume
|
|
@@ -1239,14 +1367,13 @@ const firecrawl = (config = {}) => {
|
|
|
1239
1367
|
output: await checkOutput(o.schema, result.output, { provider })
|
|
1240
1368
|
};
|
|
1241
1369
|
},
|
|
1242
|
-
start: async () => {
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
}
|
|
1370
|
+
start: async () => await startJob(raw, "/agent", {
|
|
1371
|
+
...call,
|
|
1372
|
+
body: researchBody(question, o)
|
|
1373
|
+
}, RunStart, (reply) => {
|
|
1374
|
+
started = reply;
|
|
1375
|
+
return reply.value.id;
|
|
1376
|
+
})
|
|
1250
1377
|
}, {
|
|
1251
1378
|
...call,
|
|
1252
1379
|
interval: o.interval,
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { $ as TableCell, A as ImageResult, B as ParsedDocument, C as DocumentInput, D as FailedUrl, E as Extraction, F as MonitorEvents, G as ProductVariant, H as Price, I as MonitorInfo, J as RunStatus, K as Recency, L as MonitorSchedule, M as JsonSchema, N as Meta, O as FieldSource, P as MonitorEvent, Q as SiteMap, R as Page, S as DocumentBlock, T as Entity, U as Product, V as Place, W as ProductImage, X as SearchResult, Y as SearchResponse, Z as SiteLink, _ as Crawl, a as RawClient, b as Decisions, c as ActResult, d as BrowserSession, et as Usage, f as CAPABILITIES, g as Condition, h as Citation, i as defineAdapter, j as ImageSearch, k as GROUP_CAPABILITIES, l as Answer, m as Capability, n as AnyAdapter, o as RequestOptions, p as CallOptions, q as Research, r as Operations, s as AccountUsage, t as Adapter, tt as WordBox, u as Box, v as DecisionAnswer, w as DocumentPage, x as Discovery, y as DecisionQuestion, z as PageBatch } from "./adapter-
|
|
2
|
-
import { i as FieldworkErrorCode, n as FieldworkOptions, r as FieldworkError, t as Fieldwork } from "./fieldwork-
|
|
3
|
-
import { n as StandardSchemaWithJSON, t as OutputSchema } from "./schema-
|
|
1
|
+
import { $ as TableCell, A as ImageResult, B as ParsedDocument, C as DocumentInput, D as FailedUrl, E as Extraction, F as MonitorEvents, G as ProductVariant, H as Price, I as MonitorInfo, J as RunStatus, K as Recency, L as MonitorSchedule, M as JsonSchema, N as Meta, O as FieldSource, P as MonitorEvent, Q as SiteMap, R as Page, S as DocumentBlock, T as Entity, U as Product, V as Place, W as ProductImage, X as SearchResult, Y as SearchResponse, Z as SiteLink, _ as Crawl, a as RawClient, b as Decisions, c as ActResult, d as BrowserSession, et as Usage, f as CAPABILITIES, g as Condition, h as Citation, i as defineAdapter, j as ImageSearch, k as GROUP_CAPABILITIES, l as Answer, m as Capability, n as AnyAdapter, o as RequestOptions, p as CallOptions, q as Research, r as Operations, s as AccountUsage, t as Adapter, tt as WordBox, u as Box, v as DecisionAnswer, w as DocumentPage, x as Discovery, y as DecisionQuestion, z as PageBatch } from "./adapter-Bh8EIrNe.js";
|
|
2
|
+
import { i as FieldworkErrorCode, n as FieldworkOptions, r as FieldworkError, t as Fieldwork } from "./fieldwork-BaWqUNI3.js";
|
|
3
|
+
import { n as StandardSchemaWithJSON, t as OutputSchema } from "./schema-BWWiMvkg.js";
|
|
4
4
|
/** Which adapter serves each capability, for `router`. */
|
|
5
5
|
type Routes = Partial<Record<Capability, AnyAdapter>>;
|
|
6
6
|
/** Each route must name an adapter whose provider offers that capability. */
|