@howells/fieldwork-sdk 0.5.1 → 0.5.2

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,13 @@
1
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";
2
+ import { r as invalidRequest, t as FieldworkError } from "./errors-DROZyb9T.js";
3
+ import { B as requireJobId, C as createRawClient, E as segment, I as presentPage, L as presentPages, M as compact, P as meta, S as withOriginal, T as requireKey, a as looseObject, b as warningEntry, c as optionalArrayOf, d as optionalId, f as optionalNumber, h as optionalString, i as both, k as callSettings, l as optionalBoolean, m as optionalScalar, n as anything, p as optionalObject, r as arrayOf, s as optionalAnyString, u as optionalFirstString, v as recordOf, z as refuseTogether } from "./parse-BY3R0oWO.js";
4
+ import { t as runJob } from "./job-DVsmQMKP.js";
5
+ import { n as jsonSchemaOf, t as checkOutput } from "./schema-BYcXgfuZ.js";
6
+ import { a as refuseLarger, i as mediaTypeOf, n as documentPart, t as MEDIA_TYPES } from "./document-CjMeBtV5.js";
7
7
  import * as z from "zod/mini";
8
8
  // src/adapters/firecrawl/shared.ts
9
9
  const provider = "firecrawl";
10
+ /** A country code in upper case, as sent to Firecrawl. */
10
11
  const country = (code) => code?.toUpperCase();
11
12
  // src/adapters/firecrawl/schedule.ts
12
13
  /** The fewest minutes Firecrawl allows between two checks of a monitor. */
@@ -16,6 +17,7 @@ const NAMED_CRON = /* @__PURE__ */ new Map([
16
17
  ["day", "0 0 * * *"],
17
18
  ["week", "0 0 * * 0"]
18
19
  ]);
20
+ /** The day counts that have a cron: every day, and every seven days (Sunday). */
19
21
  const DAILY_CRON = /* @__PURE__ */ new Map([[1, "0 0 * * *"], [7, "0 0 * * 0"]]);
20
22
  const CRON_PART = /^(?:\*|(?<from>\d+)(?:-(?<to>\d+))?)(?:\/(?<step>\d+))?$/u;
21
23
  const INTERVAL = /^(?<count>\d+)(?<unit>[hd])$/u;
@@ -23,6 +25,7 @@ const rangeEnd = (groups, wildcard, from, max) => {
23
25
  if (wildcard || groups.to === void 0 && groups.step !== void 0) return max;
24
26
  return groups.to === void 0 ? from : Number(groups.to);
25
27
  };
