@howells/fieldwork-sdk 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/firecrawl.js CHANGED
@@ -1,11 +1,12 @@
1
1
  import { t as defineAdapter } from "./adapter-CEAQuT7F.js";
2
2
  import { r as withJob, t as FieldworkError } from "./errors-BiIBG9zN.js";
3
- import { b as requireKey, c as num, d as record, f as refuseTogether, g as text, h as strings, i as compact, m as scalar, o as list, p as requireId, s as meta, t as callSettings, u as productImages, v as createRawClient, y as poll } from "./util-CYenIQQT.js";
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";
5
+ import * as z from "zod/mini";
4
6
  // src/adapters/firecrawl/shared.ts
5
7
  const provider = "firecrawl";
6
8
  const invalid = (message) => new FieldworkError("InvalidRequest", message, { provider });
7
9
  const segment = (id) => encodeURIComponent(id);
8
- const warnings = (...values) => values.flatMap((value) => typeof value === "string" ? [value] : list(value).map(String));
9
10
  const country = (code) => code?.toUpperCase();
10
11
  // src/adapters/firecrawl/schedule.ts
11
12
  /** The fewest minutes Firecrawl allows between two checks of a monitor. */
@@ -40,7 +41,7 @@ const runGaps = (minutes, hours) => {
40
41
  const gaps = minutes.slice(1).map((minute, index) => minute - (minutes[index] ?? 0));
41
42
  const [first] = minutes;
42
43
  const last = minutes.at(-1);
43
- if (hours?.some((hour) => hours.includes((hour + 1) % 24)) && first !== void 0 && last !== void 0) gaps.push(60 - last + first);
44
+ if (hours?.some((hour) => hours.includes((hour + 1) % 24)) === true && first !== void 0 && last !== void 0) gaps.push(60 - last + first);
44
45
  return gaps;
45
46
  };
