@howells/fieldwork-sdk 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/firecrawl.js CHANGED
@@ -1,12 +1,12 @@
1
- import { t as defineAdapter } from "./adapter-CEAQuT7F.js";
2
- import { r as withJob, t as FieldworkError } from "./errors-BiIBG9zN.js";
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";
1
+ import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
+ import { r as invalidRequest, t as FieldworkError } from "./errors-Yvk42oZH.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-n8MmaK1x.js";
4
+ import { t as runJob } from "./job-BGTwH3F-.js";
5
+ import { n as jsonSchemaOf, t as checkOutput } from "./schema-DbSIABP0.js";
6
+ import { a as refuseLarger, i as mediaTypeOf, n as documentPart, t as MEDIA_TYPES } from "./document-Dpj01mGx.js";
5
7
  import * as z from "zod/mini";
6
8
  // src/adapters/firecrawl/shared.ts
7
9
  const provider = "firecrawl";
8
- const invalid = (message) => new FieldworkError("InvalidRequest", message, { provider });
9
- const segment = (id) => encodeURIComponent(id);
10
10
  const country = (code) => code?.toUpperCase();
11
11
  // src/adapters/firecrawl/schedule.ts
12
12
  /** The fewest minutes Firecrawl allows between two checks of a monitor. */
@@ -46,11 +46,11 @@ const runGaps = (minutes, hours) => {
46
46
  };
47
47
  const checkCron = (cron) => {
48
48
  const fields = cron.trim().split(/\s+/u);
49
- if (fields.length !== 5) throw invalid(`firecrawl needs a five-field cron expression, got "${cron}"`);
49
+ if (fields.length !== 5) throw invalidRequest(provider, `needs a five-field cron expression, got "${cron}"`);
50
50
  const [minuteField = "", hourField = ""] = fields;
51
51
  const minutes = cronValues(minuteField, 59);
52
52
  const hours = cronValues(hourField, 23);
53
- if (minutes && runGaps(minutes, hours).some((gap) => gap < MIN_MINUTES)) throw invalid(`firecrawl monitors run at most every ${MIN_MINUTES} minutes, got "${cron}"`);
53
+ if (minutes && runGaps(minutes, hours).some((gap) => gap < MIN_MINUTES)) throw invalidRequest(provider, `monitors run at most every ${MIN_MINUTES} minutes, got "${cron}"`);
54
54
  return cron.trim();
55
55
  };
