@howells/fieldwork-sdk 0.11.0 → 0.12.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.
Files changed (47) hide show
  1. package/README.md +72 -15
  2. package/dist/{adapter-DWYJys20.js → adapter-CBSAfErv.js} +1 -1
  3. package/dist/adapter-J2yatZJ0.d.ts +73 -0
  4. package/dist/best-CO9liYDa.js +1436 -0
  5. package/dist/brave.d.ts +7 -6
  6. package/dist/brave.js +180 -173
  7. package/dist/browserbase.d.ts +4 -3
  8. package/dist/browserbase.js +185 -170
  9. package/dist/{document-DMIUCoDA.js → document-BSCwJgBM.js} +4 -4
  10. package/dist/{download-CP8noBdX.js → download-kuTqNnuZ.js} +1 -1
  11. package/dist/{adapter-B8kAAAgF.d.ts → errors-gMtejKHc.d.ts} +87 -69
  12. package/dist/exa.d.ts +18 -11
  13. package/dist/exa.js +306 -275
  14. package/dist/fieldwork-D7npPoUf.d.ts +35 -0
  15. package/dist/firecrawl.d.ts +4 -3
  16. package/dist/firecrawl.js +450 -417
  17. package/dist/{parse-Q7H4mrnO.js → http-CJcvTPnE.js} +223 -225
  18. package/dist/image.d.ts +253 -0
  19. package/dist/image.js +1 -0
  20. package/dist/index.d.ts +6 -7
  21. package/dist/index.js +66 -82
  22. package/dist/{job-DnavRq_s.js → job-JLEpszjr.js} +9 -9
  23. package/dist/kernel.d.ts +20 -2
  24. package/dist/kernel.js +65 -19
  25. package/dist/llamaparse.d.ts +3 -2
  26. package/dist/llamaparse.js +16 -16
  27. package/dist/parallel.d.ts +8 -8
  28. package/dist/parallel.js +423 -389
  29. package/dist/path-DO2llIdp.js +10 -0
  30. package/dist/perplexity.d.ts +6 -5
  31. package/dist/perplexity.js +21 -21
  32. package/dist/reducto.d.ts +3 -2
  33. package/dist/reducto.js +14 -14
  34. package/dist/{schema-CAPSX7yQ.d.ts → schema-C9xzRkKJ.d.ts} +17 -6
  35. package/dist/{schema--iU4AXSM.js → schema-CJXFAZ-x.js} +12 -3
  36. package/dist/serpapi.d.ts +3 -3
  37. package/dist/serpapi.js +176 -171
  38. package/dist/tavily.d.ts +4 -3
  39. package/dist/tavily.js +247 -234
  40. package/dist/tools.d.ts +76 -15
  41. package/dist/tools.js +351 -33
  42. package/dist/{util-DFUXQX6v.js → util-LvME_uOj.js} +35 -11
  43. package/package.json +6 -1
  44. package/dist/fieldwork-BrfoehvG.d.ts +0 -113
  45. package/dist/path-DL5P8XH2.js +0 -17
  46. package/dist/util-DhYr1OS3.d.ts +0 -1
  47. package/dist/{errors-DkFJysIM.js → errors-gpxg6Tnh.js} +5 -5
package/dist/firecrawl.js CHANGED
@@ -1,12 +1,12 @@
1
- import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
- import { r as invalidRequest, t as FieldworkError } from "./errors-DkFJysIM.js";
3
- import { C as createRawClient, E as segment, 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, l as optionalBoolean, m as optionalScalar, n as anything, p as optionalObject, r as arrayOf, s as optionalAnyString, u as optionalFirstString, v as recordOf } from "./parse-Q7H4mrnO.js";
4
- import { i as startJob, n as requireOutput, r as runJob, t as jobState } from "./job-DnavRq_s.js";
5
- import { n as jsonSchemaOf, t as checkOutput } from "./schema--iU4AXSM.js";
6
- import { a as compact, f as refuseTogether, l as presentPage, p as requireJobId, s as meta, t as callSettings, u as presentPages } from "./util-DFUXQX6v.js";
7
- import { a as presentFile, n as byteLimit, o as tooLarge, r as checkFileUrl, t as MIB } from "./download-CP8noBdX.js";
8
- import { a as mediaTypeOf, n as documentPart, o as refuseLarger, t as MEDIA_TYPES } from "./document-DMIUCoDA.js";
9
- import * as z from "zod/mini";
1
+ import { t as defineAdapter } from "./adapter-CBSAfErv.js";
2
+ import { r as invalidRequest, t as FieldworkError } from "./errors-gpxg6Tnh.js";
3
+ import { E as warningEntry, O as withOriginal, _ as optionalId, b as optionalScalar, c as anything, d as looseObject, g as optionalFirstString, h as optionalBoolean, i as segment, l as arrayOf, m as optionalArrayOf, p as optionalAnyString, r as requireKey, t as createRawClient, u as both, v as optionalNumber, w as recordOf, x as optionalString, y as optionalObject } from "./http-CJcvTPnE.js";
4
+ import { i as startJob, n as requireOutput, r as runJob, t as jobState } from "./job-JLEpszjr.js";
5
+ import { n as jsonSchemaOf, t as checkOutput } from "./schema-CJXFAZ-x.js";
6
+ import { a as compact, d as refuseTogether, f as requireJobId, l as presentPage, s as meta, t as callSettings, u as presentPages } from "./util-LvME_uOj.js";
7
+ import { a as mediaTypeOf, n as documentPart, o as refuseLarger, t as MEDIA_TYPES } from "./document-BSCwJgBM.js";
8
+ import { a as presentFile, n as byteLimit, o as tooLarge, r as checkFileUrl, t as MIB } from "./download-kuTqNnuZ.js";
9
+ import * as z$1 from "zod/mini";
10
10
  // src/adapters/firecrawl/shared.ts
11
11
  const provider = "firecrawl";
12
12
  /** A country code in upper case, as sent to Firecrawl. */