46
47
  const checkCron = (cron) => {
@@ -61,11 +62,11 @@ const cronFor = (schedule) => {
61
62
  if ("cron" in schedule) return checkCron(schedule.cron);
62
63
  const every = schedule.every;
63
64
  const named = NAMED_CRON.get(every);
64
- if (named) return named;
65
+ if (named !== void 0) return named;
65
66
  const groups = INTERVAL.exec(every)?.groups;
66
67
  const count = Number(groups?.count);
67
68
  const cron = groups?.unit === "h" ? hourlyCron(count) : DAILY_CRON.get(count);
68
- if (cron) return cron;
69
+ if (cron !== void 0) return cron;
69
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
71
  };
71
72
  // src/adapters/firecrawl/request.ts
@@ -156,7 +157,7 @@ const timeFilter = (o) => {
156
157
  };
157
158
  const searchBody = (query, o) => {
158
159
  refuseTogether(provider, o, "includeDomains", "excludeDomains");
159
- if (o.categories?.includes("gov") && o.categories.length > 1) throw invalid("firecrawl searches the gov category on its own; do not combine it with another category");
160
+ 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");
160
161
  return compact({
161
162
  categories: o.categories?.map((type) => ({ type })),
162
163
  country: country(o.country),
@@ -167,7 +168,7 @@ const searchBody = (query, o) => {
167
168
  location: o.location,
168
169
  query,
169
170
  safe: o.safe,
170
- scrapeOptions: o.content ? { formats: ["markdown"] } : void 0,
171
+ scrapeOptions: o.content === true ? { formats: ["markdown"] } : void 0,
171
172
  sources: o.sources?.map((type) => ({ type })),
172
173
  tbs: timeFilter(o)
173
174
  });
@@ -209,18 +210,18 @@ const crawlBody = (url, o) => compact({
209
210
  });
210
211
  const researchBody = (question, o) => compact({
211
212
  effort: o.effort,
212
- location: o.country ? { country: country(o.country) } : void 0,
213
+ location: o.country === void 0 || o.country === "" ? void 0 : { country: country(o.country) },
213
214
  maxCredits: o.maxCredits,
214
215
  model: o.model,
215
216
  prompt: question,
216
- schema: o.schema,
217
+ schema: o.schema === void 0 ? void 0 : jsonSchemaOf(o.schema),
217
218
  strictConstrainToURLs: o.strictConstrainToURLs,
218
219
  threadId: o.continueFrom,
219
220
  urls: o.urls
220
221
  });
221
222
  const sessionBody = (o) => compact({
222
223
  activityTtl: o.activityTtl ?? o.ttl,
223
- location: o.country ? { country: country(o.country) } : void 0,
224
+ location: o.country === void 0 || o.country === "" ? void 0 : { country: country(o.country) },
224
225
  profile: o.profile,
225
226
  ttl: o.ttl
226
227
  });
@@ -248,7 +249,7 @@ const scriptRequest = (code, language, call, seconds) => ({
248
249
  const parseForm = (document, o) => {
249
250
  const extension = document.name.split(".").pop()?.toLowerCase() ?? "";
250
251
  const mediaType = MEDIA_TYPES.get(extension);
251
- if (!mediaType) throw invalid(`firecrawl parses ${[...MEDIA_TYPES.keys()].join(", ")} files, not "${document.name}"`);
252
+ if (mediaType === void 0) throw invalid(`firecrawl parses ${[...MEDIA_TYPES.keys()].join(", ")} files, not "${document.name}"`);
252
253
  const size = document.data instanceof Blob ? document.data.size : document.data.byteLength;
253
254
  if (size > MAX_PARSE_BYTES) throw invalid(`firecrawl parses files up to 50 MB; ${document.name} is ${(size / 1024 / 1024).toFixed(1)} MB`);
254
255
  const parser = compact({
@@ -264,7 +265,8 @@ const parseForm = (document, o) => {
264
265
  formats: ["markdown"],
265
266
  parsers: [parser]
266
267
  }));
267
- form.set("file", new Blob([document.data], { type: mediaType }), document.name);
268
+ const part = document.data instanceof Uint8Array ? new Uint8Array(document.data) : document.data;
269
+ form.set("file", new Blob([part], { type: mediaType }), document.name);
268
270
  return form;
269
271
  };
270
272
  const monitorTarget = (o) => {
@@ -281,7 +283,7 @@ const monitorTarget = (o) => {
281
283
  urls: o.urls
282
284
  };
283
285
  }
284
- if (!o.query) throw invalid("firecrawl monitors need urls to watch or a query");
286
+ if (o.query === void 0 || o.query === "") throw invalid("firecrawl monitors need urls to watch or a query");
285
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`);
286
288
  return compact({
287
289
  excludeDomains: o.excludeDomains,
@@ -303,7 +305,7 @@ const monitorBody = (o) => {
303
305
  timezone: o.timezone
304
306
  }),
305
307
  targets: [target],
306
- webhook: o.webhookUrl ? { url: o.webhookUrl } : void 0
308
+ webhook: o.webhookUrl === void 0 || o.webhookUrl === "" ? void 0 : { url: o.webhookUrl }
307
309
  });
308
310
  };
309
311
  // src/adapters/firecrawl/response.ts
@@ -315,84 +317,70 @@ const PAPER_URLS = /* @__PURE__ */ new Map([
315
317
  ["doi", (id) => `https://doi.org/${id}`]
316
318
  ]);
317
319
  const LANGUAGE = /^(?<code>[a-z]{2})(?:[-_]|$)/u;
318
- const firstText = (value) => Array.isArray(value) ? text(value.find((item) => typeof item === "string" && item !== "")) : text(value);
319
- const languageCode = (value) => LANGUAGE.exec(firstText(value)?.toLowerCase() ?? "")?.groups?.code;
320
+ /** The list, or undefined when it is empty. */
321
+ const some = (items) => items.length > 0 ? [...items] : void 0;
322
+ const languageCode = (value) => LANGUAGE.exec(value?.toLowerCase() ?? "")?.groups?.code;
320
323
  const excerptsOf = (data) => {
321
- const highlight = text(data.highlights);
322
- const highlights = highlight ? [highlight] : strings(data.highlights);
323
- const answer = text(data.answer);
324
- return highlights ?? (answer ? [answer] : void 0);
325
- };
326
- const pageMeta = (top, data) => {
327
- const metadata = record(data.metadata);
328
- return meta({
329
- credits: metadata.creditsUsed,
330
- requestId: metadata.scrapeId,
331
- warnings: warnings(data.warning, top.warning)
332
- });
324
+ const { list, text } = data.highlights;
325
+ return (text === void 0 ? some(list) : [text]) ?? (data.answer === void 0 ? void 0 : [data.answer]);
333
326
  };
334
- const toPage = (data, fallbackUrl, raw, top = {}) => {
335
- const metadata = record(data.metadata);
327
+ const pageMeta = (data, topNotes) => meta({
328
+ credits: data.metadata.creditsUsed,
329
+ requestId: data.metadata.scrapeId,
330
+ warnings: [...data.warning.notes, ...topNotes]
331
+ });
332
+ /** A page from scraped data; the caller adds `raw`. `topNotes` are the warnings of the whole response. */
333
+ const toPage = (data, fallbackUrl, topNotes = []) => {
334
+ const { metadata } = data;
336
335
  return compact({
337
- author: firstText(metadata.author),
338
- description: firstText(metadata.description),
336
+ author: metadata.author,
337
+ description: metadata.description,
339
338
  excerpts: excerptsOf(data),
340
- favicon: text(metadata.favicon),
341
- html: text(data.html),
342
- image: firstText(metadata.ogImage) ?? firstText(metadata["og:image"]),
343
- images: strings(data.images),
339
+ favicon: metadata.favicon,
340
+ html: data.html,
341
+ image: metadata.ogImage ?? metadata["og:image"],
342
+ images: some(data.images),
344
343
  language: languageCode(metadata.language),
345
- links: strings(data.links),
346
- markdown: text(data.markdown),
347
- meta: pageMeta(top, data),
348
- publishedAt: text(metadata.publishedTime) ?? text(metadata["article:published_time"]),
349
- raw,
350
- rawHtml: text(data.rawHtml),
351
- screenshot: text(data.screenshot),
352
- statusCode: num(metadata.statusCode),
353
- summary: text(data.summary),
354
- title: firstText(metadata.title),
355
- url: text(metadata.url) ?? text(metadata.sourceURL) ?? fallbackUrl
344
+ links: some(data.links),
345
+ markdown: data.markdown,
346
+ meta: pageMeta(data, topNotes),
347
+ publishedAt: metadata.publishedTime ?? metadata["article:published_time"],
348
+ rawHtml: data.rawHtml,
349
+ screenshot: data.screenshot,
350
+ statusCode: metadata.statusCode,
351
+ summary: data.summary,
352
+ title: metadata.title,
353
+ url: metadata.url ?? metadata.sourceURL ?? fallbackUrl
356
354
  });
357
355
  };
358
- const price = (value) => {
359
- const item = record(value);
356
+ const price = (item) => {
360
357
  const result = compact({
361
- amount: text(item.amount) ?? num(item.amount)?.toString(),
362
- currency: text(item.currency),
363
- formatted: text(item.formatted)
358
+ amount: item.amount,
359
+ currency: item.currency,
360
+ formatted: item.formatted
364
361
  });
365
362
  return Object.keys(result).length > 0 ? result : void 0;
366
363
  };
367
- const gtin = (variant) => {
368
- for (const key of [
369
- "gtin",
370
- "gtin14",
371
- "gtin13",
372
- "gtin12",
373
- "gtin8"
374
- ]) {
375
- const value = scalar(variant[key]);
376
- if (value) return value;
377
- }
378
- };
379
- const toVariant = (value) => {
380
- const variant = record(value);
381
- const availability = record(variant.availability);
382
- const values = Object.fromEntries(Object.entries(record(variant.values)).flatMap(([key, item]) => {
383
- const option = scalar(item);
384
- return option === void 0 ? [] : [[key, option]];
385
- }));
364
+ const gtin = (variant) => [
365
+ variant.gtin,
366
+ variant.gtin14,
367
+ variant.gtin13,
368
+ variant.gtin12,
369
+ variant.gtin8
370
+ ].find((value) => value !== void 0 && value !== "");
371
+ const images = (found) => some(found.filter((image) => image !== void 0));
372
+ const toVariant = (variant) => {
373
+ const values = Object.fromEntries(Object.entries(variant.values).flatMap(([key, item]) => item === void 0 ? [] : [[key, item]]));
386
374
  return compact({
387
- availability: text(availability.text),
375
+ availability: variant.availability.text,
388
376
  gtin: gtin(variant),
389
- id: text(variant.id),
390
- images: productImages(variant.images),
391
- inStock: typeof availability.inStock === "boolean" ? availability.inStock : void 0,
392
- originalPrice: price(record(variant.sale).originalPrice),
377
+ id: variant.id,
378
+ images: images(variant.images),
379
+ inStock: variant.availability.inStock,
380
+ originalPrice: price(variant.sale.originalPrice),
393
381
  price: price(variant.price),
394
- sku: text(variant.sku),
395
- title: text(variant.title),
382
+ sku: variant.sku,
383
+ title: variant.title,
396
384
  values: Object.keys(values).length > 0 ? values : void 0
397
385
  });
398
386
  };
@@ -401,224 +389,474 @@ const allImages = (variants) => {
401
389
  for (const image of variants.flatMap((variant) => variant.images ?? [])) if (!seen.has(image.url)) seen.set(image.url, image);
402
390
  return seen.size > 0 ? [...seen.values()] : void 0;
403
391
  };
404
- const toProduct = (url, response, data) => {
405
- if (!data.product) {
406
- const why = text(data.warning) ?? text(response.warning);
407
- throw new FieldworkError("NotFound", `firecrawl found no product on ${url}${why ? `: ${why}` : ""}`, {
408
- cause: response,
409
- provider
410
- });
411
- }
412
- const product = record(data.product);
413
- const variants = list(product.variants).map((variant) => toVariant(variant));
392
+ /** The product on a scraped page; the caller adds `raw`. Undefined when the page has none. */
393
+ const toProduct = (body) => {
394
+ const { product } = body.data;
395
+ if (product === void 0) return;
396
+ const variants = product.variants.map((variant) => toVariant(variant));
414
397
  return compact({
415
- brand: text(product.brand),
416
- category: text(product.category),
417
- description: text(product.description),
418
- images: productImages(product.images) ?? allImages(variants),
419
- meta: pageMeta(response, data),
420
- raw: response,
421
- title: text(product.title),
422
- url: text(product.url),
398
+ brand: product.brand,
399
+ category: product.category,
400
+ description: product.description,
401
+ images: images(product.images) ?? allImages(variants),
402
+ meta: pageMeta(body.data, body.warning.notes),
403
+ title: product.title,
404
+ url: product.url,
423
405
  variants
424
406
  });
425
407
  };
426
- const searchItem = (item, kind) => {
427
- const result = record(item);
428
- return compact({
429
- content: text(result.markdown),
430
- image: text(result.imageUrl),
431
- kind: text(result.category) ?? kind,
432
- publishedAt: text(result.date),
433
- snippet: text(result.description) ?? text(result.snippet),
434
- title: text(result.title),
435
- url: text(result.url) ?? ""
436
- });
437
- };
438
- const paperItem = (item) => {
439
- const paper = record(item);
440
- const paperId = text(paper.paperId) ?? "";
441
- const primary = text(paper.primaryId) ?? paperId;
408
+ /** Why a page has no product: the warning it carries, if any. */
409
+ const noProductReason = (body) => body.data.warning.text ?? body.warning.text;
410
+ const searchItem = (result, kind) => compact({
411
+ content: result.markdown,
412
+ image: result.imageUrl,
413
+ kind: result.category ?? kind,
414
+ publishedAt: result.date,
415
+ snippet: result.description ?? result.snippet,
416
+ title: result.title,
417
+ url: result.url ?? ""
418
+ });
419
+ const paperItem = (paper) => {
420
+ const paperId = paper.paperId ?? "";
421
+ const primary = paper.primaryId ?? paperId;
442
422
  const colon = primary.indexOf(":");
443
423
  const resolve = colon > 0 ? PAPER_URLS.get(primary.slice(0, colon)) : void 0;
444
424
  return compact({
445
425
  kind: "research",
446
- score: num(paper.score),
447
- snippet: text(paper.abstract),
448
- title: text(paper.title),
426
+ score: paper.score,
427
+ snippet: paper.abstract,
428
+ title: paper.title,
449
429
  url: paperId.startsWith("web:") ? paperId.slice(4) : resolve?.(primary.slice(colon + 1)) ?? primary
450
430
  });
451
431
  };
452
- const imageItems = (value) => list(value).flatMap((item) => {
453
- const image = record(item);
454
- const url = text(image.imageUrl);
455
- return url ? [compact({
456
- height: num(image.imageHeight),
457
- sourceUrl: text(image.url),
458
- title: text(image.title),
432
+ const imageItems = (found) => found.flatMap((image) => {
433
+ const { imageUrl: url } = image;
434
+ return url === void 0 ? [] : [compact({
435
+ height: image.imageHeight,
436
+ sourceUrl: image.url,
437
+ title: image.title,
459
438
  url,
460
- width: num(image.imageWidth)
461
- })] : [];
439
+ width: image.imageWidth
440
+ })];
462
441
  });
463
- const searchMeta = (response) => meta({
464
- credits: response.creditsUsed,
465
- requestId: response.id,
466
- warnings: warnings(response.warning, response.warnings)
442
+ const searchMeta = (body) => meta({
443
+ credits: body.creditsUsed,
444
+ requestId: body.id,
445
+ warnings: [...body.warning, ...body.warnings]
467
446
  });
468
- const searchResult = (response) => {
469
- const data = record(response.data);
447
+ /** The results of a search; the caller adds `raw`. */
448
+ const searchResult = (body) => {
449
+ const { data } = body;
470
450
  return compact({
471
- images: Array.isArray(data.images) ? imageItems(data.images) : void 0,
472
- meta: searchMeta(response),
473
- raw: response,
451
+ images: data.images === void 0 ? void 0 : imageItems(data.images),
452
+ meta: searchMeta(body),
474
453
  results: [
475
- ...list(data.web).map((item) => searchItem(item, "web")),
476
- ...list(data.news).map((item) => searchItem(item, "news")),
477
- ...list(data.research).map((item) => paperItem(item))
454
+ ...data.web.map((item) => searchItem(item, "web")),
455
+ ...data.news.map((item) => searchItem(item, "news")),
456
+ ...data.research.map((item) => paperItem(item))
478
457
  ]
479
458
  });
480
459
  };
481
- const imagesResult = (response) => compact({
482
- meta: searchMeta(response),
483
- raw: response,
484
- results: imageItems(record(response.data).images)
460
+ const imagesResult = (body) => compact({
461
+ meta: searchMeta(body),
462
+ results: imageItems(body.data.images ?? [])
485
463
  });
486
- const failedPages = (errors) => list(errors.errors).map((item) => {
487
- const entry = record(item);
488
- return {
489
- error: text(entry.error) ?? "unknown error",
490
- url: text(entry.url) ?? ""
491
- };
492
- });
493
- const researchState = (id, status) => {
494
- const state = text(status.status);
464
+ const failedPages = (errors) => errors.value.errors.map((entry) => ({
465
+ error: entry.error ?? "unknown error",
466
+ url: entry.url ?? ""
467
+ }));
468
+ const researchState = (id, entry) => {
469
+ const status = entry.value;
470
+ const state = status.status;
495
471
  const hasPartial = status.partial !== void 0 && status.partial !== null;
496
472
  const done = state === "completed" || state === "failed" && hasPartial;
497
- if (!done && (state === "failed" || state === "cancelled")) throw new FieldworkError("JobFailed", `firecrawl research run ${id} ${state}: ${text(status.error) ?? text(status.stopReason) ?? "no reason given"}`, {
498
- cause: status,
473
+ if (!done && (state === "failed" || state === "cancelled")) throw new FieldworkError("JobFailed", `firecrawl research run ${id} ${state}: ${status.error ?? status.stopReason ?? "no reason given"}`, {
474
+ cause: entry.original,
499
475
  provider
500
476
  });
501
- return done ? status : void 0;
477
+ return done ? entry : void 0;
502
478
  };
503
- const researchResult = (id, started, run) => {
479
+ const researchResult = (id, started, entry) => {
480
+ const run = entry.value;
504
481
  const stopped = run.status === "failed";
505
482
  const status = stopped ? "partial" : "completed";
506
483
  return compact({
507
- continuationId: text(run.threadId) ?? text(started.threadId),
484
+ continuationId: run.threadId ?? started.value.threadId,
508
485
  id,
509
486
  meta: meta({
510
487
  credits: run.creditsUsed,
511
488
  requestId: id,
512
- warnings: stopped ? [run.message, run.partialSchemaValid === false ? "the partial output does not match the schema" : void 0] : void 0
489
+ warnings: stopped ? [run.message.note, run.partialSchemaValid === false ? "the partial output does not match the schema" : void 0].filter((note) => note !== void 0) : void 0
513
490
  }),
514
- output: stopped ? run.partial : run.data ?? run.message,
515
- raw: run,
491
+ output: stopped ? run.partial : run.data ?? run.message.value,
492
+ raw: entry.original,
516
493
  sources: [],
517
494
  status,
518
- stopReason: stopped ? text(run.stopReason) ?? text(run.error) ?? "failed" : void 0
495
+ stopReason: stopped ? run.stopReason ?? run.error ?? "failed" : void 0
519
496
  });
520
497
  };
521
- const actResult = (result, sessionId, closed) => {
522
- const stdout = text(result.stdout) ?? "";
498
+ const actResult = (entry, sessionId, closed) => {
499
+ const result = entry.value;
500
+ const stdout = result.stdout ?? "";
523
501
  const failure = result.success === false ? "firecrawl reported that the script did not succeed" : void 0;
524
502
  const repeated = result.result === "" || result.result === null || result.result === stdout;
525
503
  return compact({
526
- error: text(result.error) ?? failure,
527
- exitCode: num(result.exitCode),
528
- killed: typeof result.killed === "boolean" ? result.killed : void 0,
504
+ error: result.error ?? failure,
505
+ exitCode: result.exitCode,
506
+ killed: result.killed,
529
507
  meta: meta({ credits: closed?.creditsBilled }),
530
- raw: result,
508
+ raw: entry.original,
531
509
  result: repeated ? void 0 : result.result,
532
510
  sessionId,
533
- stderr: text(result.stderr) ?? "",
511
+ stderr: result.stderr ?? "",
534
512
  stdout
535
513
  });
536
514
  };
537
- const browserSession = (response) => compact({
538
- cdpUrl: text(response.cdpUrl),
539
- expiresAt: text(response.expiresAt),
540
- id: requireId(provider, response.id),
541
- liveViewUrl: text(response.liveViewUrl),
542
- raw: response
543
- });
544
- const parseResult = (response) => {
545
- const data = record(response.data);
546
- const metadata = record(data.metadata);
515
+ const browserSession = (entry) => {
516
+ const session = entry.value;
547
517
  return compact({
548
- markdown: text(data.markdown) ?? "",
549
- pages: Array.isArray(data.pages) ? list(data.pages).map((page) => ({
550
- markdown: text(record(page).markdown) ?? "",
551
- pageNumber: Number(record(page).pageNumber)
552
- })) : void 0,
553
- blocks: Array.isArray(data.blocks) ? data.blocks : void 0,
554
- pageCount: num(metadata.totalPages) ?? num(metadata.numPages),
555
- meta: pageMeta(response, data),
556
- raw: response
518
+ cdpUrl: session.cdpUrl,
519
+ expiresAt: session.expiresAt,
520
+ id: requireJobId(provider, session.id),
521
+ liveViewUrl: session.liveViewUrl,
522
+ raw: entry.original
523
+ });
524
+ };
525
+ /** A parsed document; the caller adds `raw`. */
526
+ const parseResult = (body) => {
527
+ const { data } = body;
528
+ return compact({
529
+ markdown: data.markdown ?? "",
530
+ pages: data.pages?.map((page) => ({
531
+ markdown: page.markdown ?? "",
532
+ pageNumber: Number(page.pageNumber)
533
+ })),
534
+ blocks: data.blocks,
535
+ pageCount: data.metadata.totalPages ?? data.metadata.numPages,
536
+ meta: pageMeta(data, body.warning.notes)
557
537
  });
558
538
  };
559
539
  const watching = (monitor) => {
560
- const goal = text(monitor.goal);
561
- if (goal) return goal;
562
- return list(monitor.targets).map((item) => record(item)).flatMap((target) => {
563
- if (target.type === "scrape") return strings(target.urls) ?? [];
564
- if (target.type === "crawl") return [text(target.url)];
565
- return strings(target.queries) ?? [];
540
+ if (monitor.goal !== void 0) return monitor.goal;
541
+ return monitor.targets.flatMap((target) => {
542
+ if (target.type === "scrape") return target.urls;
543
+ if (target.type === "crawl") return [target.url];
544
+ return target.queries;
566
545
  }).filter((item) => item !== void 0).join(", ") || void 0;
567
546
  };
568
- const monitorInfo = (value) => {
569
- const monitor = record(value);
570
- const schedule = record(monitor.schedule);
547
+ const monitorInfo = (entry) => {
548
+ const monitor = entry.value;
571
549
  return compact({
572
- createdAt: text(monitor.createdAt),
573
- id: requireId(provider, monitor.id),
574
- raw: monitor,
575
- schedule: text(schedule.cron) ?? text(schedule.text),
576
- status: text(monitor.status),
550
+ createdAt: monitor.createdAt,
551
+ id: requireJobId(provider, monitor.id),
552
+ raw: entry.original,
553
+ schedule: monitor.schedule.cron ?? monitor.schedule.text,
554
+ status: monitor.status,
577
555
  watch: watching(monitor),
578
- webhookUrl: text(record(monitor.webhook).url)
556
+ webhookUrl: monitor.webhook.url
579
557
  });
580
558
  };
581
- const checkEvent = (check) => {
582
- const summary = record(check.summary);
559
+ const checkEvent = (entry) => {
560
+ const check = entry.value;
561
+ const { summary } = check;
583
562
  const counts = [
584
563
  "changed",
585
564
  "new",
586
565
  "removed",
587
566
  "error"
588
567
  ].flatMap((key) => {
589
- const count = num(summary[key]);
568
+ const count = summary[key];
590
569
  return count === void 0 ? [] : [`${count} ${key}`];
591
570
  });
592
- const pages = num(summary.totalPages);
571
+ const pages = summary.totalPages;
593
572
  const of = pages === void 0 ? "" : ` of ${pages} pages`;
594
573
  return compact({
595
- at: text(check.finishedAt) ?? text(check.startedAt) ?? text(check.scheduledFor) ?? text(check.createdAt),
596
- id: text(check.id),
597
- raw: check,
574
+ at: check.finishedAt ?? check.startedAt ?? check.scheduledFor ?? check.createdAt,
575
+ id: check.id,
576
+ raw: entry.original,
598
577
  summary: [
599
- text(check.status),
578
+ check.status,
600
579
  counts.length > 0 ? `${counts.join(", ")}${of}` : void 0,
601
- text(check.error)
580
+ check.error
602
581
  ].filter((part) => part !== void 0).join(": ")
603
582
  });
604
583
  };
605
- const monitorEvents = (response, offset) => {
606
- const checks = list(response.data).map((item) => record(item));
607
- return compact({
608
- events: checks.map((check) => checkEvent(check)),
609
- next: checks.length === 100 ? String(offset + checks.length) : void 0,
610
- raw: response
611
- });
612
- };
613
- const usageResult = (response) => {
614
- const data = record(response.data);
615
- return compact({
616
- limit: num(data.planCredits),
617
- periodEnd: text(data.billingPeriodEnd),
618
- raw: response,
619
- remaining: num(data.remainingCredits)
584
+ /** One page of a monitor's checks; the caller adds `raw`. */
585
+ const monitorEvents = (checks, offset) => compact({
586
+ events: checks.map((check) => checkEvent(check)),
587
+ next: checks.length === 100 ? String(offset + checks.length) : void 0
588
+ });
589
+ /** The account's credit usage; the caller adds `raw`. */
590
+ const usageResult = (body) => compact({
591
+ limit: body.data.planCredits,
592
+ periodEnd: body.data.billingPeriodEnd,
593
+ remaining: body.data.remainingCredits
594
+ });
595
+ // src/adapters/firecrawl/shapes.ts
596
+ /**
597
+ * Warnings as text: a string is one warning (an empty one too); an array gives
598
+ * every entry as a string, whatever it is; anything else gives none.
599
+ */
600
+ const Notes = z.union([z.pipe(z.string(), z.transform((note) => [note])), arrayOf(z.pipe(z.unknown(), z.transform(String)))]);
601
+ /** A warning, as its text when it is a non-empty string and as the list of warnings it amounts to. */
602
+ const Warning = z.pipe(both(optionalString, Notes), z.transform(({ first, second }) => ({
603
+ notes: second,
604
+ text: first
605
+ })));
606
+ /** A product image: a bare URL, or an object with a URL (or `src`) and a description. One without a URL reads as undefined. */
607
+ const Image = z.union([z.pipe(z.string(), z.transform((url) => url === "" ? void 0 : { url })), z.pipe(looseObject({
608
+ alt: optionalString,
609
+ src: optionalString,
610
+ url: optionalString
611
+ }), z.transform((image) => {
612
+ const url = image.url ?? image.src;
613
+ return url === void 0 ? void 0 : compact({
614
+ alt: image.alt,
615
+ url
620
616
  });
617
+ }))]);
618
+ /** A price. The amount is a string or a number, read as a string. */
619
+ const Price = looseObject({
620
+ amount: optionalId,
621
+ currency: optionalString,
622
+ formatted: optionalString
623
+ });
624
+ const Variant = looseObject({
625
+ availability: looseObject({
626
+ inStock: optionalBoolean,
627
+ text: optionalString
628
+ }),
629
+ gtin: optionalScalar,
630
+ gtin12: optionalScalar,
631
+ gtin13: optionalScalar,
632
+ gtin14: optionalScalar,
633
+ gtin8: optionalScalar,
634
+ id: optionalString,
635
+ images: arrayOf(Image),
636
+ price: Price,
637
+ sale: looseObject({ originalPrice: Price }),
638
+ sku: optionalString,
639
+ title: optionalString,
640
+ values: recordOf(optionalScalar)
641
+ });
642
+ /** The metadata of a scraped page, and of a parsed document. */
643
+ const metadataShape = {
644
+ "article:published_time": optionalString,
645
+ author: optionalFirstString,
646
+ creditsUsed: optionalNumber,
647
+ description: optionalFirstString,
648
+ favicon: optionalString,
649
+ language: optionalFirstString,
650
+ numPages: optionalNumber,
651
+ "og:image": optionalFirstString,
652
+ ogImage: optionalFirstString,
653
+ publishedTime: optionalString,
654
+ scrapeId: optionalScalar,
655
+ sourceURL: optionalString,
656
+ statusCode: optionalNumber,
657
+ title: optionalFirstString,
658
+ totalPages: optionalNumber,
659
+ url: optionalString
621
660
  };
661
+ /** What a scrape returns for one page. `json` is kept as it arrived. */
662
+ const PageData = looseObject({
663
+ answer: optionalString,
664
+ highlights: z.pipe(both(optionalString, arrayOf(z.string())), z.transform(({ first, second }) => ({
665
+ list: second,
666
+ text: first
667
+ }))),
668
+ html: optionalString,
669
+ images: arrayOf(z.string()),
670
+ json: anything,
671
+ links: arrayOf(z.string()),
672
+ markdown: optionalString,
673
+ metadata: looseObject(metadataShape),
674
+ product: optionalObject({
675
+ brand: optionalString,
676
+ category: optionalString,
677
+ description: optionalString,
678
+ images: arrayOf(Image),
679
+ title: optionalString,
680
+ url: optionalString,
681
+ variants: arrayOf(Variant)
682
+ }),
683
+ rawHtml: optionalString,
684
+ screenshot: optionalString,
685
+ summary: optionalString,
686
+ warning: Warning
687
+ });
688
+ /** `/scrape`. */
689
+ const ScrapeResponse = looseObject({
690
+ data: PageData,
691
+ warning: Warning
692
+ });
693
+ /** A page of a crawl or batch, beside the entry as it arrived. */
694
+ const PageEntry = withOriginal(PageData);
695
+ /** A crawl or batch while it runs, and each batch of its pages, beside the response as it arrived. */
696
+ const Batch = withOriginal(looseObject({
697
+ creditsUsed: optionalNumber,
698
+ data: arrayOf(PageEntry),
699
+ next: optionalString,
700
+ status: optionalString,
701
+ total: optionalNumber
702
+ }));
703
+ /** The pages a crawl or batch could not read. */
704
+ const BatchErrors = withOriginal(looseObject({
705
+ errors: arrayOf(looseObject({
706
+ error: optionalString,
707
+ url: optionalString
708
+ })),
709
+ robotsBlocked: arrayOf(z.string())
710
+ }));
711
+ /** The reply to starting a crawl. */
712
+ const CrawlStart = looseObject({ id: withOriginal(optionalId) });
713
+ /** The reply to starting a batch scrape or an agent run, beside the response as it arrived. */
714
+ const RunStart = withOriginal(looseObject({
715
+ id: withOriginal(optionalId),
716
+ invalidURLs: arrayOf(z.string()),
717
+ threadId: optionalString
718
+ }));
719
+ /** An agent run while it is polled. */
720
+ const AgentRun = withOriginal(looseObject({
721
+ creditsUsed: optionalNumber,
722
+ data: anything,
723
+ error: optionalString,
724
+ message: z.pipe(both(anything, warningEntry), z.transform(({ first, second }) => ({
725
+ note: second,
726
+ value: first
727
+ }))),
728
+ partial: anything,
729
+ partialSchemaValid: optionalBoolean,
730
+ status: optionalString,
731
+ stopReason: optionalString,
732
+ threadId: optionalString
733
+ }));
734
+ /** A browser session as opened, beside the response as it arrived. */
735
+ const Session = withOriginal(looseObject({
736
+ cdpUrl: optionalString,
737
+ expiresAt: optionalString,
738
+ id: withOriginal(optionalId),
739
+ liveViewUrl: optionalString
740
+ }));
741
+ /** A script's outcome, beside the response as it arrived. */
742
+ const Execution = withOriginal(looseObject({
743
+ error: optionalString,
744
+ exitCode: optionalNumber,
745
+ killed: optionalBoolean,
746
+ result: anything,
747
+ stderr: optionalString,
748
+ stdout: optionalString,
749
+ success: optionalBoolean
750
+ }));
751
+ /** What closing a session billed. */
752
+ const Closed = looseObject({ creditsBilled: optionalNumber });
753
+ const WebItem = looseObject({
754
+ category: optionalString,
755
+ date: optionalString,
756
+ description: optionalString,
757
+ imageUrl: optionalString,
758
+ markdown: optionalString,
759
+ snippet: optionalString,
760
+ title: optionalString,
761
+ url: optionalString
762
+ });
763
+ const Paper = looseObject({
764
+ abstract: optionalString,
765
+ paperId: optionalString,
766
+ primaryId: optionalString,
767
+ score: optionalNumber,
768
+ title: optionalString
769
+ });
770
+ const ImageItem = looseObject({
771
+ imageHeight: optionalNumber,
772
+ imageUrl: optionalString,
773
+ imageWidth: optionalNumber,
774
+ title: optionalString,
775
+ url: optionalString
776
+ });
777
+ /** `/search`. */
778
+ const SearchResponse = looseObject({
779
+ creditsUsed: optionalNumber,
780
+ data: looseObject({
781
+ images: optionalArrayOf(ImageItem),
782
+ news: arrayOf(WebItem),
783
+ research: arrayOf(Paper),
784
+ web: arrayOf(WebItem)
785
+ }),
786
+ id: optionalScalar,
787
+ warning: Notes,
788
+ warnings: Notes
789
+ });
790
+ /** `/map`: each link is a bare URL or an object. */
791
+ const MapResponse = looseObject({ links: arrayOf(z.union([z.pipe(z.string(), z.transform((url) => ({ url }))), z.pipe(looseObject({
792
+ description: optionalString,
793
+ title: optionalString,
794
+ url: optionalString
795
+ }), z.transform((link) => compact({
796
+ description: link.description,
797
+ title: link.title,
798
+ url: link.url ?? ""
799
+ })))])) });
800
+ const Monitor = looseObject({
801
+ createdAt: optionalString,
802
+ goal: optionalString,
803
+ id: withOriginal(optionalId),
804
+ schedule: looseObject({
805
+ cron: optionalString,
806
+ text: optionalString
807
+ }),
808
+ status: optionalString,
809
+ targets: arrayOf(looseObject({
810
+ queries: arrayOf(z.string()),
811
+ type: optionalString,
812
+ url: optionalString,
813
+ urls: arrayOf(z.string())
814
+ })),
815
+ webhook: looseObject({ url: optionalString })
816
+ });
817
+ /** A monitor beside the entry as it arrived. */
818
+ const MonitorEntry = withOriginal(Monitor);
819
+ /** The reply to creating or getting a monitor. */
820
+ const MonitorResponse = looseObject({ data: MonitorEntry });
821
+ /** One page of monitors. */
822
+ const MonitorsResponse = looseObject({ data: arrayOf(MonitorEntry) });
823
+ /** One page of a monitor's checks, each beside its entry as it arrived. */
824
+ const ChecksResponse = looseObject({ data: arrayOf(withOriginal(looseObject({
825
+ createdAt: optionalString,
826
+ error: optionalString,
827
+ finishedAt: optionalString,
828
+ id: optionalString,
829
+ scheduledFor: optionalString,
830
+ startedAt: optionalString,
831
+ status: optionalString,
832
+ summary: looseObject({
833
+ changed: optionalNumber,
834
+ error: optionalNumber,
835
+ new: optionalNumber,
836
+ removed: optionalNumber,
837
+ totalPages: optionalNumber
838
+ })
839
+ }))) });
840
+ /** `/parse`. */
841
+ const ParseResponse = looseObject({
842
+ data: looseObject({
843
+ blocks: optionalArrayOf(anything),
844
+ markdown: optionalString,
845
+ metadata: looseObject(metadataShape),
846
+ pages: optionalArrayOf(looseObject({
847
+ markdown: optionalString,
848
+ pageNumber: anything
849
+ })),
850
+ warning: Warning
851
+ }),
852
+ warning: Warning
853
+ });
854
+ /** `/team/credit-usage`. */
855
+ const UsageResponse = looseObject({ data: looseObject({
856
+ billingPeriodEnd: optionalString,
857
+ planCredits: optionalNumber,
858
+ remainingCredits: optionalNumber
859
+ }) });
622
860
  // src/adapters/firecrawl.ts
623
861
  const firecrawl = (config = {}) => {
624
862
  const baseUrl = config.baseUrl ?? "https://api.firecrawl.dev/v2";
@@ -626,19 +864,22 @@ const firecrawl = (config = {}) => {
626
864
  baseUrl,
627
865
  fetch: config.fetch,
628
866
  headers: { authorization: `Bearer ${requireKey(provider, config.apiKey, "FIRECRAWL_API_KEY")}` },
629
- provider
867
+ provider,
868
+ retries: config.retries
630
869
  });
631
870
  const scrape = async (url, formats, settings, call) => {
632
- const response = record(await raw.request("POST", "/scrape", {
871
+ const response = await raw.request("POST", "/scrape", {
633
872
  ...call,
634
873
  body: {
635
874
  formats,
636
875
  url,
637
876
  ...pageBody(settings)
638
877
  }
639
- }));
878
+ });
879
+ const body = z.parse(ScrapeResponse, response);
640
880
  return {
641
- data: record(response.data),
881
+ body,
882
+ data: body.data,
642
883
  response
643
884
  };
644
885
  };
@@ -649,18 +890,18 @@ const firecrawl = (config = {}) => {
649
890
  };
650
891
  const finished = async (kind, id, call, interval) => {
651
892
  const path = `/${kind}/${segment(id)}`;
652
- const get = async (to) => {
893
+ const get = async (schema, to) => {
653
894
  try {
654
- return record(await raw.request("GET", to, { signal: call.signal }));
895
+ return z.parse(schema, await raw.request("GET", to, { signal: call.signal }));
655
896
  } catch (error) {
656
897
  throw withJob(error, id);
657
898
  }
658
899
  };
659
900
  const first = await poll(provider, id, async () => {
660
- const status = record(await raw.request("GET", path, { signal: call.signal }));
661
- const state = text(status.status);
901
+ const status = z.parse(Batch, await raw.request("GET", path, { signal: call.signal }));
902
+ const state = status.value.status;
662
903
  if (state === "failed" || state === "cancelled") throw new FieldworkError("JobFailed", `firecrawl ${kind} ${id} ended ${state}`, {
663
- cause: status,
904
+ cause: status.original,
664
905
  provider
665
906
  });
666
907
  return state === "completed" ? status : void 0;
@@ -669,13 +910,13 @@ const firecrawl = (config = {}) => {
669
910
  interval
670
911
  });
671
912
  const batches = [first];
672
- let next = text(first.next);
673
- while (next) {
674
- const batch = await get(pathOf(next));
913
+ let { next } = first.value;
914
+ while (next !== void 0) {
915
+ const batch = await get(Batch, pathOf(next));
675
916
  batches.push(batch);
676
- next = text(batch.next);
917
+ ({next} = batch.value);
677
918
  }
678
- const errors = await get(`${path}/errors`);
919
+ const errors = await get(BatchErrors, `${path}/errors`);
679
920
  return {
680
921
  batches,
681
922
  errors,
@@ -684,18 +925,19 @@ const firecrawl = (config = {}) => {
684
925
  };
685
926
  };
686
927
  const openSession = async (o, call) => {
687
- const response = record(await raw.request("POST", "/interact", {
928
+ const session = z.parse(Session, await raw.request("POST", "/interact", {
688
929
  body: sessionBody(o),
930
+ creates: true,
689
931
  signal: call.signal
690
932
  }));
691
933
  return {
692
- id: requireId(provider, response.id),
693
- response
934
+ id: requireJobId(provider, session.value.id),
935
+ session
694
936
  };
695
937
  };
696
938
  const closeQuietly = async (id, call) => {
697
939
  try {
698
- return record(await raw.request("DELETE", `/interact/${segment(id)}`, { signal: call.signal }));
940
+ return z.parse(Closed, await raw.request("DELETE", `/interact/${segment(id)}`, { signal: call.signal }));
699
941
  } catch {
700
942
  return null;
701
943
  }
@@ -710,7 +952,10 @@ const firecrawl = (config = {}) => {
710
952
  const keep = o.keepSession ?? !created;
711
953
  const { id } = o.session === void 0 ? await openSession(o, call) : { id: o.session };
712
954
  try {
713
- const result = record(await raw.request("POST", `/interact/${segment(id)}/execute`, scriptRequest(code, o.language, call, seconds)));
955
+ const result = z.parse(Execution, await raw.request("POST", `/interact/${segment(id)}/execute`, {
956
+ ...scriptRequest(code, o.language, call, seconds),
957
+ creates: true
958
+ }));
714
959
  const closed = keep ? null : await closeQuietly(id, call);
715
960
  return actResult(result, keep ? id : void 0, closed);
716
961
  } catch (error) {
@@ -725,85 +970,86 @@ const firecrawl = (config = {}) => {
725
970
  },
726
971
  async open(options) {
727
972
  const { call, rest: o } = callSettings(options);
728
- const { response } = await openSession(o, call);
729
- return browserSession(response);
973
+ const { session } = await openSession(o, call);
974
+ return browserSession(session);
730
975
  }
731
976
  },
732
977
  async crawl(url, options) {
733
978
  const { call, rest: o } = callSettings(options);
734
- const id = o.resume ?? requireId("firecrawl", record(await raw.request("POST", "/crawl", {
979
+ const id = o.resume ?? requireJobId("firecrawl", z.parse(CrawlStart, await raw.request("POST", "/crawl", {
980
+ creates: true,
735
981
  ...call,
736
982
  body: crawlBody(url, o)
737
983
  })).id);
738
984
  const job = await finished("crawl", id, call, o.interval);
985
+ const { robotsBlocked } = job.errors.value;
739
986
  return compact({
740
987
  failed: job.failed,
741
988
  id,
742
989
  meta: meta({
743
- credits: job.first.creditsUsed,
990
+ credits: job.first.value.creditsUsed,
744
991
  requestId: id
745
992
  }),
746
- pages: job.batches.flatMap((batch) => list(batch.data).map((item) => toPage(record(item), url, item))),
993
+ pages: job.batches.flatMap((batch) => batch.value.data.map((item) => ({
994
+ ...toPage(item.value, url),
995
+ raw: item.original
996
+ }))),
747
997
  raw: {
748
- batches: job.batches,
749
- errors: job.errors
998
+ batches: job.batches.map((batch) => batch.original),
999
+ errors: job.errors.original
750
1000
  },
751
- robotsBlocked: strings(job.errors.robotsBlocked),
752
- total: num(job.first.total)
1001
+ robotsBlocked: robotsBlocked.length > 0 ? robotsBlocked : void 0,
1002
+ total: job.first.value.total
753
1003
  });
754
1004
  },
755
1005
  async extract(url, options) {
756
1006
  const { call, rest: o } = callSettings(options);
757
1007
  const { schema, prompt, ...page } = o;
758
- const { response, data } = await scrape(url, [compact({
1008
+ const { body, response, data } = await scrape(url, [compact({
759
1009
  prompt,
760
- schema,
1010
+ schema: jsonSchemaOf(schema),
761
1011
  type: "json"
762
1012
  })], page, call);
763
1013
  if (data.json === void 0) {
764
- const why = text(data.warning);
765
- throw new FieldworkError("ProviderError", `firecrawl returned no JSON for ${url}${why ? `: ${why}` : ""}`, {
1014
+ const why = data.warning.text;
1015
+ throw new FieldworkError("ProviderError", `firecrawl returned no JSON for ${url}${why === void 0 ? "" : `: ${why}`}`, {
766
1016
  cause: response,
767
1017
  provider
768
1018
  });
769
1019
  }
770
1020
  return compact({
771
- data: data.json,
772
- meta: pageMeta(response, data),
1021
+ data: await checkOutput(schema, data.json, { provider }),
1022
+ meta: pageMeta(data, body.warning.notes),
773
1023
  raw: response
774
1024
  });
775
1025
  },
776
1026
  async images(query, options) {
777
1027
  const { call, rest: o } = callSettings(options);
778
- const response = record(await raw.request("POST", "/search", {
1028
+ const response = await raw.request("POST", "/search", {
779
1029
  ...call,
780
1030
  body: imagesBody(query, o)
781
- }));
782
- return imagesResult(response);
1031
+ });
1032
+ return {
1033
+ ...imagesResult(z.parse(SearchResponse, response)),
1034
+ raw: response
1035
+ };
783
1036
  },
784
1037
  async map(url, options) {
785
1038
  const { call, rest: o } = callSettings(options);
786
- const response = record(await raw.request("POST", "/map", {
1039
+ const response = await raw.request("POST", "/map", {
787
1040
  ...call,
788
1041
  body: mapBody(url, o)
789
- }));
1042
+ });
790
1043
  return {
791
- links: list(response.links).map((item) => {
792
- if (typeof item === "string") return { url: item };
793
- const link = record(item);
794
- return compact({
795
- description: text(link.description),
796
- title: text(link.title),
797
- url: text(link.url) ?? ""
798
- });
799
- }),
1044
+ links: z.parse(MapResponse, response).links,
800
1045
  raw: response
801
1046
  };
802
1047
  },
803
1048
  monitor: {
804
1049
  async create(options) {
805
1050
  const { call, rest: o } = callSettings(options);
806
- const response = record(await raw.request("POST", "/monitor", {
1051
+ const response = z.parse(MonitorResponse, await raw.request("POST", "/monitor", {
1052
+ creates: true,
807
1053
  ...call,
808
1054
  body: monitorBody(o)
809
1055
  }));
@@ -817,33 +1063,35 @@ const firecrawl = (config = {}) => {
817
1063
  const { call, rest: o } = callSettings(options);
818
1064
  const offset = Number(o.cursor ?? 0);
819
1065
  if (!Number.isInteger(offset) || offset < 0) throw invalid(`firecrawl events cursor "${o.cursor}" is not valid`);
820
- const response = record(await raw.request("GET", `/monitor/${segment(id)}/checks`, {
1066
+ const response = await raw.request("GET", `/monitor/${segment(id)}/checks`, {
821
1067
  ...call,
822
1068
  query: {
823
1069
  limit: 100,
824
1070
  offset
825
1071
  }
826
- }));
827
- return monitorEvents(response, offset);
1072
+ });
1073
+ return {
1074
+ ...monitorEvents(z.parse(ChecksResponse, response).data, offset),
1075
+ raw: response
1076
+ };
828
1077
  },
829
1078
  async get(id, options) {
830
1079
  const { call } = callSettings(options);
831
- const response = record(await raw.request("GET", `/monitor/${segment(id)}`, call));
1080
+ const response = z.parse(MonitorResponse, await raw.request("GET", `/monitor/${segment(id)}`, call));
832
1081
  return monitorInfo(response.data);
833
1082
  },
834
1083
  async list(options) {
835
1084
  const { call } = callSettings(options);
836
1085
  const monitors = [];
837
1086
  for (;;) {
838
- const response = record(await raw.request("GET", "/monitor", {
1087
+ const page = z.parse(MonitorsResponse, await raw.request("GET", "/monitor", {
839
1088
  ...call,
840
1089
  query: {
841
1090
  limit: 100,
842
1091
  offset: monitors.length
843
1092
  }
844
- }));
845
- const page = list(response.data);
846
- monitors.push(...page.map((item) => monitorInfo(item)));
1093
+ })).data;
1094
+ monitors.push(...page.map((entry) => monitorInfo(entry)));
847
1095
  if (page.length < 100) return monitors;
848
1096
  }
849
1097
  }
@@ -851,26 +1099,44 @@ const firecrawl = (config = {}) => {
851
1099
  async parse(document, options) {
852
1100
  const { call, rest: o } = callSettings(options);
853
1101
  const form = parseForm(document, o);
854
- const response = record(await raw.request("POST", "/parse", {
1102
+ const response = await raw.request("POST", "/parse", {
855
1103
  ...call,
856
1104
  form
857
- }));
858
- return parseResult(response);
1105
+ });
1106
+ return {
1107
+ ...parseResult(z.parse(ParseResponse, response)),
1108
+ raw: response
1109
+ };
859
1110
  },
860
1111
  async product(url, options) {
861
1112
  const { call, rest: o } = callSettings(options);
862
- const { response, data } = await scrape(url, ["product"], o, call);
863
- return toProduct(url, response, data);
1113
+ const { body, response } = await scrape(url, ["product"], o, call);
1114
+ const product = toProduct(body);
1115
+ if (product === void 0) {
1116
+ const why = noProductReason(body);
1117
+ throw new FieldworkError("NotFound", `firecrawl found no product on ${url}${why === void 0 ? "" : `: ${why}`}`, {
1118
+ cause: response,
1119
+ provider
1120
+ });
1121
+ }
1122
+ return {
1123
+ ...product,
1124
+ raw: response
1125
+ };
864
1126
  },
865
1127
  async read(url, options) {
866
1128
  const { call, rest: o } = callSettings(options);
867
- const { response, data } = await scrape(url, readFormats(o), o, call);
868
- return toPage(data, url, response, response);
1129
+ const { body, data, response } = await scrape(url, readFormats(o), o, call);
1130
+ return presentPage(provider, {
1131
+ ...toPage(data, url, body.warning.notes),
1132
+ raw: response
1133
+ });
869
1134
  },
870
1135
  async readMany(urls, options) {
871
1136
  const { call, rest: o } = callSettings(options);
872
1137
  const { interval, resume, maxConcurrency, ignoreInvalidURLs, ...read } = o;
873
- const started = resume === void 0 ? record(await raw.request("POST", "/batch/scrape", {
1138
+ const started = z.parse(RunStart, resume === void 0 ? await raw.request("POST", "/batch/scrape", {
1139
+ creates: true,
874
1140
  ...call,
875
1141
  body: compact({
876
1142
  urls,
@@ -878,52 +1144,75 @@ const firecrawl = (config = {}) => {
878
1144
  maxConcurrency,
879
1145
  ignoreInvalidURLs
880
1146
  })
881
- })) : {};
882
- const id = resume ?? requireId("firecrawl", started.id);
1147
+ }) : {});
1148
+ const id = resume ?? requireJobId("firecrawl", started.value.id);
883
1149
  const job = await finished("batch/scrape", id, call, interval);
884
- const rejected = (strings(started.invalidURLs) ?? []).map((url) => ({
1150
+ const rejected = started.value.invalidURLs.map((url) => ({
885
1151
  error: "invalid URL",
886
1152
  url
887
1153
  }));
1154
+ const { pages, gone } = presentPages(job.batches.flatMap((batch) => batch.value.data.map((item) => ({
1155
+ ...toPage(item.value, ""),
1156
+ raw: item.original
1157
+ }))));
888
1158
  return compact({
889
- failed: [...job.failed, ...rejected],
1159
+ failed: [
1160
+ ...job.failed,
1161
+ ...rejected,
1162
+ ...gone
1163
+ ],
890
1164
  id,
891
1165
  meta: meta({
892
- credits: job.first.creditsUsed,
1166
+ credits: job.first.value.creditsUsed,
893
1167
  requestId: id
894
1168
  }),
895
- pages: job.batches.flatMap((batch) => list(batch.data).map((item) => toPage(record(item), "", item))),
1169
+ pages,
896
1170
  raw: {
897
- batches: job.batches,
898
- errors: job.errors,
899
- started
1171
+ batches: job.batches.map((batch) => batch.original),
1172
+ errors: job.errors.original,
1173
+ started: started.original
900
1174
  }
901
1175
  });
902
1176
  },
903
1177
  async research(question, options) {
904
1178
  const { call, rest: o } = callSettings(options);
905
- const started = o.resume === void 0 ? record(await raw.request("POST", "/agent", {
1179
+ const started = z.parse(RunStart, o.resume === void 0 ? await raw.request("POST", "/agent", {
1180
+ creates: true,
906
1181
  ...call,
907
1182
  body: researchBody(question, o)
908
- })) : {};
909
- const id = o.resume ?? requireId("firecrawl", started.id);
910
- const run = await poll(provider, id, async () => researchState(id, record(await raw.request("GET", `/agent/${segment(id)}`, { signal: call.signal }))), {
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 }))), {
911
1186
  ...call,
912
1187
  interval: o.interval
913
1188
  });
914
- return researchResult(id, started, run);
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
+ };
915
1197
  },
916
1198
  async search(query, options) {
917
1199
  const { call, rest: o } = callSettings(options);
918
- const response = record(await raw.request("POST", "/search", {
1200
+ const response = await raw.request("POST", "/search", {
919
1201
  ...call,
920
1202
  body: searchBody(query, o)
921
- }));
922
- return searchResult(response);
1203
+ });
1204
+ return {
1205
+ ...searchResult(z.parse(SearchResponse, response)),
1206
+ raw: response
1207
+ };
923
1208
  },
924
1209
  async usage(options) {
925
1210
  const { call } = callSettings(options);
926
- return usageResult(record(await raw.request("GET", "/team/credit-usage", call)));
1211
+ const response = await raw.request("GET", "/team/credit-usage", call);
1212
+ return {
1213
+ ...usageResult(z.parse(UsageResponse, response)),
1214
+ raw: response
1215
+ };
927
1216
  }
928
1217
  },
929
1218
  raw