56
56
  const hourlyCron = (count) => {
@@ -67,39 +67,19 @@ const cronFor = (schedule) => {
67
67
  const count = Number(groups?.count);
68
68
  const cron = groups?.unit === "h" ? hourlyCron(count) : DAILY_CRON.get(count);
69
69
  if (cron !== void 0) return cron;
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
+ throw invalidRequest(provider, `cannot run a monitor every "${every}"; use hour, day, week, a number of hours that divides 24, 1d, 7d or a cron expression`);
71
71
  };
72
72
  // src/adapters/firecrawl/request.ts
73
- /** The largest file `/parse` takes. */
74
- const MAX_PARSE_BYTES = 52428800;
73
+ /** The largest file `/parse` takes, in megabytes. */
74
+ const MAX_PARSE_MB = 50;
75
75
  /** Longest script `/interact/{id}/execute` runs, in seconds. */
76
76
  const MAX_SCRIPT_SECONDS = 300;
77
- /** Milliseconds the request outlives the script's own limit, so a killed script reports back. */
78
- const SCRIPT_GRACE_MS = 1e4;
77
+ /** Longest `/parse` runs, in milliseconds. */
78
+ const MAX_PARSE_MS = 3e5;
79
+ /** Milliseconds a request outlives Firecrawl's own limit, so Firecrawl reports the timeout itself. */
80
+ const REPORT_GRACE_MS = 1e4;
79
81
  /** The longest query a search monitor takes. */
80
82
  const MAX_MONITOR_QUERY = 256;
81
- const MEDIA_TYPES = new Map(Object.entries({
82
- csv: "text/csv",
83
- doc: "application/msword",
84
- docm: "application/vnd.ms-word.document.macroEnabled.12",
85
- docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
86
- epub: "application/epub+zip",
87
- htm: "text/html",
88
- html: "text/html",
89
- odp: "application/vnd.oasis.opendocument.presentation",
90
- ods: "application/vnd.oasis.opendocument.spreadsheet",
91
- odt: "application/vnd.oasis.opendocument.text",
92
- pdf: "application/pdf",
93
- ppt: "application/vnd.ms-powerpoint",
94
- pptm: "application/vnd.ms-powerpoint.presentation.macroEnabled.12",
95
- pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
96
- rtf: "application/rtf",
97
- xhtml: "application/xhtml+xml",
98
- xls: "application/vnd.ms-excel",
99
- xlsb: "application/vnd.ms-excel.sheet.binary.macroEnabled.12",
100
- xlsm: "application/vnd.ms-excel.sheet.macroEnabled.12",
101
- xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
102
- }));
103
83
  const RECENCY = {
104
84
  day: "d",
105
85
  hour: "h",
@@ -140,7 +120,7 @@ const readBody = (o) => ({
140
120
  });
141
121
  const usDate = (value) => {
142
122
  const groups = DATE.exec(value)?.groups;
143
- if (!groups) throw invalid(`firecrawl needs dates as YYYY-MM-DD, got "${value}"`);
123
+ if (!groups) throw invalidRequest(provider, `needs dates as YYYY-MM-DD, got "${value}"`);
144
124
  return `${groups.month}/${groups.day}/${groups.year}`;
145
125
  };
146
126
  const timeFilter = (o) => {
@@ -157,7 +137,7 @@ const timeFilter = (o) => {
157
137
  };
158
138
  const searchBody = (query, o) => {
159
139
  refuseTogether(provider, o, "includeDomains", "excludeDomains");
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");
140
+ 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");
161
141
  return compact({
162
142
  categories: o.categories?.map((type) => ({ type })),
163
143
  country: country(o.country),
@@ -234,7 +214,7 @@ const checkAct = (o, timeout) => {
234
214
  ]) refuseTogether(provider, o, "session", name);
235
215
  if (timeout === void 0) return;
236
216
  const seconds = Math.max(1, Math.ceil(timeout / 1e3));
237
- if (seconds > MAX_SCRIPT_SECONDS) throw invalid(`firecrawl runs a script for at most ${MAX_SCRIPT_SECONDS} seconds`);
217
+ if (seconds > MAX_SCRIPT_SECONDS) throw invalidRequest(provider, `runs a script for at most ${MAX_SCRIPT_SECONDS} seconds`);
238
218
  return seconds;
239
219
  };
240
220
  const scriptRequest = (code, language, call, seconds) => ({
@@ -243,15 +223,14 @@ const scriptRequest = (code, language, call, seconds) => ({
243
223
  language: language ?? "node",
244
224
  timeout: seconds
245
225
  }),
226
+ retries: call.retries,
246
227
  signal: call.signal,
247
- timeout: call.timeout === void 0 ? void 0 : call.timeout + SCRIPT_GRACE_MS
228
+ timeout: call.timeout === void 0 ? void 0 : call.timeout + REPORT_GRACE_MS
248
229
  });
249
- const parseForm = (document, o) => {
250
- const extension = document.name.split(".").pop()?.toLowerCase() ?? "";
251
- const mediaType = MEDIA_TYPES.get(extension);
252
- if (mediaType === void 0) throw invalid(`firecrawl parses ${[...MEDIA_TYPES.keys()].join(", ")} files, not "${document.name}"`);
253
- const size = document.data instanceof Blob ? document.data.size : document.data.byteLength;
254
- if (size > MAX_PARSE_BYTES) throw invalid(`firecrawl parses files up to 50 MB; ${document.name} is ${(size / 1024 / 1024).toFixed(1)} MB`);
230
+ const parseForm = (document, o, timeout) => {
231
+ if (timeout !== void 0 && timeout > MAX_PARSE_MS) throw invalidRequest(provider, `parses for at most ${MAX_PARSE_MS / 1e3} seconds`);
232
+ if (mediaTypeOf(document.name) === void 0) throw invalidRequest(provider, `parses ${[...MEDIA_TYPES.keys()].join(", ")} files, not "${document.name}"`);
233
+ refuseLarger(provider, document, MAX_PARSE_MB);
255
234
  const parser = compact({
256
235
  blocks: o.blocks,
257
236
  maxPages: o.maxPages,
@@ -261,12 +240,12 @@ const parseForm = (document, o) => {
261
240
  type: "pdf"
262
241
  });
263
242
  const form = new FormData();
264
- form.set("options", JSON.stringify({
243
+ form.set("options", JSON.stringify(compact({
265
244
  formats: ["markdown"],
266
- parsers: [parser]
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);
245
+ parsers: [parser],
246
+ timeout
247
+ })));
248
+ form.set("file", documentPart(document), document.name);
270
249
  return form;
271
250
  };
272
251
  const monitorTarget = (o) => {
@@ -277,14 +256,14 @@ const monitorTarget = (o) => {
277
256
  o.excludeDomains
278
257
  ].some((value) => value !== void 0);
279
258
  if (o.urls && o.urls.length > 0) {
280
- if (searchOnly) throw invalid("firecrawl applies searchWindow, maxResults and the domain lists to search monitors, which take a query and no urls");
259
+ if (searchOnly) throw invalidRequest(provider, "applies searchWindow, maxResults and the domain lists to search monitors, which take a query and no urls");
281
260
  return {
282
261
  type: "scrape",
283
262
  urls: o.urls
284
263
  };
285
264
  }
286
- if (o.query === void 0 || o.query === "") throw invalid("firecrawl monitors need urls to watch or a query");
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`);
265
+ if (o.query === void 0 || o.query === "") throw invalidRequest(provider, "monitors need urls to watch or a query");
266
+ if (o.query.length > MAX_MONITOR_QUERY) throw invalidRequest(provider, `searches queries of up to ${MAX_MONITOR_QUERY} characters; pass urls to watch pages with a longer query`);
288
267
  return compact({
289
268
  excludeDomains: o.excludeDomains,
290
269
  includeDomains: o.includeDomains,
@@ -495,7 +474,7 @@ const researchResult = (id, started, entry) => {
495
474
  stopReason: stopped ? run.stopReason ?? run.error ?? "failed" : void 0
496
475
  });
497
476
  };
498
- const actResult = (entry, sessionId, closed) => {
477
+ const actResult = (entry, sessionId, close) => {
499
478
  const result = entry.value;
500
479
  const stdout = result.stdout ?? "";
501
480
  const failure = result.success === false ? "firecrawl reported that the script did not succeed" : void 0;
@@ -504,7 +483,10 @@ const actResult = (entry, sessionId, closed) => {
504
483
  error: result.error ?? failure,
505
484
  exitCode: result.exitCode,
506
485
  killed: result.killed,
507
- meta: meta({ credits: closed?.creditsBilled }),
486
+ meta: meta({
487
+ credits: close.closed?.creditsBilled,
488
+ warnings: close.failure
489
+ }),
508
490
  raw: entry.original,
509
491
  result: repeated ? void 0 : result.result,
510
492
  sessionId,
@@ -522,6 +504,25 @@ const browserSession = (entry) => {
522
504
  raw: entry.original
523
505
  });
524
506
  };
507
+ /** Firecrawl's blocks, a page at a time; a page without a number is left out. */
508
+ const documentBlocks = (pages) => pages.flatMap((entry) => {
509
+ const page = entry.pageNumber;
510
+ if (page === void 0) return [];
511
+ return entry.items.map((item) => {
512
+ const [x0, y0, x1, y1] = item.bbox;
513
+ return compact({
514
+ box: item.bbox.length === 4 && x0 !== void 0 && y0 !== void 0 && x1 !== void 0 && y1 !== void 0 ? {
515
+ height: y1 - y0,
516
+ left: x0,
517
+ top: y0,
518
+ width: x1 - x0
519
+ } : void 0,
520
+ page,
521
+ text: item.content ?? "",
522
+ type: item.type ?? "unknown"
523
+ });
524
+ });
525
+ });
525
526
  /** A parsed document; the caller adds `raw`. */
526
527
  const parseResult = (body) => {
527
528
  const { data } = body;
@@ -531,7 +532,7 @@ const parseResult = (body) => {
531
532
  markdown: page.markdown ?? "",
532
533
  pageNumber: Number(page.pageNumber)
533
534
  })),
534
- blocks: data.blocks,
535
+ blocks: data.blocks && documentBlocks(data.blocks),
535
536
  pageCount: data.metadata.totalPages ?? data.metadata.numPages,
536
537
  meta: pageMeta(data, body.warning.notes)
537
538
  });
@@ -837,10 +838,19 @@ const ChecksResponse = looseObject({ data: arrayOf(withOriginal(looseObject({
837
838
  totalPages: optionalNumber
838
839
  })
839
840
  }))) });
841
+ /** A page of `/parse` blocks; each box is `[x0, y0, x1, y1]` in fractions of the page. */
842
+ const ParsePage = looseObject({
843
+ items: arrayOf(looseObject({
844
+ bbox: arrayOf(z.number()),
845
+ content: optionalAnyString,
846
+ type: optionalString
847
+ })),
848
+ pageNumber: optionalNumber
849
+ });
840
850
  /** `/parse`. */
841
851
  const ParseResponse = looseObject({
842
852
  data: looseObject({
843
- blocks: optionalArrayOf(anything),
853
+ blocks: optionalArrayOf(ParsePage),
844
854
  markdown: optionalString,
845
855
  metadata: looseObject(metadataShape),
846
856
  pages: optionalArrayOf(looseObject({
@@ -858,6 +868,13 @@ const UsageResponse = looseObject({ data: looseObject({
858
868
  remainingCredits: optionalNumber
859
869
  }) });
860
870
  // src/adapters/firecrawl.ts
871
+ /** How long closing a session may take, apart from the call's own deadline. */
872
+ const CLOSE_TIMEOUT = 15e3;
873
+ /**
874
+ * An adapter for Firecrawl: search, images, read, readMany, extract, product, map, crawl, research, act, browser, parse, monitor and usage. Pass it to `new Fieldwork({ adapter })`.
875
+ *
876
+ * Throws `Unauthorized` when neither `apiKey` nor `FIRECRAWL_API_KEY` is set.
877
+ */
861
878
  const firecrawl = (config = {}) => {
862
879
  const baseUrl = config.baseUrl ?? "https://api.firecrawl.dev/v2";
863
880
  const raw = createRawClient({
@@ -888,46 +905,48 @@ const firecrawl = (config = {}) => {
888
905
  const base = new URL(baseUrl).pathname.replace(/\/$/u, "");
889
906
  return next.pathname.slice(base.length) + next.search;
890
907
  };
891
- const finished = async (kind, id, call, interval) => {
892
- const path = `/${kind}/${segment(id)}`;
893
- const get = async (schema, to) => {
894
- try {
895
- return z.parse(schema, await raw.request("GET", to, { signal: call.signal }));
896
- } catch (error) {
897
- throw withJob(error, id);
898
- }
899
- };
900
- const first = await poll(provider, id, async () => {
901
- const status = z.parse(Batch, await raw.request("GET", path, { signal: call.signal }));
908
+ /**
909
+ * Runs a crawl or batch scrape: waits for it, then reads every page of its
910
+ * results and the pages that failed.
911
+ */
912
+ 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));
902
915
  const state = status.value.status;
903
916
  if (state === "failed" || state === "cancelled") throw new FieldworkError("JobFailed", `firecrawl ${kind} ${id} ended ${state}`, {
904
917
  cause: status.original,
905
918
  provider
906
919
  });
907
920
  return state === "completed" ? status : void 0;
908
- }, {
909
- ...call,
910
- interval
911
- });
912
- const batches = [first];
913
- let { next } = first.value;
914
- while (next !== void 0) {
915
- const batch = await get(Batch, pathOf(next));
916
- batches.push(batch);
917
- ({next} = batch.value);
918
- }
919
- const errors = await get(BatchErrors, `${path}/errors`);
920
- return {
921
- batches,
922
- errors,
923
- failed: failedPages(errors),
924
- first
925
- };
926
- };
921
+ },
922
+ finish: async (first, id) => {
923
+ const path = `/${kind}/${segment(id)}`;
924
+ const request = {
925
+ retries: settings.retries,
926
+ signal: settings.signal
927
+ };
928
+ const batches = [first];
929
+ let { next } = first.value;
930
+ while (next !== void 0) {
931
+ const batch = z.parse(Batch, await raw.request("GET", pathOf(next), request));
932
+ batches.push(batch);
933
+ ({next} = batch.value);
934
+ }
935
+ const errors = z.parse(BatchErrors, await raw.request("GET", `${path}/errors`, request));
936
+ return finish({
937
+ batches,
938
+ errors,
939
+ failed: failedPages(errors),
940
+ first
941
+ }, id);
942
+ },
943
+ start
944
+ }, settings);
927
945
  const openSession = async (o, call) => {
928
946
  const session = z.parse(Session, await raw.request("POST", "/interact", {
929
947
  body: sessionBody(o),
930
948
  creates: true,
949
+ retries: call.retries,
931
950
  signal: call.signal
932
951
  }));
933
952
  return {
@@ -935,18 +954,33 @@ const firecrawl = (config = {}) => {
935
954
  session
936
955
  };
937
956
  };
938
- const closeQuietly = async (id, call) => {
957
+ /**
958
+ * Closes a session so it stops billing. It runs on its own deadline, so a
959
+ * call that was cancelled or timed out still closes what it opened. A
960
+ * failure is returned rather than thrown: the caller reports it with the
961
+ * session id, so the session can still be closed by hand.
962
+ */
963
+ const closeSession = async (id, call) => {
939
964
  try {
940
- return z.parse(Closed, await raw.request("DELETE", `/interact/${segment(id)}`, { signal: call.signal }));
941
- } catch {
942
- return null;
965
+ return {
966
+ closed: z.parse(Closed, await raw.request("DELETE", `/interact/${segment(id)}`, {
967
+ retries: call.retries,
968
+ signal: AbortSignal.timeout(CLOSE_TIMEOUT)
969
+ })),
970
+ failure: void 0
971
+ };
972
+ } catch (error) {
973
+ return {
974
+ closed: void 0,
975
+ failure: `firecrawl could not close session ${id}, which may still bill: ${error instanceof Error ? error.message : String(error)}. Close it with DELETE /interact/${id}`
976
+ };
943
977
  }
944
978
  };
945
979
  return defineAdapter({
946
980
  name: provider,
947
981
  operations: {
948
982
  async act(code, options) {
949
- const { call, rest: o } = callSettings(options);
983
+ const { call, rest: o } = callSettings(options, REPORT_GRACE_MS);
950
984
  const seconds = checkAct(o, call.timeout);
951
985
  const created = o.session === void 0;
952
986
  const keep = o.keepSession ?? !created;
@@ -956,11 +990,18 @@ const firecrawl = (config = {}) => {
956
990
  ...scriptRequest(code, o.language, call, seconds),
957
991
  creates: true
958
992
  }));
959
- const closed = keep ? null : await closeQuietly(id, call);
960
- return actResult(result, keep ? id : void 0, closed);
993
+ if (keep) return actResult(result, id, {});
994
+ const close = await closeSession(id, call);
995
+ return actResult(result, close.failure === void 0 ? void 0 : id, close);
961
996
  } catch (error) {
962
- if (created || !keep) await closeQuietly(id, call);
963
- throw error;
997
+ if (!created && keep) throw error;
998
+ const close = await closeSession(id, call);
999
+ if (close.failure === void 0 || !(error instanceof FieldworkError)) throw error;
1000
+ throw new FieldworkError(error.code, `${error.message}; ${close.failure}`, {
1001
+ cause: error,
1002
+ provider,
1003
+ status: error.status
1004
+ });
964
1005
  }
965
1006
  },
966
1007
  browser: {
@@ -976,30 +1017,34 @@ const firecrawl = (config = {}) => {
976
1017
  },
977
1018
  async crawl(url, options) {
978
1019
  const { call, rest: o } = callSettings(options);
979
- const id = o.resume ?? requireJobId("firecrawl", z.parse(CrawlStart, await raw.request("POST", "/crawl", {
1020
+ return await batchJob("crawl", async () => requireJobId(provider, z.parse(CrawlStart, await raw.request("POST", "/crawl", {
980
1021
  creates: true,
981
1022
  ...call,
982
1023
  body: crawlBody(url, o)
983
- })).id);
984
- const job = await finished("crawl", id, call, o.interval);
985
- const { robotsBlocked } = job.errors.value;
986
- return compact({
987
- failed: job.failed,
988
- id,
989
- meta: meta({
990
- credits: job.first.value.creditsUsed,
991
- requestId: id
992
- }),
993
- pages: job.batches.flatMap((batch) => batch.value.data.map((item) => ({
994
- ...toPage(item.value, url),
995
- raw: item.original
996
- }))),
997
- raw: {
998
- batches: job.batches.map((batch) => batch.original),
999
- errors: job.errors.original
1000
- },
1001
- robotsBlocked: robotsBlocked.length > 0 ? robotsBlocked : void 0,
1002
- total: job.first.value.total
1024
+ })).id), {
1025
+ ...call,
1026
+ interval: o.interval,
1027
+ resume: o.resume
1028
+ }, (job, id) => {
1029
+ const { robotsBlocked } = job.errors.value;
1030
+ return compact({
1031
+ failed: job.failed,
1032
+ id,
1033
+ meta: meta({
1034
+ credits: job.first.value.creditsUsed,
1035
+ requestId: id
1036
+ }),
1037
+ pages: job.batches.flatMap((batch) => batch.value.data.map((item) => ({
1038
+ ...toPage(item.value, url),
1039
+ raw: item.original
1040
+ }))),
1041
+ raw: {
1042
+ batches: job.batches.map((batch) => batch.original),
1043
+ errors: job.errors.original
1044
+ },
1045
+ robotsBlocked: robotsBlocked.length > 0 ? robotsBlocked : void 0,
1046
+ total: job.first.value.total
1047
+ });
1003
1048
  });
1004
1049
  },
1005
1050
  async extract(url, options) {
@@ -1062,7 +1107,7 @@ const firecrawl = (config = {}) => {
1062
1107
  async events(id, options) {
1063
1108
  const { call, rest: o } = callSettings(options);
1064
1109
  const offset = Number(o.cursor ?? 0);
1065
- if (!Number.isInteger(offset) || offset < 0) throw invalid(`firecrawl events cursor "${o.cursor}" is not valid`);
1110
+ if (!Number.isInteger(offset) || offset < 0) throw invalidRequest(provider, `events cursor "${o.cursor}" is not valid`);
1066
1111
  const response = await raw.request("GET", `/monitor/${segment(id)}/checks`, {
1067
1112
  ...call,
1068
1113
  query: {
@@ -1097,11 +1142,12 @@ const firecrawl = (config = {}) => {
1097
1142
  }
1098
1143
  },
1099
1144
  async parse(document, options) {
1100
- const { call, rest: o } = callSettings(options);
1101
- const form = parseForm(document, o);
1145
+ const { call, rest: o } = callSettings(options, REPORT_GRACE_MS);
1146
+ const form = parseForm(document, o, call.timeout);
1102
1147
  const response = await raw.request("POST", "/parse", {
1103
1148
  ...call,
1104
- form
1149
+ form,
1150
+ timeout: call.timeout === void 0 ? void 0 : call.timeout + REPORT_GRACE_MS
1105
1151
  });
1106
1152
  return {
1107
1153
  ...parseResult(z.parse(ParseResponse, response)),
@@ -1135,65 +1181,77 @@ const firecrawl = (config = {}) => {
1135
1181
  async readMany(urls, options) {
1136
1182
  const { call, rest: o } = callSettings(options);
1137
1183
  const { interval, resume, maxConcurrency, ignoreInvalidURLs, ...read } = o;
1138
- const started = z.parse(RunStart, resume === void 0 ? await raw.request("POST", "/batch/scrape", {
1139
- creates: true,
1184
+ let started = z.parse(RunStart, {});
1185
+ return await batchJob("batch/scrape", async () => {
1186
+ started = z.parse(RunStart, await raw.request("POST", "/batch/scrape", {
1187
+ creates: true,
1188
+ ...call,
1189
+ body: compact({
1190
+ urls,
1191
+ ...readBody(read),
1192
+ maxConcurrency,
1193
+ ignoreInvalidURLs
1194
+ })
1195
+ }));
1196
+ return requireJobId(provider, started.value.id);
1197
+ }, {
1140
1198
  ...call,
1141
- body: compact({
1142
- urls,
1143
- ...readBody(read),
1144
- maxConcurrency,
1145
- ignoreInvalidURLs
1146
- })
1147
- }) : {});
1148
- const id = resume ?? requireJobId("firecrawl", started.value.id);
1149
- const job = await finished("batch/scrape", id, call, interval);
1150
- const rejected = started.value.invalidURLs.map((url) => ({
1151
- error: "invalid URL",
1152
- url
1153
- }));
1154
- const { pages, gone } = presentPages(job.batches.flatMap((batch) => batch.value.data.map((item) => ({
1155
- ...toPage(item.value, ""),
1156
- raw: item.original
1157
- }))));
1158
- return compact({
1159
- failed: [
1160
- ...job.failed,
1161
- ...rejected,
1162
- ...gone
1163
- ],
1164
- id,
1165
- meta: meta({
1166
- credits: job.first.value.creditsUsed,
1167
- requestId: id
1168
- }),
1169
- pages,
1170
- raw: {
1171
- batches: job.batches.map((batch) => batch.original),
1172
- errors: job.errors.original,
1173
- started: started.original
1174
- }
1199
+ interval,
1200
+ resume
1201
+ }, (job, id) => {
1202
+ const rejected = started.value.invalidURLs.map((url) => ({
1203
+ error: "invalid URL",
1204
+ url
1205
+ }));
1206
+ const { pages, gone } = presentPages(job.batches.flatMap((batch) => batch.value.data.map((item) => ({
1207
+ ...toPage(item.value, ""),
1208
+ raw: item.original
1209
+ }))));
1210
+ return compact({
1211
+ failed: [
1212
+ ...job.failed,
1213
+ ...rejected,
1214
+ ...gone
1215
+ ],
1216
+ id,
1217
+ meta: meta({
1218
+ credits: job.first.value.creditsUsed,
1219
+ requestId: id
1220
+ }),
1221
+ pages,
1222
+ raw: {
1223
+ batches: job.batches.map((batch) => batch.original),
1224
+ errors: job.errors.original,
1225
+ started: started.original
1226
+ }
1227
+ });
1175
1228
  });
1176
1229
  },
1177
1230
  async research(question, options) {
1178
1231
  const { call, rest: o } = callSettings(options);
1179
- const started = z.parse(RunStart, o.resume === void 0 ? await raw.request("POST", "/agent", {
1180
- creates: true,
1181
- ...call,
1182
- body: researchBody(question, o)
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 }))), {
1232
+ let started = z.parse(RunStart, {});
1233
+ return await runJob(provider, {
1234
+ check: async (id, request) => researchState(id, z.parse(AgentRun, await raw.request("GET", `/agent/${segment(id)}`, request))),
1235
+ finish: async (run, id) => {
1236
+ const result = researchResult(id, started, run);
1237
+ return {
1238
+ ...result,
1239
+ output: await checkOutput(o.schema, result.output, { provider })
1240
+ };
1241
+ },
1242
+ start: async () => {
1243
+ started = z.parse(RunStart, await raw.request("POST", "/agent", {
1244
+ creates: true,
1245
+ ...call,
1246
+ body: researchBody(question, o)
1247
+ }));
1248
+ return requireJobId(provider, started.value.id);
1249
+ }
1250
+ }, {
1186
1251
  ...call,
1187
- interval: o.interval
1252
+ interval: o.interval,
1253
+ resume: o.resume
1188
1254
  });
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
- };
1197
1255
  },
1198
1256
  async search(query, options) {
1199
1257
  const { call, rest: o } = callSettings(options);
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
- import { A as JsonSchema, B as Price, C as Entity, D as GROUP_CAPABILITIES, E as FieldSource, F as MonitorSchedule, G as Research, H as ProductImage, I as Page, J as SearchResult, K as RunStatus, L as PageBatch, M as MonitorEvent, N as MonitorEvents, O as ImageResult, P as MonitorInfo, R as ParsedDocument, S as DocumentPage, T as FailedUrl, U as ProductVariant, V as Product, W as Recency, X as SiteMap, Y as SiteLink, Z as Usage, _ as DecisionAnswer, a as RawClient, b as Discovery, c as ActResult, d as CAPABILITIES, f as CallOptions, g as Crawl, h as Condition, i as defineAdapter, j as Meta, k as ImageSearch, l as Answer, m as Citation, n as AnyAdapter, o as RequestOptions, p as Capability, q as SearchResponse, r as Operations, s as AccountUsage, t as Adapter, u as BrowserSession, v as DecisionQuestion, w as Extraction, x as DocumentInput, y as Decisions, z as Place } from "./adapter-CDY8qczv.js";
2
- import { i as FieldworkErrorCode, n as FieldworkOptions, r as FieldworkError, t as Fieldwork } from "./fieldwork-DTNVIOzp.js";
3
- import { n as StandardSchemaWithJSON, t as OutputSchema } from "./schema-EZlBkY5B.js";
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-BgdfLBs-.js";
2
+ import { i as FieldworkErrorCode, n as FieldworkOptions, r as FieldworkError, t as Fieldwork } from "./fieldwork-CXNIcqSN.js";
3
+ import { n as StandardSchemaWithJSON, t as OutputSchema } from "./schema-Cupy7-7q.js";
4
+ /** Which adapter serves each capability, for `router`. */
4
5
  type Routes = Partial<Record<Capability, AnyAdapter>>;
5
6
  /** Each route must name an adapter whose provider offers that capability. */
6
7
  type ValidRoutes<R extends Routes> = { [C in keyof R]: C extends Capability ? R[C] extends {
@@ -22,4 +23,4 @@ export declare const router: <const R extends Routes>(routes: R & ValidRoutes<R>
22
23
  * `Unsupported` here instead of failing to compile.
23
24
  */
24
25
  export declare const runtimeRouter: (routes: Routes) => AnyAdapter;
25
- export { AccountUsage, ActResult, type Adapter, Answer, type AnyAdapter, BrowserSession, CAPABILITIES, CallOptions, Capability, Citation, Condition, Crawl, DecisionAnswer, DecisionQuestion, Decisions, Discovery, DocumentInput, DocumentPage, Entity, Extraction, FailedUrl, FieldSource, Fieldwork, FieldworkError, type FieldworkErrorCode, type FieldworkOptions, GROUP_CAPABILITIES, ImageResult, ImageSearch, JsonSchema, Meta, MonitorEvent, MonitorEvents, MonitorInfo, MonitorSchedule, type Operations, type OutputSchema, Page, PageBatch, ParsedDocument, Place, Price, Product, ProductImage, ProductVariant, type RawClient, Recency, type RequestOptions, Research, type Routes, RunStatus, SearchResponse, SearchResult, SiteLink, SiteMap, type StandardSchemaWithJSON, Usage, defineAdapter };
26
+ export { AccountUsage, ActResult, type Adapter, Answer, type AnyAdapter, Box, BrowserSession, CAPABILITIES, CallOptions, Capability, Citation, Condition, Crawl, DecisionAnswer, DecisionQuestion, Decisions, Discovery, DocumentBlock, DocumentInput, DocumentPage, Entity, Extraction, FailedUrl, FieldSource, Fieldwork, FieldworkError, type FieldworkErrorCode, type FieldworkOptions, GROUP_CAPABILITIES, ImageResult, ImageSearch, JsonSchema, Meta, MonitorEvent, MonitorEvents, MonitorInfo, MonitorSchedule, type Operations, type OutputSchema, Page, PageBatch, ParsedDocument, Place, Price, Product, ProductImage, ProductVariant, type RawClient, Recency, type RequestOptions, Research, type Routes, RunStatus, SearchResponse, SearchResult, SiteLink, SiteMap, type StandardSchemaWithJSON, TableCell, Usage, WordBox, defineAdapter };