@@ -643,14 +643,14 @@ const documentBlocks = (pages) => pages.flatMap((entry) => {
643
643
  const parseResult = (body) => {
644
644
  const { data } = body;
645
645
  return compact({
646
+ blocks: data.blocks && documentBlocks(data.blocks),
646
647
  markdown: data.markdown ?? "",
648
+ meta: pageMeta(data, body.warning.notes),
649
+ pageCount: data.metadata.totalPages ?? data.metadata.numPages,
647
650
  pages: data.pages?.map((page) => ({
648
651
  markdown: page.markdown ?? "",
649
652
  pageNumber: Number(page.pageNumber)
650
- })),
651
- blocks: data.blocks && documentBlocks(data.blocks),
652
- pageCount: data.metadata.totalPages ?? data.metadata.numPages,
653
- meta: pageMeta(data, body.warning.notes)
653
+ }))
654
654
  });
655
655
  };
656
656
  /** What a monitor watches: its goal, else its target URLs or queries joined with commas. */
@@ -726,18 +726,18 @@ const usageResult = (body) => compact({
726
726
  * Warnings as text: a string is one warning (an empty one too); an array gives
727
727
  * every entry as a string, whatever it is; anything else gives none.
728
728
  */
729
- const Notes = z.union([z.pipe(z.string(), z.transform((note) => [note])), arrayOf(z.pipe(z.unknown(), z.transform(String)))]);
729
+ const Notes = z$1.union([z$1.pipe(z$1.string(), z$1.transform((note) => [note])), arrayOf(z$1.pipe(z$1.unknown(), z$1.transform(String)))]);
730
730
  /** A warning, as its text when it is a non-empty string and as the list of warnings it amounts to. */
731
- const Warning = z.pipe(both(optionalString, Notes), z.transform(({ first, second }) => ({
731
+ const Warning = z$1.pipe(both(optionalString, Notes), z$1.transform(({ first, second }) => ({
732
732
  notes: second,
733
733
  text: first
734
734
  })));
735
735
  /** A product image: a bare URL, or an object with a URL (or `src`) and a description. One without a URL reads as undefined. */
736
- const Image = z.union([z.pipe(z.string(), z.transform((url) => url === "" ? void 0 : { url })), z.pipe(looseObject({
736
+ const Image = z$1.union([z$1.pipe(z$1.string(), z$1.transform((url) => url === "" ? void 0 : { url })), z$1.pipe(looseObject({
737
737
  alt: optionalString,
738
738
  src: optionalString,
739
739
  url: optionalString
740
- }), z.transform((image) => {
740
+ }), z$1.transform((image) => {
741
741
  const url = image.url ?? image.src;
742
742
  return url === void 0 ? void 0 : compact({
743
743
  alt: image.alt,
@@ -792,14 +792,14 @@ const metadataShape = {
792
792
  /** What a scrape returns for one page. `json` is kept as it arrived. */
793
793
  const PageData = looseObject({
794
794
  answer: optionalString,
795
- highlights: z.pipe(both(optionalString, arrayOf(z.string())), z.transform(({ first, second }) => ({
795
+ highlights: z$1.pipe(both(optionalString, arrayOf(z$1.string())), z$1.transform(({ first, second }) => ({
796
796
  list: second,
797
797
  text: first
798
798
  }))),
799
799
  html: optionalString,
800
- images: arrayOf(z.string()),
800
+ images: arrayOf(z$1.string()),
801
801
  json: anything,
802
- links: arrayOf(z.string()),
802
+ links: arrayOf(z$1.string()),
803
803
  markdown: optionalString,
804
804
  metadata: looseObject(metadataShape),
805
805
  product: optionalObject({
@@ -838,14 +838,14 @@ const BatchErrors = withOriginal(looseObject({
838
838
  error: optionalString,
839
839
  url: optionalString
840
840
  })),
841
- robotsBlocked: arrayOf(z.string())
841
+ robotsBlocked: arrayOf(z$1.string())
842
842
  }));
843
843
  /** The reply to starting a crawl. */
844
844
  const CrawlStart = looseObject({ id: withOriginal(optionalId) });
845
845
  /** The reply to starting a batch scrape or an agent run, beside the response as it arrived. */
846
846
  const RunStart = withOriginal(looseObject({
847
847
  id: withOriginal(optionalId),
848
- invalidURLs: arrayOf(z.string()),
848
+ invalidURLs: arrayOf(z$1.string()),
849
849
  threadId: optionalString
850
850
  }));
851
851
  /** An agent run while it is polled. */
@@ -853,7 +853,7 @@ const AgentRun = withOriginal(looseObject({
853
853
  creditsUsed: optionalNumber,
854
854
  data: anything,
855
855
  error: optionalString,
856
- message: z.pipe(both(anything, warningEntry), z.transform(({ first, second }) => ({
856
+ message: z$1.pipe(both(anything, warningEntry), z$1.transform(({ first, second }) => ({
857
857
  note: second,
858
858
  value: first
859
859
  }))),
@@ -923,11 +923,11 @@ const SearchResponse = looseObject({
923
923
  warnings: Notes
924
924
  });
925
925
  /** `/map`: each link is a bare URL or an object. */
926
- const MapResponse = looseObject({ links: arrayOf(z.union([z.pipe(z.string(), z.transform((url) => ({ url }))), z.pipe(looseObject({
926
+ const MapResponse = looseObject({ links: arrayOf(z$1.union([z$1.pipe(z$1.string(), z$1.transform((url) => ({ url }))), z$1.pipe(looseObject({
927
927
  description: optionalString,
928
928
  title: optionalString,
929
929
  url: optionalString
930
- }), z.transform((link) => compact({
930
+ }), z$1.transform((link) => compact({
931
931
  description: link.description,
932
932
  title: link.title,
933
933
  url: link.url ?? ""
@@ -943,10 +943,10 @@ const Monitor = looseObject({
943
943
  }),
944
944
  status: optionalString,
945
945
  targets: arrayOf(looseObject({
946
- queries: arrayOf(z.string()),
946
+ queries: arrayOf(z$1.string()),
947
947
  type: optionalString,
948
948
  url: optionalString,
949
- urls: arrayOf(z.string())
949
+ urls: arrayOf(z$1.string())
950
950
  })),
951
951
  webhook: looseObject({ url: optionalString })
952
952
  });
@@ -976,7 +976,7 @@ const ChecksResponse = looseObject({ data: arrayOf(withOriginal(looseObject({
976
976
  /** A page of `/parse` blocks; each box is `[x0, y0, x1, y1]` in fractions of the page. */
977
977
  const ParsePage = looseObject({
978
978
  items: arrayOf(looseObject({
979
- bbox: arrayOf(z.number()),
979
+ bbox: arrayOf(z$1.number()),
980
980
  content: optionalAnyString,
981
981
  type: optionalString
982
982
  })),
@@ -1002,15 +1002,138 @@ const UsageResponse = looseObject({ data: looseObject({
1002
1002
  planCredits: optionalNumber,
1003
1003
  remainingCredits: optionalNumber
1004
1004
  }) });
1005
+ // src/adapters/firecrawl/batch.ts
1006
+ /** The path of a `next` link, absolute or relative to the base URL, so the next page of results goes through the same client. */
1007
+ const pathOf = (baseUrl, link) => {
1008
+ const base = new URL(`${baseUrl.replace(/\/$/u, "")}/`);
1009
+ const next = new URL(link, base);
1010
+ return next.pathname.slice(base.pathname.length - 1) + next.search;
1011
+ };
1012
+ /**
1013
+ * This page of results and every one after it, in order: each `next` link is
1014
+ * followed only once the page that names it has come back.
1015
+ */
1016
+ const readBatches = async (raw, baseUrl, batch, request) => {
1017
+ const { next } = batch.value;
1018
+ if (next === void 0) return [batch];
1019
+ const following = z$1.parse(Batch, await raw.request("GET", pathOf(baseUrl, next), request));
1020
+ return [batch, ...await readBatches(raw, baseUrl, following, request)];
1021
+ };
1022
+ /**
1023
+ * Runs a crawl or batch scrape: waits for it, then reads every page of its
1024
+ * results and the pages that failed.
1025
+ */
1026
+ const batchJob = async (raw, baseUrl, kind, start, settings, finish) => await runJob(provider, {
1027
+ check: async (id, request) => batchState(kind, id, z$1.parse(Batch, await raw.request("GET", `/${kind}/${segment(id)}`, request))),
1028
+ finish: async (first, id) => {
1029
+ const path = `/${kind}/${segment(id)}`;
1030
+ const request = {
1031
+ retries: settings.retries,
1032
+ signal: settings.signal
1033
+ };
1034
+ const batches = await readBatches(raw, baseUrl, first, request);
1035
+ const errors = z$1.parse(BatchErrors, await raw.request("GET", `${path}/errors`, request));
1036
+ return finish({
1037
+ batches,
1038
+ errors,
1039
+ failed: failedPages(errors),
1040
+ first
1041
+ }, id);
1042
+ },
1043
+ start
1044
+ }, settings);
1045
+ /** `crawl` and `readMany`, the two batch jobs, calling through `raw`. */
1046
+ const batching = (raw, baseUrl) => ({
1047
+ async crawl(url, options = {}) {
1048
+ const { call, rest: o } = callSettings(options);
1049
+ return await batchJob(raw, baseUrl, "crawl", async () => await startJob(raw, "/crawl", {
1050
+ ...call,
1051
+ body: crawlBody(url, o)
1052
+ }, CrawlStart, (reply) => reply.id), {
1053
+ ...call,
1054
+ interval: o.interval,
1055
+ resume: o.resume
1056
+ }, (job, id) => {
1057
+ const { robotsBlocked } = job.errors.value;
1058
+ const { pages, gone } = presentPages(job.batches.flatMap((batch) => batch.value.data.map((item) => ({
1059
+ ...toPage(item.value, url),
1060
+ raw: item.original
1061
+ }))));
1062
+ return compact({
1063
+ failed: [...job.failed, ...gone],
1064
+ id,
1065
+ meta: meta({
1066
+ credits: job.first.value.creditsUsed,
1067
+ requestId: id
1068
+ }),
1069
+ pages,
1070
+ raw: {
1071
+ batches: job.batches.map((batch) => batch.original),
1072
+ errors: job.errors.original
1073
+ },
1074
+ robotsBlocked: robotsBlocked.length > 0 ? robotsBlocked : void 0,
1075
+ total: job.first.value.total
1076
+ });
1077
+ });
1078
+ },
1079
+ async readMany(urls, options = {}) {
1080
+ const { call, rest: o } = callSettings(options);
1081
+ const { interval, resume, maxConcurrency, ignoreInvalidURLs, ...read } = o;
1082
+ let started = z$1.parse(RunStart, {});
1083
+ return await batchJob(raw, baseUrl, "batch/scrape", async () => await startJob(raw, "/batch/scrape", {
1084
+ ...call,
1085
+ body: compact({
1086
+ urls,
1087
+ ...readBody(read),
1088
+ ignoreInvalidURLs,
1089
+ maxConcurrency
1090
+ })
1091
+ }, RunStart, (reply) => {
1092
+ started = reply;
1093
+ return reply.value.id;
1094
+ }), {
1095
+ ...call,
1096
+ interval,
1097
+ resume
1098
+ }, (job, id) => {
1099
+ const rejected = started.value.invalidURLs.map((url) => ({
1100
+ error: "invalid URL",
1101
+ url
1102
+ }));
1103
+ const { pages, gone } = presentPages(job.batches.flatMap((batch) => batch.value.data.map((item) => ({
1104
+ ...toPage(item.value, ""),
1105
+ raw: item.original
1106
+ }))));
1107
+ return compact({
1108
+ failed: [
1109
+ ...job.failed,
1110
+ ...rejected,
1111
+ ...gone
1112
+ ],
1113
+ id,
1114
+ meta: meta({
1115
+ credits: job.first.value.creditsUsed,
1116
+ requestId: id
1117
+ }),
1118
+ pages,
1119
+ raw: {
1120
+ batches: job.batches.map((batch) => batch.original),
1121
+ errors: job.errors.original,
1122
+ started: started.original
1123
+ }
1124
+ });
1125
+ });
1126
+ }
1127
+ });
1005
1128
  // src/adapters/firecrawl/download.ts
1006
1129
  /** The largest file Firecrawl's scrape returns: 50 MiB. */
1007
1130
  const DOWNLOAD_CEILING = 50 * MIB;
1008
1131
  /** The part of Firecrawl's error body that names the failure. */
1009
1132
  const ErrorBody = looseObject({ code: optionalString });
1010
1133
  /** Whether Firecrawl refused the file for exceeding its size limit. */
1011
- const overCeiling = (error) => z.parse(ErrorBody, error.cause).code === "SCRAPE_UNSUPPORTED_FILE_ERROR" && error.message.includes("size limit");
1134
+ const overCeiling = (error) => z$1.parse(ErrorBody, error.cause).code === "SCRAPE_UNSUPPORTED_FILE_ERROR" && error.message.includes("size limit");
1012
1135
  /** Fetches the file through Firecrawl's scrape and checks it. */
1013
- const downloadFile = async (raw, url, options) => {
1136
+ const downloadFile = async (raw, url, options = {}) => {
1014
1137
  const { provider } = raw;
1015
1138
  const { call, rest: o } = callSettings(options);
1016
1139
  checkFileUrl(provider, url);
@@ -1033,7 +1156,7 @@ const downloadFile = async (raw, url, options) => {
1033
1156
  } catch (error) {
1034
1157
  throw error instanceof FieldworkError && overCeiling(error) ? tooLarge(provider, url, void 0, limit) : error;
1035
1158
  }
1036
- const { data, warning } = z.parse(ScrapeResponse, response);
1159
+ const { data, warning } = z$1.parse(ScrapeResponse, response);
1037
1160
  const { metadata } = data;
1038
1161
  const meta = pageMeta(data, warning.notes);
1039
1162
  if (data.rawBase64 === void 0) throw new FieldworkError("ProviderError", `firecrawl downloaded ${url} but returned no rawBase64 content`, {
@@ -1051,11 +1174,297 @@ const downloadFile = async (raw, url, options) => {
1051
1174
  url: metadata.url ?? url
1052
1175
  }, limit);
1053
1176
  };
1054
- // src/adapters/firecrawl.ts
1177
+ // src/adapters/firecrawl/monitor.ts
1178
+ /**
1179
+ * Every monitor from `offset` on, one page after another: the next page is
1180
+ * requested only once this one came back full.
1181
+ */
1182
+ const listMonitors = async (raw, call, offset) => {
1183
+ const page = z$1.parse(MonitorsResponse, await raw.request("GET", "/monitor", {
1184
+ ...call,
1185
+ query: {
1186
+ limit: 100,
1187
+ offset
1188
+ }
1189
+ })).data;
1190
+ const monitors = page.map((entry) => monitorInfo(entry));
1191
+ if (page.length < 100) return monitors;
1192
+ return [...monitors, ...await listMonitors(raw, call, offset + monitors.length)];
1193
+ };
1194
+ /** Firecrawl's monitor methods, calling through `raw`. */
1195
+ const firecrawlMonitor = (raw) => ({
1196
+ async create(options) {
1197
+ const { call, rest: o } = callSettings(options);
1198
+ const response = z$1.parse(MonitorResponse, await raw.request("POST", "/monitor", {
1199
+ creates: true,
1200
+ ...call,
1201
+ body: monitorBody(o)
1202
+ }));
1203
+ return monitorInfo(response.data);
1204
+ },
1205
+ async delete(id, options = {}) {
1206
+ const { call } = callSettings(options);
1207
+ await raw.request("DELETE", `/monitor/${segment(id)}`, call);
1208
+ },
1209
+ async events(id, options = {}) {
1210
+ const { call, rest: o } = callSettings(options);
1211
+ const offset = Number(o.cursor ?? 0);
1212
+ if (!Number.isInteger(offset) || offset < 0) throw invalidRequest(provider, `events cursor "${o.cursor}" is not valid`);
1213
+ const response = await raw.request("GET", `/monitor/${segment(id)}/checks`, {
1214
+ ...call,
1215
+ query: {
1216
+ limit: 100,
1217
+ offset
1218
+ }
1219
+ });
1220
+ return {
1221
+ ...monitorEvents(z$1.parse(ChecksResponse, response).data, offset),
1222
+ raw: response
1223
+ };
1224
+ },
1225
+ async get(id, options = {}) {
1226
+ const { call } = callSettings(options);
1227
+ const response = z$1.parse(MonitorResponse, await raw.request("GET", `/monitor/${segment(id)}`, call));
1228
+ return monitorInfo(response.data);
1229
+ },
1230
+ async list(options = {}) {
1231
+ const { call } = callSettings(options);
1232
+ return await listMonitors(raw, call, 0);
1233
+ }
1234
+ });
1235
+ // src/adapters/firecrawl/session.ts
1055
1236
  /** How long closing a session may take, apart from the call's own deadline. */
1056
1237
  const CLOSE_TIMEOUT = 15e3;
1238
+ /** Opens a browser session. Only a rate limit is retried, since after any other failure the session may already be open and billing. */
1239
+ const openSession = async (raw, o, call) => {
1240
+ const session = z$1.parse(Session, await raw.request("POST", "/interact", {
1241
+ body: sessionBody(o),
1242
+ creates: true,
1243
+ retries: call.retries,
1244
+ signal: call.signal
1245
+ }));
1246
+ return {
1247
+ id: requireJobId(provider, session.value.id),
1248
+ session
1249
+ };
1250
+ };
1057
1251
  /**
1058
- * An adapter for Firecrawl: search, images, read, readMany, extract, product, map, crawl, research, act, browser, parse, download, monitor and usage. Pass it to `new Fieldwork({ adapter })`.
1252
+ * Closes a session so it stops billing. It runs on its own deadline, so a
1253
+ * call that was cancelled or timed out still closes what it opened. A
1254
+ * failure is returned rather than thrown: the caller reports it with the
1255
+ * session id, so the session can still be closed by hand.
1256
+ */
1257
+ const closeSession = async (raw, id, call) => {
1258
+ try {
1259
+ return {
1260
+ closed: z$1.parse(Closed, await raw.request("DELETE", `/interact/${segment(id)}`, {
1261
+ retries: call.retries,
1262
+ signal: AbortSignal.timeout(CLOSE_TIMEOUT)
1263
+ })),
1264
+ failure: void 0
1265
+ };
1266
+ } catch (error) {
1267
+ return {
1268
+ closed: void 0,
1269
+ failure: `firecrawl could not close session ${id}, which may still bill: ${error instanceof Error ? error.message : String(error)}. Close it with DELETE /interact/${id}`
1270
+ };
1271
+ }
1272
+ };
1273
+ /** `act` and `browser`, calling through `raw`. */
1274
+ const browsing = (raw) => ({
1275
+ async act(code, options = {}) {
1276
+ const { call, rest: o } = callSettings(options, REPORT_GRACE_MS);
1277
+ const seconds = checkAct(o, call.timeout);
1278
+ const created = o.session === void 0;
1279
+ const keep = o.keepSession ?? !created;
1280
+ const { id } = o.session === void 0 ? await openSession(raw, o, call) : { id: o.session };
1281
+ try {
1282
+ const result = z$1.parse(Execution, await raw.request("POST", `/interact/${segment(id)}/execute`, {
1283
+ ...scriptRequest(code, o.language, call, seconds),
1284
+ creates: true
1285
+ }));
1286
+ if (keep) return actResult(result, id, {});
1287
+ const close = await closeSession(raw, id, call);
1288
+ return actResult(result, close.failure === void 0 ? void 0 : id, close);
1289
+ } catch (error) {
1290
+ if (!created && keep) throw error;
1291
+ const close = await closeSession(raw, id, call);
1292
+ if (close.failure === void 0 || !(error instanceof FieldworkError)) throw error;
1293
+ throw new FieldworkError(error.code, `${error.message}; ${close.failure}`, {
1294
+ cause: error,
1295
+ provider,
1296
+ status: error.status
1297
+ });
1298
+ }
1299
+ },
1300
+ browser: {
1301
+ async close(id, options = {}) {
1302
+ const { call } = callSettings(options);
1303
+ await raw.request("DELETE", `/interact/${segment(id)}`, call);
1304
+ },
1305
+ async open(options = {}) {
1306
+ const { call, rest: o } = callSettings(options);
1307
+ const { session } = await openSession(raw, o, call);
1308
+ return browserSession(session);
1309
+ }
1310
+ }
1311
+ });
1312
+ // src/adapters/firecrawl.ts
1313
+ /** Scrapes one URL with the formats and page settings given. */
1314
+ const scrape = async (raw, url, formats, settings, call) => {
1315
+ const response = await raw.request("POST", "/scrape", {
1316
+ ...call,
1317
+ body: {
1318
+ formats,
1319
+ url,
1320
+ ...pageBody(settings)
1321
+ }
1322
+ });
1323
+ const body = z$1.parse(ScrapeResponse, response);
1324
+ return {
1325
+ body,
1326
+ data: body.data,
1327
+ response
1328
+ };
1329
+ };
1330
+ /** `read`, `extract` and `product`: one scrape each. */
1331
+ const scraping = (raw) => ({
1332
+ async extract(url, options) {
1333
+ const { call, rest: o } = callSettings(options);
1334
+ const { schema, prompt, ...page } = o;
1335
+ const { body, response, data } = await scrape(raw, url, [compact({
1336
+ prompt,
1337
+ schema: jsonSchemaOf(schema),
1338
+ type: "json"
1339
+ })], page, call);
1340
+ presentPage(provider, {
1341
+ ...toPage(data, url),
1342
+ raw: response
1343
+ });
1344
+ if (data.json === void 0) {
1345
+ const why = data.warning.text;
1346
+ throw new FieldworkError("ProviderError", `firecrawl returned no JSON for ${url}${why === void 0 ? "" : `: ${why}`}`, {
1347
+ cause: response,
1348
+ provider
1349
+ });
1350
+ }
1351
+ return compact({
1352
+ data: await checkOutput(schema, data.json, { provider }),
1353
+ meta: pageMeta(data, body.warning.notes),
1354
+ raw: response
1355
+ });
1356
+ },
1357
+ async product(url, options = {}) {
1358
+ const { call, rest: o } = callSettings(options);
1359
+ const { body, response } = await scrape(raw, url, ["product"], o, call);
1360
+ const product = toProduct(body);
1361
+ if (product === void 0) {
1362
+ const why = noProductReason(body);
1363
+ throw new FieldworkError("NotFound", `firecrawl found no product on ${url}${why === void 0 ? "" : `: ${why}`}`, {
1364
+ cause: response,
1365
+ provider
1366
+ });
1367
+ }
1368
+ return {
1369
+ ...product,
1370
+ raw: response
1371
+ };
1372
+ },
1373
+ async read(url, options = {}) {
1374
+ const { call, rest: o } = callSettings(options);
1375
+ const { body, data, response } = await scrape(raw, url, readFormats(o), o, call);
1376
+ return presentPage(provider, {
1377
+ ...toPage(data, url, body.warning.notes),
1378
+ raw: response
1379
+ });
1380
+ }
1381
+ });
1382
+ /** The single-request operations: `search`, `images`, `map`, `parse`, `download` and `usage`. */
1383
+ const requesting = (raw) => ({
1384
+ download: async (url, options) => await downloadFile(raw, url, options),
1385
+ async images(query, options = {}) {
1386
+ const { call, rest: o } = callSettings(options);
1387
+ const response = await raw.request("POST", "/search", {
1388
+ ...call,
1389
+ body: imagesBody(query, o)
1390
+ });
1391
+ return {
1392
+ ...imagesResult(z$1.parse(SearchResponse, response)),
1393
+ raw: response
1394
+ };
1395
+ },
1396
+ async map(url, options = {}) {
1397
+ const { call, rest: o } = callSettings(options);
1398
+ const response = await raw.request("POST", "/map", {
1399
+ ...call,
1400
+ body: mapBody(url, o)
1401
+ });
1402
+ return {
1403
+ links: z$1.parse(MapResponse, response).links,
1404
+ raw: response
1405
+ };
1406
+ },
1407
+ async parse(document, options = {}) {
1408
+ const { call, rest: o } = callSettings(options, REPORT_GRACE_MS);
1409
+ const form = parseForm(document, o, call.timeout);
1410
+ const response = await raw.request("POST", "/parse", {
1411
+ ...call,
1412
+ form,
1413
+ timeout: call.timeout === void 0 ? void 0 : call.timeout + REPORT_GRACE_MS
1414
+ });
1415
+ return {
1416
+ ...parseResult(z$1.parse(ParseResponse, response)),
1417
+ raw: response
1418
+ };
1419
+ },
1420
+ async search(query, options = {}) {
1421
+ const { call, rest: o } = callSettings(options);
1422
+ const response = await raw.request("POST", "/search", {
1423
+ ...call,
1424
+ body: searchBody(query, o)
1425
+ });
1426
+ return {
1427
+ ...searchResult(z$1.parse(SearchResponse, response)),
1428
+ raw: response
1429
+ };
1430
+ },
1431
+ async usage(options = {}) {
1432
+ const { call } = callSettings(options);
1433
+ const response = await raw.request("GET", "/team/credit-usage", call);
1434
+ return {
1435
+ ...usageResult(z$1.parse(UsageResponse, response)),
1436
+ raw: response
1437
+ };
1438
+ }
1439
+ });
1440
+ /** `research`: a run Firecrawl's agent works through, polled to its result. */
1441
+ const researching = (raw) => ({ async research(question, options = {}) {
1442
+ const { call, rest: o } = callSettings(options);
1443
+ let started = z$1.parse(RunStart, {});
1444
+ return await runJob(provider, {
1445
+ check: async (id, request) => researchState(id, z$1.parse(AgentRun, await raw.request("GET", `/agent/${segment(id)}`, request))),
1446
+ finish: async (run, id) => {
1447
+ const result = researchResult(id, started, run);
1448
+ return {
1449
+ ...result,
1450
+ output: await checkOutput(o.schema, result.output, { provider })
1451
+ };
1452
+ },
1453
+ start: async () => await startJob(raw, "/agent", {
1454
+ ...call,
1455
+ body: researchBody(question, o)
1456
+ }, RunStart, (reply) => {
1457
+ started = reply;
1458
+ return reply.value.id;
1459
+ })
1460
+ }, {
1461
+ ...call,
1462
+ interval: o.interval,
1463
+ resume: o.resume
1464
+ });
1465
+ } });
1466
+ /**
1467
+ * An adapter for Firecrawl: search, images, read, readMany, extract, product, map, crawl, research, act, browser, parse, download, monitor and usage. Pass it to `fieldwork({ adapter })`.
1059
1468
  *
1060
1469
  * Throws `Unauthorized` when neither `apiKey` nor `FIRECRAWL_API_KEY` is set.
1061
1470
  */
@@ -1068,393 +1477,17 @@ const firecrawl = (config = {}) => {
1068
1477
  provider,
1069
1478
  retries: config.retries
1070
1479
  });
1071
- /** Scrapes one URL with the formats and page settings given. */
1072
- const scrape = async (url, formats, settings, call) => {
1073
- const response = await raw.request("POST", "/scrape", {
1074
- ...call,
1075
- body: {
1076
- formats,
1077
- url,
1078
- ...pageBody(settings)
1079
- }
1080
- });
1081
- const body = z.parse(ScrapeResponse, response);
1082
- return {
1083
- body,
1084
- data: body.data,
1085
- response
1086
- };
1087
- };
1088
- /** The path of a `next` link, absolute or relative to the base URL, so the next page of results goes through the same client. */
1089
- const pathOf = (link) => {
1090
- const base = new URL(`${baseUrl.replace(/\/$/u, "")}/`);
1091
- const next = new URL(link, base);
1092
- return next.pathname.slice(base.pathname.length - 1) + next.search;
1093
- };
1094
- /**
1095
- * Runs a crawl or batch scrape: waits for it, then reads every page of its
1096
- * results and the pages that failed.
1097
- */
1098
- const batchJob = async (kind, start, settings, finish) => await runJob(provider, {
1099
- check: async (id, request) => batchState(kind, id, z.parse(Batch, await raw.request("GET", `/${kind}/${segment(id)}`, request))),
1100
- finish: async (first, id) => {
1101
- const path = `/${kind}/${segment(id)}`;
1102
- const request = {
1103
- retries: settings.retries,
1104
- signal: settings.signal
1105
- };
1106
- const batches = [first];
1107
- let { next } = first.value;
1108
- while (next !== void 0) {
1109
- const batch = z.parse(Batch, await raw.request("GET", pathOf(next), request));
1110
- batches.push(batch);
1111
- ({next} = batch.value);
1112
- }
1113
- const errors = z.parse(BatchErrors, await raw.request("GET", `${path}/errors`, request));
1114
- return finish({
1115
- batches,
1116
- errors,
1117
- failed: failedPages(errors),
1118
- first
1119
- }, id);
1120
- },
1121
- start
1122
- }, settings);
1123
- /** Opens a browser session. Only a rate limit is retried, since after any other failure the session may already be open and billing. */
1124
- const openSession = async (o, call) => {
1125
- const session = z.parse(Session, await raw.request("POST", "/interact", {
1126
- body: sessionBody(o),
1127
- creates: true,
1128
- retries: call.retries,
1129
- signal: call.signal
1130
- }));
1131
- return {
1132
- id: requireJobId(provider, session.value.id),
1133
- session
1134
- };
1135
- };
1136
- /**
1137
- * Closes a session so it stops billing. It runs on its own deadline, so a
1138
- * call that was cancelled or timed out still closes what it opened. A
1139
- * failure is returned rather than thrown: the caller reports it with the
1140
- * session id, so the session can still be closed by hand.
1141
- */
1142
- const closeSession = async (id, call) => {
1143
- try {
1144
- return {
1145
- closed: z.parse(Closed, await raw.request("DELETE", `/interact/${segment(id)}`, {
1146
- retries: call.retries,
1147
- signal: AbortSignal.timeout(CLOSE_TIMEOUT)
1148
- })),
1149
- failure: void 0
1150
- };
1151
- } catch (error) {
1152
- return {
1153
- closed: void 0,
1154
- failure: `firecrawl could not close session ${id}, which may still bill: ${error instanceof Error ? error.message : String(error)}. Close it with DELETE /interact/${id}`
1155
- };
1156
- }
1480
+ const operations = {
1481
+ ...batching(raw, baseUrl),
1482
+ ...browsing(raw),
1483
+ ...requesting(raw),
1484
+ ...researching(raw),
1485
+ ...scraping(raw),
1486
+ monitor: firecrawlMonitor(raw)
1157
1487
  };
1158
1488
  return defineAdapter({
1159
1489
  name: provider,
1160
- operations: {
1161
- async act(code, options) {
1162
- const { call, rest: o } = callSettings(options, REPORT_GRACE_MS);
1163
- const seconds = checkAct(o, call.timeout);
1164
- const created = o.session === void 0;
1165
- const keep = o.keepSession ?? !created;
1166
- const { id } = o.session === void 0 ? await openSession(o, call) : { id: o.session };
1167
- try {
1168
- const result = z.parse(Execution, await raw.request("POST", `/interact/${segment(id)}/execute`, {
1169
- ...scriptRequest(code, o.language, call, seconds),
1170
- creates: true
1171
- }));
1172
- if (keep) return actResult(result, id, {});
1173
- const close = await closeSession(id, call);
1174
- return actResult(result, close.failure === void 0 ? void 0 : id, close);
1175
- } catch (error) {
1176
- if (!created && keep) throw error;
1177
- const close = await closeSession(id, call);
1178
- if (close.failure === void 0 || !(error instanceof FieldworkError)) throw error;
1179
- throw new FieldworkError(error.code, `${error.message}; ${close.failure}`, {
1180
- cause: error,
1181
- provider,
1182
- status: error.status
1183
- });
1184
- }
1185
- },
1186
- browser: {
1187
- async close(id, options) {
1188
- const { call } = callSettings(options);
1189
- await raw.request("DELETE", `/interact/${segment(id)}`, call);
1190
- },
1191
- async open(options) {
1192
- const { call, rest: o } = callSettings(options);
1193
- const { session } = await openSession(o, call);
1194
- return browserSession(session);
1195
- }
1196
- },
1197
- async crawl(url, options) {
1198
- const { call, rest: o } = callSettings(options);
1199
- return await batchJob("crawl", async () => await startJob(raw, "/crawl", {
1200
- ...call,
1201
- body: crawlBody(url, o)
1202
- }, CrawlStart, (reply) => reply.id), {
1203
- ...call,
1204
- interval: o.interval,
1205
- resume: o.resume
1206
- }, (job, id) => {
1207
- const { robotsBlocked } = job.errors.value;
1208
- const { pages, gone } = presentPages(job.batches.flatMap((batch) => batch.value.data.map((item) => ({
1209
- ...toPage(item.value, url),
1210
- raw: item.original
1211
- }))));
1212
- return compact({
1213
- failed: [...job.failed, ...gone],
1214
- id,
1215
- meta: meta({
1216
- credits: job.first.value.creditsUsed,
1217
- requestId: id
1218
- }),
1219
- pages,
1220
- raw: {
1221
- batches: job.batches.map((batch) => batch.original),
1222
- errors: job.errors.original
1223
- },
1224
- robotsBlocked: robotsBlocked.length > 0 ? robotsBlocked : void 0,
1225
- total: job.first.value.total
1226
- });
1227
- });
1228
- },
1229
- download: async (url, options) => await downloadFile(raw, url, options),
1230
- async extract(url, options) {
1231
- const { call, rest: o } = callSettings(options);
1232
- const { schema, prompt, ...page } = o;
1233
- const { body, response, data } = await scrape(url, [compact({
1234
- prompt,
1235
- schema: jsonSchemaOf(schema),
1236
- type: "json"
1237
- })], page, call);
1238
- presentPage(provider, {
1239
- ...toPage(data, url),
1240
- raw: response
1241
- });
1242
- if (data.json === void 0) {
1243
- const why = data.warning.text;
1244
- throw new FieldworkError("ProviderError", `firecrawl returned no JSON for ${url}${why === void 0 ? "" : `: ${why}`}`, {
1245
- cause: response,
1246
- provider
1247
- });
1248
- }
1249
- return compact({
1250
- data: await checkOutput(schema, data.json, { provider }),
1251
- meta: pageMeta(data, body.warning.notes),
1252
- raw: response
1253
- });
1254
- },
1255
- async images(query, options) {
1256
- const { call, rest: o } = callSettings(options);
1257
- const response = await raw.request("POST", "/search", {
1258
- ...call,
1259
- body: imagesBody(query, o)
1260
- });
1261
- return {
1262
- ...imagesResult(z.parse(SearchResponse, response)),
1263
- raw: response
1264
- };
1265
- },
1266
- async map(url, options) {
1267
- const { call, rest: o } = callSettings(options);
1268
- const response = await raw.request("POST", "/map", {
1269
- ...call,
1270
- body: mapBody(url, o)
1271
- });
1272
- return {
1273
- links: z.parse(MapResponse, response).links,
1274
- raw: response
1275
- };
1276
- },
1277
- monitor: {
1278
- async create(options) {
1279
- const { call, rest: o } = callSettings(options);
1280
- const response = z.parse(MonitorResponse, await raw.request("POST", "/monitor", {
1281
- creates: true,
1282
- ...call,
1283
- body: monitorBody(o)
1284
- }));
1285
- return monitorInfo(response.data);
1286
- },
1287
- async delete(id, options) {
1288
- const { call } = callSettings(options);
1289
- await raw.request("DELETE", `/monitor/${segment(id)}`, call);
1290
- },
1291
- async events(id, options) {
1292
- const { call, rest: o } = callSettings(options);
1293
- const offset = Number(o.cursor ?? 0);
1294
- if (!Number.isInteger(offset) || offset < 0) throw invalidRequest(provider, `events cursor "${o.cursor}" is not valid`);
1295
- const response = await raw.request("GET", `/monitor/${segment(id)}/checks`, {
1296
- ...call,
1297
- query: {
1298
- limit: 100,
1299
- offset
1300
- }
1301
- });
1302
- return {
1303
- ...monitorEvents(z.parse(ChecksResponse, response).data, offset),
1304
- raw: response
1305
- };
1306
- },
1307
- async get(id, options) {
1308
- const { call } = callSettings(options);
1309
- const response = z.parse(MonitorResponse, await raw.request("GET", `/monitor/${segment(id)}`, call));
1310
- return monitorInfo(response.data);
1311
- },
1312
- async list(options) {
1313
- const { call } = callSettings(options);
1314
- const monitors = [];
1315
- for (;;) {
1316
- const page = z.parse(MonitorsResponse, await raw.request("GET", "/monitor", {
1317
- ...call,
1318
- query: {
1319
- limit: 100,
1320
- offset: monitors.length
1321
- }
1322
- })).data;
1323
- monitors.push(...page.map((entry) => monitorInfo(entry)));
1324
- if (page.length < 100) return monitors;
1325
- }
1326
- }
1327
- },
1328
- async parse(document, options) {
1329
- const { call, rest: o } = callSettings(options, REPORT_GRACE_MS);
1330
- const form = parseForm(document, o, call.timeout);
1331
- const response = await raw.request("POST", "/parse", {
1332
- ...call,
1333
- form,
1334
- timeout: call.timeout === void 0 ? void 0 : call.timeout + REPORT_GRACE_MS
1335
- });
1336
- return {
1337
- ...parseResult(z.parse(ParseResponse, response)),
1338
- raw: response
1339
- };
1340
- },
1341
- async product(url, options) {
1342
- const { call, rest: o } = callSettings(options);
1343
- const { body, response } = await scrape(url, ["product"], o, call);
1344
- const product = toProduct(body);
1345
- if (product === void 0) {
1346
- const why = noProductReason(body);
1347
- throw new FieldworkError("NotFound", `firecrawl found no product on ${url}${why === void 0 ? "" : `: ${why}`}`, {
1348
- cause: response,
1349
- provider
1350
- });
1351
- }
1352
- return {
1353
- ...product,
1354
- raw: response
1355
- };
1356
- },
1357
- async read(url, options) {
1358
- const { call, rest: o } = callSettings(options);
1359
- const { body, data, response } = await scrape(url, readFormats(o), o, call);
1360
- return presentPage(provider, {
1361
- ...toPage(data, url, body.warning.notes),
1362
- raw: response
1363
- });
1364
- },
1365
- async readMany(urls, options) {
1366
- const { call, rest: o } = callSettings(options);
1367
- const { interval, resume, maxConcurrency, ignoreInvalidURLs, ...read } = o;
1368
- let started = z.parse(RunStart, {});
1369
- return await batchJob("batch/scrape", async () => await startJob(raw, "/batch/scrape", {
1370
- ...call,
1371
- body: compact({
1372
- urls,
1373
- ...readBody(read),
1374
- maxConcurrency,
1375
- ignoreInvalidURLs
1376
- })
1377
- }, RunStart, (reply) => {
1378
- started = reply;
1379
- return reply.value.id;
1380
- }), {
1381
- ...call,
1382
- interval,
1383
- resume
1384
- }, (job, id) => {
1385
- const rejected = started.value.invalidURLs.map((url) => ({
1386
- error: "invalid URL",
1387
- url
1388
- }));
1389
- const { pages, gone } = presentPages(job.batches.flatMap((batch) => batch.value.data.map((item) => ({
1390
- ...toPage(item.value, ""),
1391
- raw: item.original
1392
- }))));
1393
- return compact({
1394
- failed: [
1395
- ...job.failed,
1396
- ...rejected,
1397
- ...gone
1398
- ],
1399
- id,
1400
- meta: meta({
1401
- credits: job.first.value.creditsUsed,
1402
- requestId: id
1403
- }),
1404
- pages,
1405
- raw: {
1406
- batches: job.batches.map((batch) => batch.original),
1407
- errors: job.errors.original,
1408
- started: started.original
1409
- }
1410
- });
1411
- });
1412
- },
1413
- async research(question, options) {
1414
- const { call, rest: o } = callSettings(options);
1415
- let started = z.parse(RunStart, {});
1416
- return await runJob(provider, {
1417
- check: async (id, request) => researchState(id, z.parse(AgentRun, await raw.request("GET", `/agent/${segment(id)}`, request))),
1418
- finish: async (run, id) => {
1419
- const result = researchResult(id, started, run);
1420
- return {
1421
- ...result,
1422
- output: await checkOutput(o.schema, result.output, { provider })
1423
- };
1424
- },
1425
- start: async () => await startJob(raw, "/agent", {
1426
- ...call,
1427
- body: researchBody(question, o)
1428
- }, RunStart, (reply) => {
1429
- started = reply;
1430
- return reply.value.id;
1431
- })
1432
- }, {
1433
- ...call,
1434
- interval: o.interval,
1435
- resume: o.resume
1436
- });
1437
- },
1438
- async search(query, options) {
1439
- const { call, rest: o } = callSettings(options);
1440
- const response = await raw.request("POST", "/search", {
1441
- ...call,
1442
- body: searchBody(query, o)
1443
- });
1444
- return {
1445
- ...searchResult(z.parse(SearchResponse, response)),
1446
- raw: response
1447
- };
1448
- },
1449
- async usage(options) {
1450
- const { call } = callSettings(options);
1451
- const response = await raw.request("GET", "/team/credit-usage", call);
1452
- return {
1453
- ...usageResult(z.parse(UsageResponse, response)),
1454
- raw: response
1455
- };
1456
- }
1457
- },
1490
+ operations,
1458
1491
  raw
1459
1492
  });
1460
1493
  };