@howells/fieldwork-sdk 0.0.0-stage → 0.3.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.
@@ -0,0 +1,932 @@
1
+ import { t as defineAdapter } from "./adapter-CEAQuT7F.js";
2
+ import { r as withJob, t as FieldworkError } from "./errors-BiIBG9zN.js";
3
+ import { b as requireKey, c as num, d as record, f as refuseTogether, g as text, h as strings, i as compact, m as scalar, o as list, p as requireId, s as meta, t as callSettings, u as productImages, v as createRawClient, y as poll } from "./util-CYenIQQT.js";
4
+ // src/adapters/firecrawl/shared.ts
5
+ const provider = "firecrawl";
6
+ const invalid = (message) => new FieldworkError("InvalidRequest", message, { provider });
7
+ const segment = (id) => encodeURIComponent(id);
8
+ const warnings = (...values) => values.flatMap((value) => typeof value === "string" ? [value] : list(value).map(String));
9
+ const country = (code) => code?.toUpperCase();
10
+ // src/adapters/firecrawl/schedule.ts
11
+ /** The fewest minutes Firecrawl allows between two checks of a monitor. */
12
+ const MIN_MINUTES = 5;
13
+ const NAMED_CRON = /* @__PURE__ */ new Map([
14
+ ["hour", "0 * * * *"],
15
+ ["day", "0 0 * * *"],
16
+ ["week", "0 0 * * 0"]
17
+ ]);
18
+ const DAILY_CRON = /* @__PURE__ */ new Map([[1, "0 0 * * *"], [7, "0 0 * * 0"]]);
19
+ const CRON_PART = /^(?:\*|(?<from>\d+)(?:-(?<to>\d+))?)(?:\/(?<step>\d+))?$/u;
20
+ const INTERVAL = /^(?<count>\d+)(?<unit>[hd])$/u;
21
+ const rangeEnd = (groups, wildcard, from, max) => {
22
+ if (wildcard || groups.to === void 0 && groups.step !== void 0) return max;
23
+ return groups.to === void 0 ? from : Number(groups.to);
24
+ };
25
+ const cronValues = (field, max) => {
26
+ const values = /* @__PURE__ */ new Set();
27
+ for (const part of field.split(",")) {
28
+ const groups = CRON_PART.exec(part)?.groups;
29
+ if (!groups) return;
30
+ const wildcard = part.startsWith("*");
31
+ const from = wildcard ? 0 : Number(groups.from);
32
+ const to = rangeEnd(groups, wildcard, from, max);
33
+ const step = Number(groups.step ?? 1);
34
+ if (step < 1 || from > to || to > max) return;
35
+ for (let value = from; value <= to; value += step) values.add(value);
36
+ }
37
+ return [...values].toSorted((a, b) => a - b);
38
+ };
39
+ const runGaps = (minutes, hours) => {
40
+ const gaps = minutes.slice(1).map((minute, index) => minute - (minutes[index] ?? 0));
41
+ const [first] = minutes;
42
+ 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
+ return gaps;
45
+ };
46
+ const checkCron = (cron) => {
47
+ const fields = cron.trim().split(/\s+/u);
48
+ if (fields.length !== 5) throw invalid(`firecrawl needs a five-field cron expression, got "${cron}"`);
49
+ const [minuteField = "", hourField = ""] = fields;
50
+ const minutes = cronValues(minuteField, 59);
51
+ const hours = cronValues(hourField, 23);
52
+ if (minutes && runGaps(minutes, hours).some((gap) => gap < MIN_MINUTES)) throw invalid(`firecrawl monitors run at most every ${MIN_MINUTES} minutes, got "${cron}"`);
53
+ return cron.trim();
54
+ };
55
+ const hourlyCron = (count) => {
56
+ if (!Number.isInteger(count) || count < 1 || 24 % count !== 0) return;
57
+ if (count === 1) return "0 * * * *";
58
+ return count === 24 ? "0 0 * * *" : `0 */${count} * * *`;
59
+ };
60
+ const cronFor = (schedule) => {
61
+ if ("cron" in schedule) return checkCron(schedule.cron);
62
+ const every = schedule.every;
63
+ const named = NAMED_CRON.get(every);
64
+ if (named) return named;
65
+ const groups = INTERVAL.exec(every)?.groups;
66
+ const count = Number(groups?.count);
67
+ const cron = groups?.unit === "h" ? hourlyCron(count) : DAILY_CRON.get(count);
68
+ if (cron) return cron;
69
+ 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
+ // src/adapters/firecrawl/request.ts
72
+ /** The largest file `/parse` takes. */
73
+ const MAX_PARSE_BYTES = 52428800;
74
+ /** Longest script `/interact/{id}/execute` runs, in seconds. */
75
+ const MAX_SCRIPT_SECONDS = 300;
76
+ /** Milliseconds the request outlives the script's own limit, so a killed script reports back. */
77
+ const SCRIPT_GRACE_MS = 1e4;
78
+ /** The longest query a search monitor takes. */
79
+ const MAX_MONITOR_QUERY = 256;
80
+ const MEDIA_TYPES = new Map(Object.entries({
81
+ csv: "text/csv",
82
+ doc: "application/msword",
83
+ docm: "application/vnd.ms-word.document.macroEnabled.12",
84
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
85
+ epub: "application/epub+zip",
86
+ htm: "text/html",
87
+ html: "text/html",
88
+ odp: "application/vnd.oasis.opendocument.presentation",
89
+ ods: "application/vnd.oasis.opendocument.spreadsheet",
90
+ odt: "application/vnd.oasis.opendocument.text",
91
+ pdf: "application/pdf",
92
+ ppt: "application/vnd.ms-powerpoint",
93
+ pptm: "application/vnd.ms-powerpoint.presentation.macroEnabled.12",
94
+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
95
+ rtf: "application/rtf",
96
+ xhtml: "application/xhtml+xml",
97
+ xls: "application/vnd.ms-excel",
98
+ xlsb: "application/vnd.ms-excel.sheet.binary.macroEnabled.12",
99
+ xlsm: "application/vnd.ms-excel.sheet.macroEnabled.12",
100
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
101
+ }));
102
+ const RECENCY = {
103
+ day: "d",
104
+ hour: "h",
105
+ month: "m",
106
+ week: "w",
107
+ year: "y"
108
+ };
109
+ const DATE = /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/u;
110
+ const pageBody = (o) => compact({
111
+ actions: o.actions,
112
+ excludeTags: o.excludeTags,
113
+ includeTags: o.includeTags,
114
+ location: o.location,
115
+ maxAge: o.maxAge === void 0 ? void 0 : Math.round(o.maxAge * 1e3),
116
+ mobile: o.mobile,
117
+ onlyMainContent: o.onlyMainContent,
118
+ parsers: o.parsers,
119
+ proxy: o.proxy,
120
+ waitFor: o.waitFor
121
+ });
122
+ const readFormats = (o) => {
123
+ const query = o.query === void 0 ? [] : [o.queryFormat === "question" ? {
124
+ question: o.query,
125
+ type: "question"
126
+ } : {
127
+ query: o.query,
128
+ type: "highlights"
129
+ }];
130
+ return [
131
+ "markdown",
132
+ ...o.include ?? [],
133
+ ...query
134
+ ];
135
+ };
136
+ const readBody = (o) => ({
137
+ formats: readFormats(o),
138
+ ...pageBody(o)
139
+ });
140
+ const usDate = (value) => {
141
+ const groups = DATE.exec(value)?.groups;
142
+ if (!groups) throw invalid(`firecrawl needs dates as YYYY-MM-DD, got "${value}"`);
143
+ return `${groups.month}/${groups.day}/${groups.year}`;
144
+ };
145
+ const timeFilter = (o) => {
146
+ refuseTogether(provider, o, "tbs", "recency", "publishedAfter");
147
+ refuseTogether(provider, o, "tbs", "recency", "publishedBefore");
148
+ if (o.tbs !== void 0) return o.tbs;
149
+ if (o.recency !== void 0) return `qdr:${RECENCY[o.recency]}`;
150
+ if (o.publishedAfter === void 0 && o.publishedBefore === void 0) return;
151
+ return [
152
+ "cdr:1",
153
+ o.publishedAfter === void 0 ? void 0 : `cd_min:${usDate(o.publishedAfter)}`,
154
+ o.publishedBefore === void 0 ? void 0 : `cd_max:${usDate(o.publishedBefore)}`
155
+ ].filter((part) => part !== void 0).join(",");
156
+ };
157
+ const searchBody = (query, o) => {
158
+ 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
+ return compact({
161
+ categories: o.categories?.map((type) => ({ type })),
162
+ country: country(o.country),
163
+ excludeDomains: o.excludeDomains,
164
+ ignoreInvalidURLs: o.ignoreInvalidURLs,
165
+ includeDomains: o.includeDomains,
166
+ limit: o.limit,
167
+ location: o.location,
168
+ query,
169
+ safe: o.safe,
170
+ scrapeOptions: o.content ? { formats: ["markdown"] } : void 0,
171
+ sources: o.sources?.map((type) => ({ type })),
172
+ tbs: timeFilter(o)
173
+ });
174
+ };
175
+ const imagesBody = (query, o) => compact({
176
+ country: country(o.country),
177
+ limit: o.limit,
178
+ location: o.location,
179
+ query,
180
+ safe: o.safe,
181
+ sources: [{ type: "images" }]
182
+ });
183
+ const mapBody = (url, o) => compact({
184
+ ignoreCache: o.ignoreCache,
185
+ ignoreQueryParameters: o.ignoreQueryParameters,
186
+ includeSubdomains: o.includeSubdomains,
187
+ limit: o.limit,
188
+ location: o.location,
189
+ search: o.search,
190
+ sitemap: o.sitemap,
191
+ url
192
+ });
193
+ const crawlBody = (url, o) => compact({
194
+ allowExternalLinks: o.allowExternalLinks,
195
+ allowSubdomains: o.allowSubdomains,
196
+ crawlEntireDomain: o.crawlEntireDomain,
197
+ delay: o.delay,
198
+ excludePaths: o.excludePaths,
199
+ ignoreQueryParameters: o.ignoreQueryParameters,
200
+ includePaths: o.includePaths,
201
+ limit: o.limit,
202
+ maxConcurrency: o.maxConcurrency,
203
+ maxDiscoveryDepth: o.maxDiscoveryDepth,
204
+ prompt: o.prompt,
205
+ regexOnFullURL: o.regexOnFullURL,
206
+ scrapeOptions: o.scrapeOptions ? readBody(o.scrapeOptions) : void 0,
207
+ sitemap: o.sitemap,
208
+ url
209
+ });
210
+ const researchBody = (question, o) => compact({
211
+ effort: o.effort,
212
+ location: o.country ? { country: country(o.country) } : void 0,
213
+ maxCredits: o.maxCredits,
214
+ model: o.model,
215
+ prompt: question,
216
+ schema: o.schema,
217
+ strictConstrainToURLs: o.strictConstrainToURLs,
218
+ threadId: o.continueFrom,
219
+ urls: o.urls
220
+ });
221
+ const sessionBody = (o) => compact({
222
+ activityTtl: o.activityTtl ?? o.ttl,
223
+ location: o.country ? { country: country(o.country) } : void 0,
224
+ profile: o.profile,
225
+ ttl: o.ttl
226
+ });
227
+ const checkAct = (o, timeout) => {
228
+ for (const name of [
229
+ "ttl",
230
+ "activityTtl",
231
+ "profile",
232
+ "country"
233
+ ]) refuseTogether(provider, o, "session", name);
234
+ if (timeout === void 0) return;
235
+ const seconds = Math.max(1, Math.ceil(timeout / 1e3));
236
+ if (seconds > MAX_SCRIPT_SECONDS) throw invalid(`firecrawl runs a script for at most ${MAX_SCRIPT_SECONDS} seconds`);
237
+ return seconds;
238
+ };
239
+ const scriptRequest = (code, language, call, seconds) => ({
240
+ body: compact({
241
+ code,
242
+ language: language ?? "node",
243
+ timeout: seconds
244
+ }),
245
+ signal: call.signal,
246
+ timeout: call.timeout === void 0 ? void 0 : call.timeout + SCRIPT_GRACE_MS
247
+ });
248
+ const parseForm = (document, o) => {
249
+ const extension = document.name.split(".").pop()?.toLowerCase() ?? "";
250
+ const mediaType = MEDIA_TYPES.get(extension);
251
+ if (!mediaType) throw invalid(`firecrawl parses ${[...MEDIA_TYPES.keys()].join(", ")} files, not "${document.name}"`);
252
+ const size = document.data instanceof Blob ? document.data.size : document.data.byteLength;
253
+ if (size > MAX_PARSE_BYTES) throw invalid(`firecrawl parses files up to 50 MB; ${document.name} is ${(size / 1024 / 1024).toFixed(1)} MB`);
254
+ const parser = compact({
255
+ blocks: o.blocks,
256
+ maxPages: o.maxPages,
257
+ mode: o.mode,
258
+ pageMarkers: o.pageMarkers,
259
+ pages: o.pages,
260
+ type: "pdf"
261
+ });
262
+ const form = new FormData();
263
+ form.set("options", JSON.stringify({
264
+ formats: ["markdown"],
265
+ parsers: [parser]
266
+ }));
267
+ form.set("file", new Blob([document.data], { type: mediaType }), document.name);
268
+ return form;
269
+ };
270
+ const monitorTarget = (o) => {
271
+ const searchOnly = [
272
+ o.searchWindow,
273
+ o.maxResults,
274
+ o.includeDomains,
275
+ o.excludeDomains
276
+ ].some((value) => value !== void 0);
277
+ if (o.urls && o.urls.length > 0) {
278
+ if (searchOnly) throw invalid("firecrawl applies searchWindow, maxResults and the domain lists to search monitors, which take a query and no urls");
279
+ return {
280
+ type: "scrape",
281
+ urls: o.urls
282
+ };
283
+ }
284
+ if (!o.query) throw invalid("firecrawl monitors need urls to watch or a query");
285
+ 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
+ return compact({
287
+ excludeDomains: o.excludeDomains,
288
+ includeDomains: o.includeDomains,
289
+ maxResults: o.maxResults,
290
+ queries: [o.query],
291
+ searchWindow: o.searchWindow,
292
+ type: "search"
293
+ });
294
+ };
295
+ const monitorBody = (o) => {
296
+ const target = monitorTarget(o);
297
+ return compact({
298
+ goal: o.query,
299
+ name: (o.name ?? o.query ?? o.urls?.[0] ?? "monitor").slice(0, 256),
300
+ retentionDays: o.retentionDays,
301
+ schedule: compact({
302
+ cron: cronFor(o.schedule),
303
+ timezone: o.timezone
304
+ }),
305
+ targets: [target],
306
+ webhook: o.webhookUrl ? { url: o.webhookUrl } : void 0
307
+ });
308
+ };
309
+ // src/adapters/firecrawl/response.ts
310
+ /** Where each paper source's records live on the web, for results that carry only ids. */
311
+ const PAPER_URLS = /* @__PURE__ */ new Map([
312
+ ["arxiv", (id) => `https://arxiv.org/abs/${id}`],
313
+ ["pmid", (id) => `https://pubmed.ncbi.nlm.nih.gov/${id}/`],
314
+ ["pmcid", (id) => `https://pmc.ncbi.nlm.nih.gov/articles/${id}/`],
315
+ ["doi", (id) => `https://doi.org/${id}`]
316
+ ]);
317
+ const LANGUAGE = /^(?<code>[a-z]{2})(?:[-_]|$)/u;
318
+ const firstText = (value) => Array.isArray(value) ? text(value.find((item) => typeof item === "string" && item !== "")) : text(value);
319
+ const languageCode = (value) => LANGUAGE.exec(firstText(value)?.toLowerCase() ?? "")?.groups?.code;
320
+ const excerptsOf = (data) => {
321
+ const highlight = text(data.highlights);
322
+ const highlights = highlight ? [highlight] : strings(data.highlights);
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
+ });
333
+ };
334
+ const toPage = (data, fallbackUrl, raw, top = {}) => {
335
+ const metadata = record(data.metadata);
336
+ return compact({
337
+ author: firstText(metadata.author),
338
+ description: firstText(metadata.description),
339
+ excerpts: excerptsOf(data),
340
+ favicon: text(metadata.favicon),
341
+ html: text(data.html),
342
+ image: firstText(metadata.ogImage) ?? firstText(metadata["og:image"]),
343
+ images: strings(data.images),
344
+ language: languageCode(metadata.language),
345
+ links: strings(data.links),
346
+ markdown: text(data.markdown),
347
+ meta: pageMeta(top, data),
348
+ publishedAt: text(metadata.publishedTime) ?? text(metadata["article:published_time"]),
349
+ raw,
350
+ rawHtml: text(data.rawHtml),
351
+ screenshot: text(data.screenshot),
352
+ statusCode: num(metadata.statusCode),
353
+ summary: text(data.summary),
354
+ title: firstText(metadata.title),
355
+ url: text(metadata.url) ?? text(metadata.sourceURL) ?? fallbackUrl
356
+ });
357
+ };
358
+ const price = (value) => {
359
+ const item = record(value);
360
+ const result = compact({
361
+ amount: text(item.amount) ?? num(item.amount)?.toString(),
362
+ currency: text(item.currency),
363
+ formatted: text(item.formatted)
364
+ });
365
+ return Object.keys(result).length > 0 ? result : void 0;
366
+ };
367
+ const gtin = (variant) => {
368
+ for (const key of [
369
+ "gtin",
370
+ "gtin14",
371
+ "gtin13",
372
+ "gtin12",
373
+ "gtin8"
374
+ ]) {
375
+ const value = scalar(variant[key]);
376
+ if (value) return value;
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
+ }));
386
+ return compact({
387
+ availability: text(availability.text),
388
+ gtin: gtin(variant),
389
+ id: text(variant.id),
390
+ images: productImages(variant.images),
391
+ inStock: typeof availability.inStock === "boolean" ? availability.inStock : void 0,
392
+ originalPrice: price(record(variant.sale).originalPrice),
393
+ price: price(variant.price),
394
+ sku: text(variant.sku),
395
+ title: text(variant.title),
396
+ values: Object.keys(values).length > 0 ? values : void 0
397
+ });
398
+ };
399
+ const allImages = (variants) => {
400
+ const seen = /* @__PURE__ */ new Map();
401
+ for (const image of variants.flatMap((variant) => variant.images ?? [])) if (!seen.has(image.url)) seen.set(image.url, image);
402
+ return seen.size > 0 ? [...seen.values()] : void 0;
403
+ };
404
+ const toProduct = (url, response, data) => {
405
+ if (!data.product) {
406
+ const why = text(data.warning) ?? text(response.warning);
407
+ throw new FieldworkError("NotFound", `firecrawl found no product on ${url}${why ? `: ${why}` : ""}`, {
408
+ cause: response,
409
+ provider
410
+ });
411
+ }
412
+ const product = record(data.product);
413
+ const variants = list(product.variants).map((variant) => toVariant(variant));
414
+ return compact({
415
+ brand: text(product.brand),
416
+ category: text(product.category),
417
+ description: text(product.description),
418
+ images: productImages(product.images) ?? allImages(variants),
419
+ meta: pageMeta(response, data),
420
+ raw: response,
421
+ title: text(product.title),
422
+ url: text(product.url),
423
+ variants
424
+ });
425
+ };
426
+ const searchItem = (item, kind) => {
427
+ const result = record(item);
428
+ return compact({
429
+ content: text(result.markdown),
430
+ image: text(result.imageUrl),
431
+ kind: text(result.category) ?? kind,
432
+ publishedAt: text(result.date),
433
+ snippet: text(result.description) ?? text(result.snippet),
434
+ title: text(result.title),
435
+ url: text(result.url) ?? ""
436
+ });
437
+ };
438
+ const paperItem = (item) => {
439
+ const paper = record(item);
440
+ const paperId = text(paper.paperId) ?? "";
441
+ const primary = text(paper.primaryId) ?? paperId;
442
+ const colon = primary.indexOf(":");
443
+ const resolve = colon > 0 ? PAPER_URLS.get(primary.slice(0, colon)) : void 0;
444
+ return compact({
445
+ kind: "research",
446
+ score: num(paper.score),
447
+ snippet: text(paper.abstract),
448
+ title: text(paper.title),
449
+ url: paperId.startsWith("web:") ? paperId.slice(4) : resolve?.(primary.slice(colon + 1)) ?? primary
450
+ });
451
+ };
452
+ const imageItems = (value) => list(value).flatMap((item) => {
453
+ const image = record(item);
454
+ const url = text(image.imageUrl);
455
+ return url ? [compact({
456
+ height: num(image.imageHeight),
457
+ sourceUrl: text(image.url),
458
+ title: text(image.title),
459
+ url,
460
+ width: num(image.imageWidth)
461
+ })] : [];
462
+ });
463
+ const searchMeta = (response) => meta({
464
+ credits: response.creditsUsed,
465
+ requestId: response.id,
466
+ warnings: warnings(response.warning, response.warnings)
467
+ });
468
+ const searchResult = (response) => {
469
+ const data = record(response.data);
470
+ return compact({
471
+ images: Array.isArray(data.images) ? imageItems(data.images) : void 0,
472
+ meta: searchMeta(response),
473
+ raw: response,
474
+ results: [
475
+ ...list(data.web).map((item) => searchItem(item, "web")),
476
+ ...list(data.news).map((item) => searchItem(item, "news")),
477
+ ...list(data.research).map((item) => paperItem(item))
478
+ ]
479
+ });
480
+ };
481
+ const imagesResult = (response) => compact({
482
+ meta: searchMeta(response),
483
+ raw: response,
484
+ results: imageItems(record(response.data).images)
485
+ });
486
+ const failedPages = (errors) => list(errors.errors).map((item) => {
487
+ const entry = record(item);
488
+ return {
489
+ error: text(entry.error) ?? "unknown error",
490
+ url: text(entry.url) ?? ""
491
+ };
492
+ });
493
+ const researchState = (id, status) => {
494
+ const state = text(status.status);
495
+ const hasPartial = status.partial !== void 0 && status.partial !== null;
496
+ const done = state === "completed" || state === "failed" && hasPartial;
497
+ if (!done && (state === "failed" || state === "cancelled")) throw new FieldworkError("JobFailed", `firecrawl research run ${id} ${state}: ${text(status.error) ?? text(status.stopReason) ?? "no reason given"}`, {
498
+ cause: status,
499
+ provider
500
+ });
501
+ return done ? status : void 0;
502
+ };
503
+ const researchResult = (id, started, run) => {
504
+ const stopped = run.status === "failed";
505
+ const status = stopped ? "partial" : "completed";
506
+ return compact({
507
+ continuationId: text(run.threadId) ?? text(started.threadId),
508
+ id,
509
+ meta: meta({
510
+ credits: run.creditsUsed,
511
+ requestId: id,
512
+ warnings: stopped ? [run.message, run.partialSchemaValid === false ? "the partial output does not match the schema" : void 0] : void 0
513
+ }),
514
+ output: stopped ? run.partial : run.data ?? run.message,
515
+ raw: run,
516
+ sources: [],
517
+ status,
518
+ stopReason: stopped ? text(run.stopReason) ?? text(run.error) ?? "failed" : void 0
519
+ });
520
+ };
521
+ const actResult = (result, sessionId, closed) => {
522
+ const stdout = text(result.stdout) ?? "";
523
+ const failure = result.success === false ? "firecrawl reported that the script did not succeed" : void 0;
524
+ const repeated = result.result === "" || result.result === null || result.result === stdout;
525
+ return compact({
526
+ error: text(result.error) ?? failure,
527
+ exitCode: num(result.exitCode),
528
+ killed: typeof result.killed === "boolean" ? result.killed : void 0,
529
+ meta: meta({ credits: closed?.creditsBilled }),
530
+ raw: result,
531
+ result: repeated ? void 0 : result.result,
532
+ sessionId,
533
+ stderr: text(result.stderr) ?? "",
534
+ stdout
535
+ });
536
+ };
537
+ const browserSession = (response) => compact({
538
+ cdpUrl: text(response.cdpUrl),
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);
547
+ return compact({
548
+ markdown: text(data.markdown) ?? "",
549
+ pages: Array.isArray(data.pages) ? list(data.pages).map((page) => ({
550
+ markdown: text(record(page).markdown) ?? "",
551
+ pageNumber: Number(record(page).pageNumber)
552
+ })) : void 0,
553
+ blocks: Array.isArray(data.blocks) ? data.blocks : void 0,
554
+ pageCount: num(metadata.totalPages) ?? num(metadata.numPages),
555
+ meta: pageMeta(response, data),
556
+ raw: response
557
+ });
558
+ };
559
+ const watching = (monitor) => {
560
+ const goal = text(monitor.goal);
561
+ if (goal) return goal;
562
+ return list(monitor.targets).map((item) => record(item)).flatMap((target) => {
563
+ if (target.type === "scrape") return strings(target.urls) ?? [];
564
+ if (target.type === "crawl") return [text(target.url)];
565
+ return strings(target.queries) ?? [];
566
+ }).filter((item) => item !== void 0).join(", ") || void 0;
567
+ };
568
+ const monitorInfo = (value) => {
569
+ const monitor = record(value);
570
+ const schedule = record(monitor.schedule);
571
+ return compact({
572
+ createdAt: text(monitor.createdAt),
573
+ id: requireId(provider, monitor.id),
574
+ raw: monitor,
575
+ schedule: text(schedule.cron) ?? text(schedule.text),
576
+ status: text(monitor.status),
577
+ watch: watching(monitor),
578
+ webhookUrl: text(record(monitor.webhook).url)
579
+ });
580
+ };
581
+ const checkEvent = (check) => {
582
+ const summary = record(check.summary);
583
+ const counts = [
584
+ "changed",
585
+ "new",
586
+ "removed",
587
+ "error"
588
+ ].flatMap((key) => {
589
+ const count = num(summary[key]);
590
+ return count === void 0 ? [] : [`${count} ${key}`];
591
+ });
592
+ const pages = num(summary.totalPages);
593
+ const of = pages === void 0 ? "" : ` of ${pages} pages`;
594
+ return compact({
595
+ at: text(check.finishedAt) ?? text(check.startedAt) ?? text(check.scheduledFor) ?? text(check.createdAt),
596
+ id: text(check.id),
597
+ raw: check,
598
+ summary: [
599
+ text(check.status),
600
+ counts.length > 0 ? `${counts.join(", ")}${of}` : void 0,
601
+ text(check.error)
602
+ ].filter((part) => part !== void 0).join(": ")
603
+ });
604
+ };
605
+ const monitorEvents = (response, offset) => {
606
+ const checks = list(response.data).map((item) => record(item));
607
+ return compact({
608
+ events: checks.map((check) => checkEvent(check)),
609
+ next: checks.length === 100 ? String(offset + checks.length) : void 0,
610
+ raw: response
611
+ });
612
+ };
613
+ const usageResult = (response) => {
614
+ const data = record(response.data);
615
+ return compact({
616
+ limit: num(data.planCredits),
617
+ periodEnd: text(data.billingPeriodEnd),
618
+ raw: response,
619
+ remaining: num(data.remainingCredits)
620
+ });
621
+ };
622
+ // src/adapters/firecrawl.ts
623
+ const firecrawl = (config = {}) => {
624
+ const baseUrl = config.baseUrl ?? "https://api.firecrawl.dev/v2";
625
+ const raw = createRawClient({
626
+ baseUrl,
627
+ fetch: config.fetch,
628
+ headers: { authorization: `Bearer ${requireKey(provider, config.apiKey, "FIRECRAWL_API_KEY")}` },
629
+ provider
630
+ });
631
+ const scrape = async (url, formats, settings, call) => {
632
+ const response = record(await raw.request("POST", "/scrape", {
633
+ ...call,
634
+ body: {
635
+ formats,
636
+ url,
637
+ ...pageBody(settings)
638
+ }
639
+ }));
640
+ return {
641
+ data: record(response.data),
642
+ response
643
+ };
644
+ };
645
+ const pathOf = (link) => {
646
+ const next = new URL(link);
647
+ const base = new URL(baseUrl).pathname.replace(/\/$/u, "");
648
+ return next.pathname.slice(base.length) + next.search;
649
+ };
650
+ const finished = async (kind, id, call, interval) => {
651
+ const path = `/${kind}/${segment(id)}`;
652
+ const get = async (to) => {
653
+ try {
654
+ return record(await raw.request("GET", to, { signal: call.signal }));
655
+ } catch (error) {
656
+ throw withJob(error, id);
657
+ }
658
+ };
659
+ const first = await poll(provider, id, async () => {
660
+ const status = record(await raw.request("GET", path, { signal: call.signal }));
661
+ const state = text(status.status);
662
+ if (state === "failed" || state === "cancelled") throw new FieldworkError("JobFailed", `firecrawl ${kind} ${id} ended ${state}`, {
663
+ cause: status,
664
+ provider
665
+ });
666
+ return state === "completed" ? status : void 0;
667
+ }, {
668
+ ...call,
669
+ interval
670
+ });
671
+ const batches = [first];
672
+ let next = text(first.next);
673
+ while (next) {
674
+ const batch = await get(pathOf(next));
675
+ batches.push(batch);
676
+ next = text(batch.next);
677
+ }
678
+ const errors = await get(`${path}/errors`);
679
+ return {
680
+ batches,
681
+ errors,
682
+ failed: failedPages(errors),
683
+ first
684
+ };
685
+ };
686
+ const openSession = async (o, call) => {
687
+ const response = record(await raw.request("POST", "/interact", {
688
+ body: sessionBody(o),
689
+ signal: call.signal
690
+ }));
691
+ return {
692
+ id: requireId(provider, response.id),
693
+ response
694
+ };
695
+ };
696
+ const closeQuietly = async (id, call) => {
697
+ try {
698
+ return record(await raw.request("DELETE", `/interact/${segment(id)}`, { signal: call.signal }));
699
+ } catch {
700
+ return null;
701
+ }
702
+ };
703
+ return defineAdapter({
704
+ name: provider,
705
+ operations: {
706
+ async act(code, options) {
707
+ const { call, rest: o } = callSettings(options);
708
+ const seconds = checkAct(o, call.timeout);
709
+ const created = o.session === void 0;
710
+ const keep = o.keepSession ?? !created;
711
+ const { id } = o.session === void 0 ? await openSession(o, call) : { id: o.session };
712
+ try {
713
+ const result = record(await raw.request("POST", `/interact/${segment(id)}/execute`, scriptRequest(code, o.language, call, seconds)));
714
+ const closed = keep ? null : await closeQuietly(id, call);
715
+ return actResult(result, keep ? id : void 0, closed);
716
+ } catch (error) {
717
+ if (created || !keep) await closeQuietly(id, call);
718
+ throw error;
719
+ }
720
+ },
721
+ browser: {
722
+ async close(id, options) {
723
+ const { call } = callSettings(options);
724
+ await raw.request("DELETE", `/interact/${segment(id)}`, call);
725
+ },
726
+ async open(options) {
727
+ const { call, rest: o } = callSettings(options);
728
+ const { response } = await openSession(o, call);
729
+ return browserSession(response);
730
+ }
731
+ },
732
+ async crawl(url, options) {
733
+ const { call, rest: o } = callSettings(options);
734
+ const id = o.resume ?? requireId("firecrawl", record(await raw.request("POST", "/crawl", {
735
+ ...call,
736
+ body: crawlBody(url, o)
737
+ })).id);
738
+ const job = await finished("crawl", id, call, o.interval);
739
+ return compact({
740
+ failed: job.failed,
741
+ id,
742
+ meta: meta({
743
+ credits: job.first.creditsUsed,
744
+ requestId: id
745
+ }),
746
+ pages: job.batches.flatMap((batch) => list(batch.data).map((item) => toPage(record(item), url, item))),
747
+ raw: {
748
+ batches: job.batches,
749
+ errors: job.errors
750
+ },
751
+ robotsBlocked: strings(job.errors.robotsBlocked),
752
+ total: num(job.first.total)
753
+ });
754
+ },
755
+ async extract(url, options) {
756
+ const { call, rest: o } = callSettings(options);
757
+ const { schema, prompt, ...page } = o;
758
+ const { response, data } = await scrape(url, [compact({
759
+ prompt,
760
+ schema,
761
+ type: "json"
762
+ })], page, call);
763
+ if (data.json === void 0) {
764
+ const why = text(data.warning);
765
+ throw new FieldworkError("ProviderError", `firecrawl returned no JSON for ${url}${why ? `: ${why}` : ""}`, {
766
+ cause: response,
767
+ provider
768
+ });
769
+ }
770
+ return compact({
771
+ data: data.json,
772
+ meta: pageMeta(response, data),
773
+ raw: response
774
+ });
775
+ },
776
+ async images(query, options) {
777
+ const { call, rest: o } = callSettings(options);
778
+ const response = record(await raw.request("POST", "/search", {
779
+ ...call,
780
+ body: imagesBody(query, o)
781
+ }));
782
+ return imagesResult(response);
783
+ },
784
+ async map(url, options) {
785
+ const { call, rest: o } = callSettings(options);
786
+ const response = record(await raw.request("POST", "/map", {
787
+ ...call,
788
+ body: mapBody(url, o)
789
+ }));
790
+ return {
791
+ links: list(response.links).map((item) => {
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
+ }),
800
+ raw: response
801
+ };
802
+ },
803
+ monitor: {
804
+ async create(options) {
805
+ const { call, rest: o } = callSettings(options);
806
+ const response = record(await raw.request("POST", "/monitor", {
807
+ ...call,
808
+ body: monitorBody(o)
809
+ }));
810
+ return monitorInfo(response.data);
811
+ },
812
+ async delete(id, options) {
813
+ const { call } = callSettings(options);
814
+ await raw.request("DELETE", `/monitor/${segment(id)}`, call);
815
+ },
816
+ async events(id, options) {
817
+ const { call, rest: o } = callSettings(options);
818
+ const offset = Number(o.cursor ?? 0);
819
+ if (!Number.isInteger(offset) || offset < 0) throw invalid(`firecrawl events cursor "${o.cursor}" is not valid`);
820
+ const response = record(await raw.request("GET", `/monitor/${segment(id)}/checks`, {
821
+ ...call,
822
+ query: {
823
+ limit: 100,
824
+ offset
825
+ }
826
+ }));
827
+ return monitorEvents(response, offset);
828
+ },
829
+ async get(id, options) {
830
+ const { call } = callSettings(options);
831
+ const response = record(await raw.request("GET", `/monitor/${segment(id)}`, call));
832
+ return monitorInfo(response.data);
833
+ },
834
+ async list(options) {
835
+ const { call } = callSettings(options);
836
+ const monitors = [];
837
+ for (;;) {
838
+ const response = record(await raw.request("GET", "/monitor", {
839
+ ...call,
840
+ query: {
841
+ limit: 100,
842
+ offset: monitors.length
843
+ }
844
+ }));
845
+ const page = list(response.data);
846
+ monitors.push(...page.map((item) => monitorInfo(item)));
847
+ if (page.length < 100) return monitors;
848
+ }
849
+ }
850
+ },
851
+ async parse(document, options) {
852
+ const { call, rest: o } = callSettings(options);
853
+ const form = parseForm(document, o);
854
+ const response = record(await raw.request("POST", "/parse", {
855
+ ...call,
856
+ form
857
+ }));
858
+ return parseResult(response);
859
+ },
860
+ async product(url, options) {
861
+ const { call, rest: o } = callSettings(options);
862
+ const { response, data } = await scrape(url, ["product"], o, call);
863
+ return toProduct(url, response, data);
864
+ },
865
+ async read(url, options) {
866
+ const { call, rest: o } = callSettings(options);
867
+ const { response, data } = await scrape(url, readFormats(o), o, call);
868
+ return toPage(data, url, response, response);
869
+ },
870
+ async readMany(urls, options) {
871
+ const { call, rest: o } = callSettings(options);
872
+ const { interval, resume, maxConcurrency, ignoreInvalidURLs, ...read } = o;
873
+ const started = resume === void 0 ? record(await raw.request("POST", "/batch/scrape", {
874
+ ...call,
875
+ body: compact({
876
+ urls,
877
+ ...readBody(read),
878
+ maxConcurrency,
879
+ ignoreInvalidURLs
880
+ })
881
+ })) : {};
882
+ const id = resume ?? requireId("firecrawl", started.id);
883
+ const job = await finished("batch/scrape", id, call, interval);
884
+ const rejected = (strings(started.invalidURLs) ?? []).map((url) => ({
885
+ error: "invalid URL",
886
+ url
887
+ }));
888
+ return compact({
889
+ failed: [...job.failed, ...rejected],
890
+ id,
891
+ meta: meta({
892
+ credits: job.first.creditsUsed,
893
+ requestId: id
894
+ }),
895
+ pages: job.batches.flatMap((batch) => list(batch.data).map((item) => toPage(record(item), "", item))),
896
+ raw: {
897
+ batches: job.batches,
898
+ errors: job.errors,
899
+ started
900
+ }
901
+ });
902
+ },
903
+ async research(question, options) {
904
+ const { call, rest: o } = callSettings(options);
905
+ const started = o.resume === void 0 ? record(await raw.request("POST", "/agent", {
906
+ ...call,
907
+ body: researchBody(question, o)
908
+ })) : {};
909
+ const id = o.resume ?? requireId("firecrawl", started.id);
910
+ const run = await poll(provider, id, async () => researchState(id, record(await raw.request("GET", `/agent/${segment(id)}`, { signal: call.signal }))), {
911
+ ...call,
912
+ interval: o.interval
913
+ });
914
+ return researchResult(id, started, run);
915
+ },
916
+ async search(query, options) {
917
+ const { call, rest: o } = callSettings(options);
918
+ const response = record(await raw.request("POST", "/search", {
919
+ ...call,
920
+ body: searchBody(query, o)
921
+ }));
922
+ return searchResult(response);
923
+ },
924
+ async usage(options) {
925
+ const { call } = callSettings(options);
926
+ return usageResult(record(await raw.request("GET", "/team/credit-usage", call)));
927
+ }
928
+ },
929
+ raw
930
+ });
931
+ };
932
+ export { firecrawl };