28
+ /** The sorted values a minute or hour field matches (lists, ranges and steps), or undefined for a field it cannot read, such as one with names. */
26
29
  const cronValues = (field, max) => {
27
30
  const values = /* @__PURE__ */ new Set();
28
31
  for (const part of field.split(",")) {
@@ -37,6 +40,7 @@ const cronValues = (field, max) => {
37
40
  }
38
41
  return [...values].toSorted((a, b) => a - b);
39
42
  };
43
+ /** The minutes between runs within an hour, and across the hour boundary when two consecutive hours both run. */
40
44
  const runGaps = (minutes, hours) => {
41
45
  const gaps = minutes.slice(1).map((minute, index) => minute - (minutes[index] ?? 0));
42
46
  const [first] = minutes;
@@ -44,6 +48,11 @@ const runGaps = (minutes, hours) => {
44
48
  if (hours?.some((hour) => hours.includes((hour + 1) % 24)) === true && first !== void 0 && last !== void 0) gaps.push(60 - last + first);
45
49
  return gaps;
46
50
  };
51
+ /**
52
+ * Refuses an expression that is not five fields, or that can run less than
53
+ * `MIN_MINUTES` apart. A minute or hour field `cronValues` cannot read is not
54
+ * checked.
55
+ */
47
56
  const checkCron = (cron) => {
48
57
  const fields = cron.trim().split(/\s+/u);
49
58
  if (fields.length !== 5) throw invalidRequest(provider, `needs a five-field cron expression, got "${cron}"`);
@@ -53,11 +62,18 @@ const checkCron = (cron) => {
53
62
  if (minutes && runGaps(minutes, hours).some((gap) => gap < MIN_MINUTES)) throw invalidRequest(provider, `monitors run at most every ${MIN_MINUTES} minutes, got "${cron}"`);
54
63
  return cron.trim();
55
64
  };
65
+ /** The cron for every `count` hours. Only counts that divide 24 have one. */
56
66
  const hourlyCron = (count) => {
57
67
  if (!Number.isInteger(count) || count < 1 || 24 % count !== 0) return;
58
68
  if (count === 1) return "0 * * * *";
59
69
  return count === 24 ? "0 0 * * *" : `0 */${count} * * *`;
60
70
  };
71
+ /**
72
+ * The cron expression for a schedule. A cron is checked and passed through. A
73
+ * named interval becomes a cron: `hour` (on the hour), `day`, `1d` (midnight),
74
+ * `week`, `7d` (midnight on Sunday), or `Nh` for an N that divides 24. Throws
75
+ * `InvalidRequest` for any other interval.
76
+ */
61
77
  const cronFor = (schedule) => {
62
78
  if ("cron" in schedule) return checkCron(schedule.cron);
63
79
  const every = schedule.every;
@@ -80,6 +96,7 @@ const MAX_PARSE_MS = 3e5;
80
96
  const REPORT_GRACE_MS = 1e4;
81
97
  /** The longest query a search monitor takes. */
82
98
  const MAX_MONITOR_QUERY = 256;
99
+ /** Firecrawl's `qdr:` units, for each named recency window. */
83
100
  const RECENCY = {
84
101
  day: "d",
85
102
  hour: "h",
@@ -88,6 +105,7 @@ const RECENCY = {
88
105
  year: "y"
89
106
  };
90
107
  const DATE = /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/u;
108
+ /** The page-fetching fields every scrape takes. `maxAge` goes out in milliseconds, and the rest as they are. */
91
109
  const pageBody = (o) => compact({
92
110
  actions: o.actions,
93
111
  excludeTags: o.excludeTags,
@@ -100,6 +118,7 @@ const pageBody = (o) => compact({
100
118
  proxy: o.proxy,
101
119
  waitFor: o.waitFor
102
120
  });
121
+ /** The formats a read asks for: Markdown always, then `include`, then `query` as highlights (the default) or a question. */
103
122
  const readFormats = (o) => {
104
123
  const query = o.query === void 0 ? [] : [o.queryFormat === "question" ? {
105
124
  question: o.query,
@@ -114,15 +133,22 @@ const readFormats = (o) => {
114
133
  ...query
115
134
  ];
116
135
  };
136
+ /** The scrape body for a read: its formats and page settings. */
117
137
  const readBody = (o) => ({
118
138
  formats: readFormats(o),
119
139
  ...pageBody(o)
120
140
  });
141
+ /** Firecrawl's date filter takes MM/DD/YYYY; the options take YYYY-MM-DD. */
121
142
  const usDate = (value) => {
122
143
  const groups = DATE.exec(value)?.groups;
123
144
  if (!groups) throw invalidRequest(provider, `needs dates as YYYY-MM-DD, got "${value}"`);
124
145
  return `${groups.month}/${groups.day}/${groups.year}`;
125
146
  };
147
+ /**
148
+ * The `tbs` time filter: `tbs` as given, else `recency` as `qdr:`, else the
149
+ * published dates as a `cdr:1` range with `cd_min` and `cd_max`. Refuses
150
+ * `tbs`, `recency` and the dates in combination.
151
+ */
126
152
  const timeFilter = (o) => {
127
153
  refuseTogether(provider, o, "tbs", "recency", "publishedAfter");
128
154
  refuseTogether(provider, o, "tbs", "recency", "publishedBefore");
@@ -135,6 +161,7 @@ const timeFilter = (o) => {
135
161
  o.publishedBefore === void 0 ? void 0 : `cd_max:${usDate(o.publishedBefore)}`
136
162
  ].filter((part) => part !== void 0).join(",");
137
163
  };
164
+ /** The `/search` body. `content` asks for each result's Markdown. Refuses `includeDomains` with `excludeDomains`, and `gov` with another category. */
138
165
  const searchBody = (query, o) => {
139
166
  refuseTogether(provider, o, "includeDomains", "excludeDomains");
140
167
  if (o.categories?.includes("gov") === true && o.categories.length > 1) throw invalidRequest(provider, "searches the gov category on its own; do not combine it with another category");
@@ -153,6 +180,7 @@ const searchBody = (query, o) => {
153
180
  tbs: timeFilter(o)
154
181
  });
155
182
  };
183
+ /** The `/search` body for images: the `images` source alone. */
156
184
  const imagesBody = (query, o) => compact({
157
185
  country: country(o.country),
158
186
  limit: o.limit,
@@ -171,6 +199,7 @@ const mapBody = (url, o) => compact({
171
199
  sitemap: o.sitemap,
172
200
  url
173
201
  });
202
+ /** The `/crawl` body. `scrapeOptions` is built like a read's body. */
174
203
  const crawlBody = (url, o) => compact({
175
204
  allowExternalLinks: o.allowExternalLinks,
176
205
  allowSubdomains: o.allowSubdomains,
@@ -188,6 +217,7 @@ const crawlBody = (url, o) => compact({
188
217
  sitemap: o.sitemap,
189
218
  url
190
219
  });
220
+ /** The `/agent` body. `continueFrom` is sent as `threadId`, and `country` as `location`. */
191
221
  const researchBody = (question, o) => compact({
192
222
  effort: o.effort,
193
223
  location: o.country === void 0 || o.country === "" ? void 0 : { country: country(o.country) },
@@ -199,12 +229,18 @@ const researchBody = (question, o) => compact({
199
229
  threadId: o.continueFrom,
200
230
  urls: o.urls
201
231
  });
232
+ /** The body that opens a browser session. `activityTtl` falls back to `ttl`. */
202
233
  const sessionBody = (o) => compact({
203
234
  activityTtl: o.activityTtl ?? o.ttl,
204
235
  location: o.country === void 0 || o.country === "" ? void 0 : { country: country(o.country) },
205
236
  profile: o.profile,
206
237
  ttl: o.ttl
207
238
  });
239
+ /**
240
+ * Refuses session settings given together with `session`, since that session
241
+ * is already open. Returns the call's `timeout` as whole seconds for the
242
+ * script's limit (at least 1), and refuses one over `MAX_SCRIPT_SECONDS`.
243
+ */
208
244
  const checkAct = (o, timeout) => {
209
245
  for (const name of [
210
246
  "ttl",
@@ -217,6 +253,11 @@ const checkAct = (o, timeout) => {
217
253
  if (seconds > MAX_SCRIPT_SECONDS) throw invalidRequest(provider, `runs a script for at most ${MAX_SCRIPT_SECONDS} seconds`);
218
254
  return seconds;
219
255
  };
256
+ /**
257
+ * The request that runs a script. The request waits `REPORT_GRACE_MS` longer
258
+ * than the script's own limit, so Firecrawl reports a timeout before the client
259
+ * gives up.
260
+ */
220
261
  const scriptRequest = (code, language, call, seconds) => ({
221
262
  body: compact({
222
263
  code,
@@ -227,6 +268,10 @@ const scriptRequest = (code, language, call, seconds) => ({
227
268
  signal: call.signal,
228
269
  timeout: call.timeout === void 0 ? void 0 : call.timeout + REPORT_GRACE_MS
229
270
  });
271
+ /**
272
+ * The multipart body of a `/parse` call. Refuses a file type it does not know,
273
+ * a file over `MAX_PARSE_MB` and a `timeout` over `MAX_PARSE_MS`.
274
+ */
230
275
  const parseForm = (document, o, timeout) => {
231
276
  if (timeout !== void 0 && timeout > MAX_PARSE_MS) throw invalidRequest(provider, `parses for at most ${MAX_PARSE_MS / 1e3} seconds`);
232
277
  if (mediaTypeOf(document.name) === void 0) throw invalidRequest(provider, `parses ${[...MEDIA_TYPES.keys()].join(", ")} files, not "${document.name}"`);
@@ -248,6 +293,11 @@ const parseForm = (document, o, timeout) => {
248
293
  form.set("file", documentPart(document), document.name);
249
294
  return form;
250
295
  };
296
+ /**
297
+ * A monitor's target: a scrape of `urls`, or a search for `query`. Refuses
298
+ * search-only options with `urls`, no `urls` and no `query`, and a search query
299
+ * over `MAX_MONITOR_QUERY` characters.
300
+ */
251
301
  const monitorTarget = (o) => {
252
302
  const searchOnly = [
253
303
  o.searchWindow,
@@ -273,6 +323,7 @@ const monitorTarget = (o) => {
273
323
  type: "search"
274
324
  });
275
325
  };
326
+ /** The `/monitor` body. `query` is also the monitor's `goal`, and the name defaults to the query or first URL, cut to 256 characters. */
276
327
  const monitorBody = (o) => {
277
328
  const target = monitorTarget(o);
278
329
  return compact({
@@ -298,11 +349,14 @@ const PAPER_URLS = /* @__PURE__ */ new Map([
298
349
  const LANGUAGE = /^(?<code>[a-z]{2})(?:[-_]|$)/u;
299
350
  /** The list, or undefined when it is empty. */
300
351
  const some = (items) => items.length > 0 ? [...items] : void 0;
352
+ /** The two-letter code of a locale such as `en-GB` or `en_GB`. */
301
353
  const languageCode = (value) => LANGUAGE.exec(value?.toLowerCase() ?? "")?.groups?.code;
354
+ /** The passages for a page: the `highlights` text, else the highlight list, else the written `answer` of a `question` query. */
302
355
  const excerptsOf = (data) => {
303
356
  const { list, text } = data.highlights;
304
357
  return (text === void 0 ? some(list) : [text]) ?? (data.answer === void 0 ? void 0 : [data.answer]);
305
358
  };
359
+ /** The credits and scrape id of a page, with its warnings and those of the whole response. */
306
360
  const pageMeta = (data, topNotes) => meta({
307
361
  credits: data.metadata.creditsUsed,
308
362
  requestId: data.metadata.scrapeId,
@@ -332,6 +386,7 @@ const toPage = (data, fallbackUrl, topNotes = []) => {
332
386
  url: metadata.url ?? metadata.sourceURL ?? fallbackUrl
333
387
  });
334
388
  };
389
+ /** A price; undefined when Firecrawl gave none of its fields. */
335
390
  const price = (item) => {
336
391
  const result = compact({
337
392
  amount: item.amount,
@@ -340,6 +395,7 @@ const price = (item) => {
340
395
  });
341
396
  return Object.keys(result).length > 0 ? result : void 0;
342
397
  };
398
+ /** The first non-empty GTIN, from `gtin` then the 14, 13, 12 and 8 digit forms. */
343
399
  const gtin = (variant) => [
344
400
  variant.gtin,
345
401
  variant.gtin14,
@@ -363,6 +419,7 @@ const toVariant = (variant) => {
363
419
  values: Object.keys(values).length > 0 ? values : void 0
364
420
  });
365
421
  };
422
+ /** The variants' images without repeats, by URL. Used when the product lists none of its own. */
366
423
  const allImages = (variants) => {
367
424
  const seen = /* @__PURE__ */ new Map();
368
425
  for (const image of variants.flatMap((variant) => variant.images ?? [])) if (!seen.has(image.url)) seen.set(image.url, image);
@@ -386,6 +443,7 @@ const toProduct = (body) => {
386
443
  };
387
444
  /** Why a page has no product: the warning it carries, if any. */
388
445
  const noProductReason = (body) => body.data.warning.text ?? body.warning.text;
446
+ /** A web or news result. `kind` is the result's own category, else its source; `snippet` is its description, else its snippet. */
389
447
  const searchItem = (result, kind) => compact({
390
448
  content: result.markdown,
391
449
  image: result.imageUrl,
@@ -395,6 +453,11 @@ const searchItem = (result, kind) => compact({
395
453
  title: result.title,
396
454
  url: result.url ?? ""
397
455
  });
456
+ /**
457
+ * A research result. Papers carry ids rather than URLs: a `web:` id holds the
458
+ * URL itself, and an `arxiv`, `pmid`, `pmcid` or `doi` id resolves through
459
+ * `PAPER_URLS`. Any other id is used as it is.
460
+ */
398
461
  const paperItem = (paper) => {
399
462
  const paperId = paper.paperId ?? "";
400
463
  const primary = paper.primaryId ?? paperId;
@@ -408,6 +471,7 @@ const paperItem = (paper) => {
408
471
  url: paperId.startsWith("web:") ? paperId.slice(4) : resolve?.(primary.slice(colon + 1)) ?? primary
409
472
  });
410
473
  };
474
+ /** Image results. `sourceUrl` is the page the image is on; an item without an image URL is dropped. */
411
475
  const imageItems = (found) => found.flatMap((image) => {
412
476
  const { imageUrl: url } = image;
413
477
  return url === void 0 ? [] : [compact({
@@ -418,12 +482,13 @@ const imageItems = (found) => found.flatMap((image) => {
418
482
  width: image.imageWidth
419
483
  })];
420
484
  });
485
+ /** The credits, request id and warnings of a search. */
421
486
  const searchMeta = (body) => meta({
422
487
  credits: body.creditsUsed,
423
488
  requestId: body.id,
424
489
  warnings: [...body.warning, ...body.warnings]
425
490
  });
426
- /** The results of a search; the caller adds `raw`. */
491
+ /** The results of a search, web then news then research; the caller adds `raw`. Images are kept apart in `images`. */
427
492
  const searchResult = (body) => {
428
493
  const { data } = body;
429
494
  return compact({
@@ -436,14 +501,21 @@ const searchResult = (body) => {
436
501
  ]
437
502
  });
438
503
  };
504
+ /** The image results of a search for images; the caller adds `raw`. */
439
505
  const imagesResult = (body) => compact({
440
506
  meta: searchMeta(body),
441
507
  results: imageItems(body.data.images ?? [])
442
508
  });
509
+ /** The pages a crawl or batch could not read. */
443
510
  const failedPages = (errors) => errors.value.errors.map((entry) => ({
444
511
  error: entry.error ?? "unknown error",
445
512
  url: entry.url ?? ""
446
513
  }));
514
+ /**
515
+ * The run when it has finished, undefined while it runs. A `failed` run that
516
+ * left partial output counts as finished; any other `failed` or `cancelled`
517
+ * run throws `JobFailed`.
518
+ */
447
519
  const researchState = (id, entry) => {
448
520
  const status = entry.value;
449
521
  const state = status.status;
@@ -455,6 +527,12 @@ const researchState = (id, entry) => {
455
527
  });
456
528
  return done ? entry : void 0;
457
529
  };
530
+ /**
531
+ * The result of a finished run. A `failed` run with partial output is
532
+ * `partial`, with that output and a `stopReason`; any other is `completed`
533
+ * with `data`, else the message. `sources` is always empty. The continuation
534
+ * id is the run's thread.
535
+ */
458
536
  const researchResult = (id, started, entry) => {
459
537
  const run = entry.value;
460
538
  const stopped = run.status === "failed";
@@ -474,6 +552,10 @@ const researchResult = (id, started, entry) => {
474
552
  stopReason: stopped ? run.stopReason ?? run.error ?? "failed" : void 0
475
553
  });
476
554
  };
555
+ /**
556
+ * The outcome of a script. `sessionId` is set only when the session is still
557
+ * open or could not be closed; `close` is what closing it returned.
558
+ */
477
559
  const actResult = (entry, sessionId, close) => {
478
560
  const result = entry.value;
479
561
  const stdout = result.stdout ?? "";
@@ -494,6 +576,7 @@ const actResult = (entry, sessionId, close) => {
494
576
  stdout
495
577
  });
496
578
  };
579
+ /** An open browser session. Throws `ProviderError` when Firecrawl returned no id. */
497
580
  const browserSession = (entry) => {
498
581
  const session = entry.value;
499
582
  return compact({
@@ -504,7 +587,7 @@ const browserSession = (entry) => {
504
587
  raw: entry.original
505
588
  });
506
589
  };
507
- /** Firecrawl's blocks, a page at a time; a page without a number is left out. */
590
+ /** Firecrawl's blocks, a page at a time; a page without a number is left out. `box` is set only when `bbox` has four numbers. */
508
591
  const documentBlocks = (pages) => pages.flatMap((entry) => {
509
592
  const page = entry.pageNumber;
510
593
  if (page === void 0) return [];
@@ -537,6 +620,7 @@ const parseResult = (body) => {
537
620
  meta: pageMeta(data, body.warning.notes)
538
621
  });
539
622
  };
623
+ /** What a monitor watches: its goal, else its target URLs or queries joined with commas. */
540
624
  const watching = (monitor) => {
541
625
  if (monitor.goal !== void 0) return monitor.goal;
542
626
  return monitor.targets.flatMap((target) => {
@@ -545,6 +629,7 @@ const watching = (monitor) => {
545
629
  return target.queries;
546
630
  }).filter((item) => item !== void 0).join(", ") || void 0;
547
631
  };
632
+ /** A monitor. `schedule` is its cron expression, else Firecrawl's text for it. */
548
633
  const monitorInfo = (entry) => {
549
634
  const monitor = entry.value;
550
635
  return compact({
@@ -557,6 +642,11 @@ const monitorInfo = (entry) => {
557
642
  webhookUrl: monitor.webhook.url
558
643
  });
559
644
  };
645
+ /**
646
+ * One check of a monitor as an event. The summary reads like
647
+ * `completed: 2 changed, 1 new of 40 pages`, and the time is when the check
648
+ * finished, else started, was scheduled or was created.
649
+ */
560
650
  const checkEvent = (entry) => {
561
651
  const check = entry.value;
562
652
  const { summary } = check;
@@ -582,7 +672,12 @@ const checkEvent = (entry) => {
582
672
  ].filter((part) => part !== void 0).join(": ")
583
673
  });
584
674
  };
585
- /** One page of a monitor's checks; the caller adds `raw`. */
675
+ /**
676
+ * One page of a monitor's checks; the caller adds `raw`. The cursor is the
677
+ * offset of the next page, set only when this page is full. Firecrawl caps a
678
+ * page at 100 and reports no total, so when the checks end exactly on a page
679
+ * boundary the cursor leads to an empty page.
680
+ */
586
681
  const monitorEvents = (checks, offset) => compact({
587
682
  events: checks.map((check) => checkEvent(check)),
588
683
  next: checks.length === 100 ? String(offset + checks.length) : void 0
@@ -622,6 +717,7 @@ const Price = looseObject({
622
717
  currency: optionalString,
623
718
  formatted: optionalString
624
719
  });
720
+ /** A product variant. GTINs arrive in several widths, so each is read apart; `values` maps option names to values. */
625
721
  const Variant = looseObject({
626
722
  availability: looseObject({
627
723
  inStock: optionalBoolean,
@@ -751,6 +847,7 @@ const Execution = withOriginal(looseObject({
751
847
  }));
752
848
  /** What closing a session billed. */
753
849
  const Closed = looseObject({ creditsBilled: optionalNumber });
850
+ /** A web or news search result. */
754
851
  const WebItem = looseObject({
755
852
  category: optionalString,
756
853
  date: optionalString,
@@ -761,6 +858,7 @@ const WebItem = looseObject({
761
858
  title: optionalString,
762
859
  url: optionalString
763
860
  });
861
+ /** A research search result. It carries ids, not a URL. */
764
862
  const Paper = looseObject({
765
863
  abstract: optionalString,
766
864
  paperId: optionalString,
@@ -768,6 +866,7 @@ const Paper = looseObject({
768
866
  score: optionalNumber,
769
867
  title: optionalString
770
868
  });
869
+ /** An image search result: `imageUrl` is the image and `url` the page it is on. */
771
870
  const ImageItem = looseObject({
772
871
  imageHeight: optionalNumber,
773
872
  imageUrl: optionalString,
@@ -798,6 +897,7 @@ const MapResponse = looseObject({ links: arrayOf(z.union([z.pipe(z.string(), z.t
798
897
  title: link.title,
799
898
  url: link.url ?? ""
800
899
  })))])) });
900
+ /** A monitor. Its targets are a scrape (`urls`), a crawl (`url`) or a search (`queries`). */
801
901
  const Monitor = looseObject({
802
902
  createdAt: optionalString,
803
903
  goal: optionalString,
@@ -884,6 +984,7 @@ const firecrawl = (config = {}) => {
884
984
  provider,
885
985
  retries: config.retries
886
986
  });
987
+ /** Scrapes one URL with the formats and page settings given. */
887
988
  const scrape = async (url, formats, settings, call) => {
888
989
  const response = await raw.request("POST", "/scrape", {
889
990
  ...call,
@@ -900,6 +1001,7 @@ const firecrawl = (config = {}) => {
900
1001
  response
901
1002
  };
902
1003
  };
1004
+ /** The path of a `next` link, relative to the base URL, so the next page of results goes through the same client. */
903
1005
  const pathOf = (link) => {
904
1006
  const next = new URL(link);
905
1007
  const base = new URL(baseUrl).pathname.replace(/\/$/u, "");
@@ -942,6 +1044,7 @@ const firecrawl = (config = {}) => {
942
1044
  },
943
1045
  start
944
1046
  }, settings);
1047
+ /** Opens a browser session. Only a rate limit is retried, since after any other failure the session may already be open and billing. */
945
1048
  const openSession = async (o, call) => {
946
1049
  const session = z.parse(Session, await raw.request("POST", "/interact", {
947
1050
  body: sessionBody(o),
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { $ as TableCell, A as ImageResult, B as ParsedDocument, C as DocumentInput, D as FailedUrl, E as Extraction, F as MonitorEvents, G as ProductVariant, H as Price, I as MonitorInfo, J as RunStatus, K as Recency, L as MonitorSchedule, M as JsonSchema, N as Meta, O as FieldSource, P as MonitorEvent, Q as SiteMap, R as Page, S as DocumentBlock, T as Entity, U as Product, V as Place, W as ProductImage, X as SearchResult, Y as SearchResponse, Z as SiteLink, _ as Crawl, a as RawClient, b as Decisions, c as ActResult, d as BrowserSession, et as Usage, f as CAPABILITIES, g as Condition, h as Citation, i as defineAdapter, j as ImageSearch, k as GROUP_CAPABILITIES, l as Answer, m as Capability, n as AnyAdapter, o as RequestOptions, p as CallOptions, q as Research, r as Operations, s as AccountUsage, t as Adapter, tt as WordBox, u as Box, v as DecisionAnswer, w as DocumentPage, x as Discovery, y as DecisionQuestion, z as PageBatch } from "./adapter-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";
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-BhTK51Yj.js";
2
+ import { i as FieldworkErrorCode, n as FieldworkOptions, r as FieldworkError, t as Fieldwork } from "./fieldwork-CseCD_-H.js";
3
+ import { n as StandardSchemaWithJSON, t as OutputSchema } from "./schema-CNd51xdD.js";
4
4
  /** Which adapter serves each capability, for `router`. */
5
5
  type Routes = Partial<Record<Capability, AnyAdapter>>;
6
6
  /** Each route must name an adapter whose provider offers that capability. */
package/dist/index.js CHANGED
@@ -1,7 +1,13 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
- import { t as FieldworkError } from "./errors-Yvk42oZH.js";
2
+ import { t as FieldworkError } from "./errors-DROZyb9T.js";
3
3
  import { n as GROUP_CAPABILITIES, t as CAPABILITIES } from "./types-CnomnF-6.js";
4
4
  // src/fieldwork.ts
5
+ /**
6
+ * The adapter's operation for a capability, bound to its `operations` object
7
+ * (or, for a group such as `monitor`, each method bound to the group) so it
8
+ * can be called detached. Undefined when the adapter lacks the capability.
9
+ * `Fieldwork` and `router` both bind through this.
10
+ */
5
11
  const bindOperation = (operations, capability) => {
6
12
  const all = operations;
7
13
  const operation = all[capability];
@@ -11,6 +17,7 @@ const bindOperation = (operations, capability) => {
11
17
  return Object.fromEntries(Object.entries(group).map(([name, method]) => [name, typeof method === "function" ? method.bind(group) : method]));
12
18
  }
13
19
  };
20
+ /** What a capability the provider lacks does when called: throws `Unsupported`, for every method of a group too. */
14
21
  const unsupported = (provider, capability) => {
15
22
  const refuse = async () => {
16
23
  throw new FieldworkError("Unsupported", `${provider} does not offer ${capability}`, { provider });
@@ -18,6 +25,11 @@ const unsupported = (provider, capability) => {
18
25
  if (!GROUP_CAPABILITIES.includes(capability)) return refuse;
19
26
  return new Proxy({}, { get: () => refuse });
20
27
  };
28
+ /**
29
+ * The implementation behind `Fieldwork`, typed loosely: each capability name
30
+ * is assigned onto the instance in the constructor, as the adapter's bound
31
+ * operation or a stand-in that throws `Unsupported`.
32
+ */
21
33
  var FieldworkClient = class {
22
34
  provider;
23
35
  capabilities;
@@ -66,10 +78,19 @@ var FieldworkClient = class {
66
78
  */
67
79
  const Fieldwork = FieldworkClient;
68
80
  // src/router.ts
81
+ /**
82
+ * Binds each route's operation and records which provider serves it, so
83
+ * `Fieldwork.providerFor` can say. `raw` is keyed by provider name, so every
84
+ * route to one provider must use the same adapter instance.
85
+ *
86
+ * Throws `Unsupported` for a route to an adapter that lacks the capability,
87
+ * and `InvalidRequest` for two instances of one provider.
88
+ */
69
89
  const build = (routes) => {
70
90
  const operations = {};
71
91
  const raw = {};
72
92
  const providers = {};
93
+ const instances = /* @__PURE__ */ new Map();
73
94
  for (const [capability, adapter] of Object.entries(routes)) {
74
95
  if (adapter === void 0) continue;
75
96
  const operation = bindOperation(adapter.operations, capability);
@@ -77,6 +98,9 @@ const build = (routes) => {
77
98
  operations[capability] = operation;
78
99
  const known = CAPABILITIES.find((name) => name === capability);
79
100
  if (known !== void 0) providers[known] = adapter.name;
101
+ const earlier = instances.get(adapter.name);
102
+ if (earlier !== void 0 && earlier !== adapter) throw new FieldworkError("InvalidRequest", `routes use two ${adapter.name} adapters; route every capability to one instance`, { provider: adapter.name });
103
+ instances.set(adapter.name, adapter);
80
104
  raw[adapter.name] = adapter.raw;
81
105
  }
82
106
  return {
@@ -1,6 +1,12 @@
1
- import { i as withJob, t as FieldworkError } from "./errors-Yvk42oZH.js";
2
- import { D as sleep, O as stopped } from "./parse-n8MmaK1x.js";
1
+ import { i as withJob, t as FieldworkError } from "./errors-DROZyb9T.js";
2
+ import { D as sleep, O as stopped } from "./parse-BY3R0oWO.js";
3
3
  // src/job.ts
4
+ /**
5
+ * Checks the job every `interval` until it has a finished state. Throws
6
+ * `Timeout` when another interval would pass the deadline, and `Aborted` or
7
+ * `Timeout` (by how the signal stopped) once the signal is aborted. Both carry
8
+ * `jobId`, because the job may still be running.
9
+ */
4
10
  const waitFor = async (provider, id, check, settings) => {
5
11
  const interval = settings.interval ?? 2e3;
6
12
  const deadline = Date.now() + (settings.timeout ?? 6e5);
@@ -1,9 +1,11 @@
1
- import { B as ParsedDocument, C as DocumentInput, a as RawClient, p as CallOptions, t as Adapter } from "./adapter-BgdfLBs-.js";
1
+ import { B as ParsedDocument, C as DocumentInput, a as RawClient, p as CallOptions, t as Adapter } from "./adapter-BhTK51Yj.js";
2
+ /** Settings for `llamaparse()`. */
2
3
  export interface LlamaParseConfig {
3
4
  /** Defaults to the LLAMA_CLOUD_API_KEY environment variable. */
4
5
  apiKey?: string;
5
6
  /** Defaults to https://api.cloud.llamaindex.ai; the EU region is https://api.cloud.eu.llamaindex.ai. */
6
7
  baseUrl?: string;
8
+ /** Defaults to the global `fetch`. It also downloads result files from the presigned URLs LlamaParse returns. A test passes a fake. */
7
9
  fetch?: typeof fetch;
8
10
  /** Repeats of a request that can succeed on repeat; 2 unless set. `0` turns retrying off. */
9
11
  retries?: number;
@@ -13,6 +15,7 @@ export interface LlamaParseConfig {
13
15
  * no AI model; `agentic` reads tables, scans and multi-column layouts.
14
16
  */
15
17
  export type LlamaParseTier = "fast" | "cost_effective" | "agentic" | "agentic_plus";
18
+ /** Options for `parse`. */
16
19
  export interface LlamaParseParseOptions extends CallOptions {
17
20
  /** Defaults to "agentic". */
18
21
  tier?: LlamaParseTier;
@@ -22,7 +25,7 @@ export interface LlamaParseParseOptions extends CallOptions {
22
25
  blocks?: boolean;
23
26
  /**
24
27
  * Also return where each word and table cell sits in each block, from a
25
- * second download. Returns blocks too. LlamaParse does not charge for it.
28
+ * second download. Returns blocks too.
26
29
  */
27
30
  wordBoxes?: boolean;
28
31
  /** Leave out text a reader cannot see, such as white text on white. */
@@ -43,8 +46,10 @@ export interface LlamaParseParseOptions extends CallOptions {
43
46
  export type LlamaParseResumeOptions = Omit<LlamaParseParseOptions, "resume"> & {
44
47
  resume: string;
45
48
  };
49
+ /** What the LlamaParse adapter offers. */
46
50
  export interface LlamaParseOperations {
47
51
  parse: {
52
+ /** Uploads the file and waits for the parse. An error after the upload carries `jobId`. */
48
53
  (document: DocumentInput, options?: LlamaParseParseOptions): Promise<ParsedDocument>;
49
54
  /** Collects an earlier parse by its id, without sending the file again. */
50
55
  (options: LlamaParseResumeOptions): Promise<ParsedDocument>;
@@ -1,8 +1,8 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
- import { a as refuseLarger, n as documentPart, r as enclosing } from "./document-Dpj01mGx.js";
3
- import { t as FieldworkError } from "./errors-Yvk42oZH.js";
4
- import { B as requireJobId, C as createRawClient, E as segment, F as parseJson, M as compact, P as meta, S as withOriginal, T as requireKey, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, k as callSettings, m as optionalScalar, n as anything, r as arrayOf, s as optionalAnyString, w as readSigned } from "./parse-n8MmaK1x.js";
5
- import { t as runJob } from "./job-BGTwH3F-.js";
2
+ import { a as refuseLarger, n as documentPart, r as enclosing } from "./document-CjMeBtV5.js";
3
+ import { t as FieldworkError } from "./errors-DROZyb9T.js";
4
+ import { B as requireJobId, C as createRawClient, E as segment, F as parseJson, M as compact, P as meta, S as withOriginal, T as requireKey, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, k as callSettings, m as optionalScalar, n as anything, r as arrayOf, s as optionalAnyString, w as readSigned } from "./parse-BY3R0oWO.js";
5
+ import { t as runJob } from "./job-DVsmQMKP.js";
6
6
  import * as z from "zod/mini";
7
7
  // src/adapters/llamaparse/response.ts
8
8
  /** A box in page points, from the page's top-left corner. */
@@ -143,6 +143,7 @@ const provider = "llamaparse";
143
143
  const PAGE_IMAGE = /^page_(?<page>\d+)\.jpg$/u;
144
144
  /** The largest file LlamaParse takes, in megabytes. */
145
145
  const MAX_PARSE_MB = 512;
146
+ /** The upload's `configuration`. The tier and version are always sent; the rest only when asked for. */
146
147
  const configuration = (o) => compact({
147
148
  output_options: o.wordBoxes === true || o.pageImages === true ? compact({
148
149
  granular_bboxes: o.wordBoxes === true ? [
@@ -156,6 +157,7 @@ const configuration = (o) => compact({
156
157
  tier: o.tier ?? "agentic",
157
158
  version: o.version ?? "latest"
158
159
  });
160
+ /** Uploads the file and returns the job id. Refuses a missing document, or a file over the size limit, before sending. */
159
161
  const startParse = async (raw, document, o, call) => {
160
162
  if (document === void 0) throw new FieldworkError("InvalidRequest", "parse needs a document, or resume with the id of an earlier parse", { provider });
161
163
  refuseLarger(provider, document, MAX_PARSE_MB);
@@ -169,6 +171,7 @@ const startParse = async (raw, document, o, call) => {
169
171
  }));
170
172
  return requireJobId(provider, created.id);
171
173
  };
174
+ /** The result once the job has completed, undefined while it runs; throws `JobFailed` when LlamaParse failed or cancelled it. */
172
175
  const finished = (found) => {
173
176
  const { error_message: message, status } = found.value.job;
174
177
  if (status === "FAILED" || status === "CANCELLED") throw new FieldworkError("JobFailed", `llamaparse job ${status.toLowerCase()}${message === void 0 ? "" : `: ${message}`}`, {
@@ -235,6 +238,7 @@ const parsedDocument = async (found, id, o, read) => {
235
238
  }
236
239
  });
237
240
  };
241
+ /** Runs the job. `expand` names the sections of the result to include; blocks, word boxes and page images each add one. */
238
242
  const parse = async (raw, document, options, fetchImpl) => {
239
243
  const { call, rest: o } = callSettings(options);
240
244
  const expand = [