@howells/fieldwork-sdk 0.5.1 → 0.6.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/serpapi.js CHANGED
@@ -1,9 +1,14 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
- import { r as invalidRequest, t as FieldworkError } from "./errors-Yvk42oZH.js";
3
- import { C as createRawClient, M as compact, P as meta, T as requireKey, a as looseObject, f as optionalNumber, h as optionalString, k as callSettings, m as optionalScalar, o as nonEmptyString, r as arrayOf, x as warnings, z as refuseTogether } from "./parse-n8MmaK1x.js";
2
+ import { r as invalidRequest, t as FieldworkError } from "./errors-DROZyb9T.js";
3
+ import { C as createRawClient, M as compact, P as meta, T as requireKey, a as looseObject, f as optionalNumber, h as optionalString, k as callSettings, m as optionalScalar, o as nonEmptyString, r as arrayOf, x as warnings, z as refuseTogether } from "./parse-COHKvfH9.js";
4
4
  import * as z from "zod/mini";
5
5
  // src/adapters/serpapi/parse.ts
6
+ /** The name this adapter reports in errors and results. */
6
7
  const provider = "serpapi";
8
+ /**
9
+ * A shopping item's price: `amount` from `extracted_price` and `formatted` from
10
+ * `price`, either alone, or undefined when it has neither.
11
+ */
7
12
  const priceOf = (item) => {
8
13
  const price = compact({
9
14
  amount: item.extracted_price,
@@ -11,6 +16,10 @@ const priceOf = (item) => {
11
16
  });
12
17
  return Object.keys(price).length > 0 ? price : void 0;
13
18
  };
19
+ /**
20
+ * Organic results of Google, Bing and DuckDuckGo, as `web` results. A result with
21
+ * no link is left out.
22
+ */
14
23
  const webResults = (body) => body.organic_results.flatMap((item) => {
15
24
  const url = item.link;
16
25
  return url === void 0 ? [] : [compact({
@@ -24,6 +33,10 @@ const webResults = (body) => body.organic_results.flatMap((item) => {
24
33
  url
25
34
  })];
26
35
  });
36
+ /**
37
+ * Google Images results: `original` is the image and `link` its source page. A
38
+ * result with no `original` is left out.
39
+ */
27
40
  const imageResults = (body) => body.images_results.flatMap((item) => {
28
41
  const url = item.original;
29
42
  return url === void 0 ? [] : [compact({
@@ -35,6 +48,10 @@ const imageResults = (body) => body.images_results.flatMap((item) => {
35
48
  width: item.original_width
36
49
  })];
37
50
  });
51
+ /**
52
+ * One news story as a result, or none without a link. The author joins the
53
+ * source's authors, and the date prefers the ISO form.
54
+ */
38
55
  const newsItem = (item) => {
39
56
  const url = item.link;
40
57
  if (url === void 0) return [];
@@ -54,6 +71,10 @@ const newsResults = (body) => body.news_results.flatMap((item) => [
54
71
  ...newsItem(item.highlight),
55
72
  ...item.stories.flatMap((story) => newsItem(story))
56
73
  ]);
74
+ /**
75
+ * Shopping results from the first non-empty of the main, categorized and inline
76
+ * lists. The URL is `link`, else `product_link`.
77
+ */
57
78
  const shoppingResults = (body) => {
58
79
  const categorized = body.categorized_shopping_results.flatMap((group) => group.shopping_results);
59
80
  return ([
@@ -113,6 +134,7 @@ const scholarResults = (body) => body.organic_results.flatMap((item) => {
113
134
  url
114
135
  })];
115
136
  });
137
+ /** Patent results: the URL is `patent_link` and the author is the inventor. */
116
138
  const patentResults = (body) => body.organic_results.flatMap((item) => {
117
139
  const url = item.patent_link;
118
140
  return url === void 0 ? [] : [compact({
@@ -125,7 +147,15 @@ const patentResults = (body) => body.organic_results.flatMap((item) => {
125
147
  url
126
148
  })];
127
149
  });
150
+ /**
151
+ * An answer box's text: its `answer`, else a non-empty `result` (a calculator's),
152
+ * else its `snippet`.
153
+ */
128
154
  const answerOf = (box) => box?.answer ?? (box?.result === "" ? void 0 : box?.result) ?? box?.snippet;
155
+ /**
156
+ * The text of the answer box, or of the first of an answer list when there is no
157
+ * single box.
158
+ */
129
159
  const answerText = (body) => answerOf(body.answer_box ?? body.answer_box_list[0]);
130
160
  const searchMeta = (body) => meta({
131
161
  requestId: body.search_metadata.id,
@@ -134,6 +164,10 @@ const searchMeta = (body) => meta({
134
164
  /** The reason a search failed, or undefined when it did not. */
135
165
  const searchFailure = (body) => body.search_metadata.status === "Error" ? `serpapi search failed: ${body.error.message ?? "no reason given"}` : void 0;
136
166
  // src/adapters/serpapi/options.ts
167
+ /**
168
+ * SerpApi's single-letter codes for the recency windows, as Google's `qdr` and
169
+ * `period_unit` and DuckDuckGo's `df` take them.
170
+ */
137
171
  const RECENCY_CODE = {
138
172
  day: "d",
139
173
  hour: "h",
@@ -141,22 +175,38 @@ const RECENCY_CODE = {
141
175
  week: "w",
142
176
  year: "y"
143
177
  };
178
+ /** The value if it is a string, else undefined. Engine specs read options as `Json`. */
144
179
  const str = (value) => typeof value === "string" ? value : void 0;
180
+ /** The value if it is a number, else undefined. */
145
181
  const count = (value) => typeof value === "number" ? value : void 0;
182
+ /**
183
+ * Google's `gl` code for a country: lower case, and "uk" for "gb", as SerpApi
184
+ * documents.
185
+ */
146
186
  const googleCountry = (value) => {
147
187
  const code = str(value)?.toLowerCase();
148
188
  return code === "gb" ? "uk" : code;
149
189
  };
190
+ /**
191
+ * The value if it is shaped YYYY-MM-DD; refuses anything else. It does not check
192
+ * that the date exists.
193
+ */
150
194
  const isoDate = (name, value) => {
151
195
  if (value === void 0) return;
152
196
  if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/u.test(value)) throw invalidRequest(provider, `${name} must be YYYY-MM-DD`);
153
197
  return value;
154
198
  };
199
+ /** A YYYY-MM-DD date as YYYYMMDD. */
155
200
  const compactDate = (name, value) => isoDate(name, value)?.replaceAll("-", "");
201
+ /**
202
+ * A YYYY-MM-DD date as M/D/YYYY with no leading zeros, the form of Google's custom
203
+ * date range.
204
+ */
156
205
  const usDate = (name, value) => {
157
206
  const [year, month, day] = isoDate(name, value)?.split("-") ?? [];
158
207
  return year === void 0 ? void 0 : `${Number(month)}/${Number(day)}/${year}`;
159
208
  };
209
+ /** A result count that is a whole number from `min` to `max`; refuses any other. */
160
210
  const bounded = (engine, value, min, max) => {
161
211
  if (value === void 0) return;
162
212
  if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) throw invalidRequest(provider, `${engine} limit must be a whole number from ${min} to ${max}`);
@@ -164,6 +214,11 @@ const bounded = (engine, value, min, max) => {
164
214
  };
165
215
  /** The code for the recency window the caller set; undefined when it names none. */
166
216
  const recencyCode = (o) => Object.entries(RECENCY_CODE).find(([name]) => name === o.recency)?.[1];
217
+ /**
218
+ * Google's `tbs`: `qdr:<code>` for `recency`, or a custom range
219
+ * `cdr:1,cd_min:<M/D/YYYY>,cd_max:<M/D/YYYY>` with either end optional. Refuses
220
+ * `recency` with either date.
221
+ */
167
222
  const googleTbs = (o) => {
168
223
  refuseTogether(provider, o, "recency", "publishedAfter");
169
224
  refuseTogether(provider, o, "recency", "publishedBefore");
@@ -177,6 +232,10 @@ const googleTbs = (o) => {
177
232
  before === void 0 ? void 0 : `cd_max:${before}`
178
233
  ].filter((part) => part !== void 0).join(",");
179
234
  };
235
+ /**
236
+ * DuckDuckGo's `df`: a window code, or `YYYY-MM-DD..YYYY-MM-DD`. Refuses "hour",
237
+ * `recency` with either date, and one date without the other.
238
+ */
180
239
  const duckDuckGoFilter = (o) => {
181
240
  refuseTogether(provider, o, "recency", "publishedAfter");
182
241
  refuseTogether(provider, o, "recency", "publishedBefore");
@@ -186,10 +245,16 @@ const duckDuckGoFilter = (o) => {
186
245
  if (o.publishedAfter === void 0 || o.publishedBefore === void 0) throw invalidRequest(provider, "duckduckgo filters a date range by both ends: pass publishedAfter and publishedBefore together");
187
246
  return `${isoDate("publishedAfter", o.publishedAfter)}..${isoDate("publishedBefore", o.publishedBefore)}`;
188
247
  };
248
+ /** Google Patents' `after` or `before` value: `publication:YYYYMMDD`. */
189
249
  const patentDate = (name, value) => {
190
250
  const date = compactDate(name, value);
191
251
  return date === void 0 ? void 0 : `publication:${date}`;
192
252
  };
253
+ /**
254
+ * Google Maps' search origin: `lat` and `lon`, or `location`, with the zoom `z`.
255
+ * Refuses `location` with coordinates, a latitude or longitude without the other,
256
+ * an origin without `zoom`, and `zoom` without an origin.
257
+ */
193
258
  const mapsOrigin = (o) => {
194
259
  refuseTogether(provider, o, "location", "latitude");
195
260
  refuseTogether(provider, o, "location", "longitude");
@@ -206,7 +271,14 @@ const mapsOrigin = (o) => {
206
271
  };
207
272
  };
208
273
  // src/adapters/serpapi/engines.ts
274
+ /**
275
+ * One spec per `SerpApiEngine`. The public types already limit the options, so
276
+ * specs read them untyped, and `allowed` is the runtime check for callers without
277
+ * types. An engine whose `allowed` has no `limit` (Google, Bing, news, maps and
278
+ * shopping) refuses it, because SerpApi documents no result count for it.
279
+ */
209
280
  const ENGINES = {
281
+ /** `country` (sent as lower-case `cc`) and `market` (`mkt`) are alternatives. */
210
282
  bing: {
211
283
  allowed: [
212
284
  "country",
@@ -230,6 +302,7 @@ const ENGINES = {
230
302
  },
231
303
  results: webResults
232
304
  },
305
+ /** `limit` is `m`, 1 to 50; `region` is `kl`; the recency or date filter is `df`. */
233
306
  duckduckgo: {
234
307
  allowed: [
235
308
  "limit",
@@ -250,6 +323,10 @@ const ENGINES = {
250
323
  }),
251
324
  results: webResults
252
325
  },
326
+ /**
327
+ * The only engine whose response also gives the search an `answer`, from the answer
328
+ * box.
329
+ */
253
330
  google: {
254
331
  allowed: [
255
332
  "country",
@@ -274,6 +351,10 @@ const ENGINES = {
274
351
  }),
275
352
  results: webResults
276
353
  },
354
+ /**
355
+ * `type=search` lists places. The origin is `lat` and `lon`, or `location`, with
356
+ * the zoom `z`.
357
+ */
277
358
  google_maps: {
278
359
  allowed: [
279
360
  "language",
@@ -292,6 +373,7 @@ const ENGINES = {
292
373
  }),
293
374
  results: placeResults
294
375
  },
376
+ /** Takes `gl` and `hl` only. */
295
377
  google_news: {
296
378
  allowed: [
297
379
  "country",
@@ -304,6 +386,7 @@ const ENGINES = {
304
386
  }),
305
387
  results: newsResults
306
388
  },
389
+ /** `limit` is `num`, 10 to 100. The dates become `publication:YYYYMMDD`. */
307
390
  google_patents: {
308
391
  allowed: [
309
392
  "limit",
@@ -328,6 +411,7 @@ const ENGINES = {
328
411
  }),
329
412
  results: patentResults
330
413
  },
414
+ /** `limit` is `num`, 1 to 20. `yearFrom` and `yearTo` are `as_ylo` and `as_yhi`. */
331
415
  google_scholar: {
332
416
  allowed: [
333
417
  "limit",
@@ -348,6 +432,7 @@ const ENGINES = {
348
432
  }),
349
433
  results: scholarResults
350
434
  },
435
+ /** The boolean filters are sent only when true. `sortBy` is `sort_by`. */
351
436
  google_shopping: {
352
437
  allowed: [
353
438
  "country",
@@ -379,6 +464,7 @@ const ENGINES = {
379
464
  results: shoppingResults
380
465
  }
381
466
  };
467
+ /** The options `images` takes. Google Images has no `limit`. */
382
468
  const IMAGE_OPTIONS = [
383
469
  "country",
384
470
  "language",
@@ -396,6 +482,10 @@ const IMAGE_OPTIONS = [
396
482
  "license",
397
483
  "noCache"
398
484
  ];
485
+ /**
486
+ * Refuses every set option outside `allowed`, naming all of them. An option set to
487
+ * undefined passes.
488
+ */
399
489
  const onlyAllowed = (engine, options, allowed) => {
400
490
  const refused = Object.keys(options).filter((name) => options[name] !== void 0 && !allowed.includes(name));
401
491
  if (refused.length > 0) throw invalidRequest(provider, `${engine} does not accept ${refused.join(", ")}`);
@@ -434,6 +524,7 @@ const storyShape = {
434
524
  thumbnail: optionalString,
435
525
  title: optionalString
436
526
  };
527
+ /** A news story. */
437
528
  const Story = looseObject(storyShape);
438
529
  /** A news result: a story, or a group with a `highlight` and `stories`. */
439
530
  const NewsResult = looseObject({
@@ -441,6 +532,10 @@ const NewsResult = looseObject({
441
532
  highlight: Story,
442
533
  stories: arrayOf(Story)
443
534
  });
535
+ /**
536
+ * A shopping result. `extracted_price` is the numeric price, `price` the formatted
537
+ * one.
538
+ */
444
539
  const ShoppingItem = looseObject({
445
540
  extracted_price: optionalScalar,
446
541
  link: optionalString,
@@ -452,6 +547,7 @@ const ShoppingItem = looseObject({
452
547
  thumbnail: optionalString,
453
548
  title: optionalString
454
549
  });
550
+ /** A Google Maps place, from `local_results` or a single `place_results`. */
455
551
  const Place = looseObject({
456
552
  address: optionalString,
457
553
  description: optionalString,
@@ -472,6 +568,7 @@ const AnswerBox = looseObject({
472
568
  result: optionalScalar,
473
569
  snippet: optionalString
474
570
  });
571
+ /** A Google Images result: `original` is the full image, `link` its source page. */
475
572
  const ImageItem = looseObject({
476
573
  link: optionalString,
477
574
  original: optionalString,
package/dist/tavily.d.ts CHANGED
@@ -1,16 +1,32 @@
1
- import { K as Recency, Q as SiteMap, R as Page, Y as SearchResponse, _ as Crawl, a as RawClient, j as ImageSearch, l as Answer, p as CallOptions, q as Research, s as AccountUsage, t as Adapter, z as PageBatch } from "./adapter-BgdfLBs-.js";
2
- import { t as OutputSchema } from "./schema-Cupy7-7q.js";
1
+ import { K as Recency, Q as SiteMap, R as Page, Y as SearchResponse, _ as Crawl, a as RawClient, j as ImageSearch, l as Answer, p as CallOptions, q as Research, s as AccountUsage, t as Adapter, z as PageBatch } from "./adapter-Bh8EIrNe.js";
2
+ import { t as OutputSchema } from "./schema-BWWiMvkg.js";
3
+ /** Settings for the Tavily adapter. */
3
4
  interface TavilyConfig {
4
5
  /** Defaults to the TAVILY_API_KEY environment variable. */
5
6
  apiKey?: string;
6
7
  /** Sent as the X-Project-ID header, so Tavily groups usage and logs by project. */
7
8
  projectId?: string;
9
+ /** Defaults to https://api.tavily.com. */
8
10
  baseUrl?: string;
11
+ /** Sends every request instead of the global `fetch`. */
9
12
  fetch?: typeof fetch;
10
13
  /** Repeats of a request that can succeed on repeat; 2 unless set. `0` turns retrying off. */
11
14
  retries?: number;
12
15
  }
16
+ /**
17
+ * How deep a search goes. `advanced` costs 2 credits; `fast` and `ultra-fast`
18
+ * refuse `safeSearch`, and `ultra-fast` refuses `chunksPerSource`.
19
+ */
13
20
  type TavilySearchDepth = "ultra-fast" | "fast" | "basic" | "advanced";
21
+ /**
22
+ * Options for `search`. The adapter throws `InvalidRequest` before sending
23
+ * when `includeDomainsMode` has no `includeDomains`, `filterByLanguage` has no
24
+ * `language`, `imageDescriptions` has no `includeImages`, `safeSearch` or
25
+ * `chunksPerSource` meets a depth that lacks it, `maxAge` is over 30 days, or
26
+ * `country` is not in Tavily's list or `topic` is not `general`.
27
+ *
28
+ * A result's `snippet` is Tavily's passages and its `content` is the page text.
29
+ */
14
30
  interface TavilySearchOptions extends CallOptions {
15
31
  /** Results to return; Tavily allows 0 to 20. */
16
32
  limit?: number;
@@ -37,7 +53,7 @@ interface TavilySearchOptions extends CallOptions {
37
53
  excludeDomains?: string[];
38
54
  /** "restrict" keeps to includeDomains; "prefer" only ranks them higher. */
39
55
  includeDomainsMode?: "restrict" | "prefer";
40
- /** ISO 3166-1 alpha-2 code such as "GB". Ranks that country higher; general topic only. */
56
+ /** ISO 3166-1 alpha-2 code such as "GB". Ranks that country higher; general topic only. Tavily takes country names, so the adapter sends the name for the code. */
41
57
  country?: string;
42
58
  /** ISO 639-1 code. Ranks pages in that language higher. */
43
59
  language?: string;
@@ -49,7 +65,7 @@ interface TavilySearchOptions extends CallOptions {
49
65
  autoParameters?: boolean;
50
66
  /** Only pages containing the quoted phrases in the query. */
51
67
  exactMatch?: boolean;
52
- /** Seconds a cached copy may be old; 0 always fetches live, a negative number never does. Tavily counts hours, up to 720. */
68
+ /** Seconds a cached copy may be old; 0 always fetches live, a negative number never does. Tavily counts hours, so this is rounded up to whole hours, up to 720. */
53
69
  maxAge?: number;
54
70
  /** Include each result's page text; `true` means Markdown. */
55
71
  content?: boolean | "markdown" | "text";
@@ -60,6 +76,7 @@ interface TavilySearchOptions extends CallOptions {
60
76
  /** Return each result's favicon. */
61
77
  favicon?: boolean;
62
78
  }
79
+ /** Options for `images`, which runs a Tavily search and returns the images it finds. */
63
80
  interface TavilyImagesOptions extends CallOptions {
64
81
  searchDepth?: TavilySearchDepth;
65
82
  topic?: "general" | "news" | "finance";
@@ -69,10 +86,16 @@ interface TavilyImagesOptions extends CallOptions {
69
86
  /** Describe each image. Defaults to true. */
70
87
  descriptions?: boolean;
71
88
  }
89
+ /**
90
+ * Options for `answer`, which is a Tavily search with a written answer. It
91
+ * takes the search options except those for page text, images and favicons.
92
+ * The citations are the search results.
93
+ */
72
94
  interface TavilyAnswerOptions extends Omit<TavilySearchOptions, "content" | "includeImages" | "imageDescriptions" | "favicon"> {
73
95
  /** `advanced` writes a more detailed answer. Defaults to `basic`. */
74
96
  answerDepth?: "basic" | "advanced";
75
97
  }
98
+ /** Options for `read`, through Tavily's extract endpoint. */
76
99
  interface TavilyExtractOptions extends CallOptions {
77
100
  /** `advanced` also reads tables and embedded content, and costs 2 credits per 5 pages. */
78
101
  extractDepth?: "basic" | "advanced";
@@ -87,8 +110,11 @@ interface TavilyExtractOptions extends CallOptions {
87
110
  /** Seconds Tavily waits for the page, 1 to 60. Not the same as `timeout`, which is milliseconds on our side. */
88
111
  serverTimeout?: number;
89
112
  }
113
+ /** Options for `read`. The same as `TavilyExtractOptions`. */
90
114
  type TavilyReadOptions = TavilyExtractOptions;
115
+ /** Options for `readMany`, which reads 1 to 20 URLs in one call. The same as `TavilyExtractOptions`. */
91
116
  type TavilyReadManyOptions = TavilyExtractOptions;
117
+ /** How Tavily walks a site, shared by `map` and `crawl`. */
92
118
  interface TavilyTraversal {
93
119
  /** Plain-words instructions that focus the walk. Raises the cost. */
94
120
  instructions?: string;
@@ -109,7 +135,12 @@ interface TavilyTraversal {
109
135
  /** Seconds Tavily works before stopping, 10 to 150. Not the same as `timeout`, which is milliseconds on our side. */
110
136
  serverTimeout?: number;
111
137
  }
138
+ /** Options for `map`. */
112
139
  interface TavilyMapOptions extends CallOptions, TavilyTraversal {}
140
+ /**
141
+ * Options for `crawl`. With `instructions`, each page comes back as `excerpts`
142
+ * instead of `markdown`.
143
+ */
113
144
  interface TavilyCrawlOptions extends CallOptions, TavilyTraversal {
114
145
  extractDepth?: "basic" | "advanced";
115
146
  format?: "markdown" | "text";
@@ -125,6 +156,11 @@ interface TavilyResearchFile {
125
156
  /** The file's text, or its bytes. Sent base64-encoded. */
126
157
  data: string | Uint8Array;
127
158
  }
159
+ /**
160
+ * Options for `research`, which starts a Tavily research task and waits for it
161
+ * as an asynchronous job. The adapter refuses more than 5 files, and file
162
+ * names that do not end in `.txt`, `.md` or `.json`.
163
+ */
128
164
  interface TavilyResearchOptions<T = unknown> extends CallOptions {
129
165
  /** Tavily accepts object, string, integer, number and array types only, and each property needs a description. */
130
166
  schema?: OutputSchema<T>;
@@ -145,6 +181,10 @@ interface TavilyResearchOptions<T = unknown> extends CallOptions {
145
181
  */
146
182
  resume?: string;
147
183
  }
184
+ /**
185
+ * What Tavily can do: search, images, read, readMany, map, crawl, answer,
186
+ * research and usage. `research` is an asynchronous job and accepts `resume`.
187
+ */
148
188
  interface TavilyOperations {
149
189
  search: (query: string, options?: TavilySearchOptions) => Promise<SearchResponse>;
150
190
  images: (query: string, options?: TavilyImagesOptions) => Promise<ImageSearch>;
package/dist/tavily.js CHANGED
@@ -1,8 +1,8 @@
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, M as compact, N as hours, 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 } 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";
2
+ import { r as invalidRequest, t as FieldworkError } from "./errors-DROZyb9T.js";
3
+ import { C as createRawClient, E as segment, M as compact, N as hours, 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 } from "./parse-COHKvfH9.js";
4
+ import { i as startJob, n as requireOutput, r as runJob, t as jobState } from "./job-CWHOfhP_.js";
5
+ import { n as jsonSchemaOf, t as checkOutput } from "./schema-BYcXgfuZ.js";
6
6
  import * as z from "zod/mini";
7
7
  // src/adapters/tavily/countries.ts
8
8
  /** Tavily's country names, by ISO 3166-1 alpha-2 code. */
@@ -41,32 +41,39 @@ const COUNTRIES = new Map(`
41
41
  `.split(",").map((entry) => entry.trim()).map((entry) => [entry.slice(0, 2), entry.slice(3)]));
42
42
  // src/adapters/tavily/parse.ts
43
43
  const provider = "tavily";
44
+ /** The file names `research` takes. */
44
45
  const RESEARCH_FILE = /\.(?:txt|md|json)$/iu;
46
+ /** The passages in Tavily's text, which arrives as one string joined with `[...]`. Undefined when there are none. */
45
47
  const chunks = (content) => {
46
48
  if (content === void 0) return;
47
49
  const parts = content.split(/\s*\[\.\.\.\]\s*/u).map((part) => part.trim()).filter((part) => part !== "");
48
50
  return parts.length > 0 ? parts : void 0;
49
51
  };
52
+ /** Tavily's name for a country code, since Tavily takes names. Throws for a topic other than `general` and for a code Tavily does not list. */
50
53
  const countryName = (code, topic) => {
51
54
  if (topic !== void 0 && topic !== "general") throw invalidRequest(provider, `country only works with topic "general", not "${topic}"`);
52
55
  const name = COUNTRIES.get(code.toUpperCase());
53
56
  if (name === void 0) throw invalidRequest(provider, `has no country for "${code}"; pass an ISO 3166-1 alpha-2 code from its supported list`);
54
57
  return name;
55
58
  };
59
+ /** The images that parsed; undefined when there are none. */
56
60
  const imageResults = (images) => {
57
61
  const items = images.filter((item) => item !== void 0);
58
62
  return items.length > 0 ? items : void 0;
59
63
  };
64
+ /** The credits, request id and response time Tavily reports. */
60
65
  const responseMeta = (body) => meta({
61
66
  credits: body.usage.credits,
62
67
  requestId: body.request_id,
63
68
  units: { responseTimeSeconds: body.response_time }
64
69
  });
70
+ /** Refuses filters that need another option, or a depth that lacks them. */
65
71
  const checkFilters = (o) => {
66
72
  if (o.includeDomainsMode !== void 0 && (o.includeDomains?.length ?? 0) === 0) throw invalidRequest(provider, "includeDomainsMode needs includeDomains");
67
73
  if (o.filterByLanguage === true && o.language === void 0) throw invalidRequest(provider, "filterByLanguage needs language");
68
74
  if (o.safeSearch === true && (o.searchDepth === "fast" || o.searchDepth === "ultra-fast")) throw invalidRequest(provider, `safeSearch is not available with searchDepth "${o.searchDepth}"`);
69
75
  };
76
+ /** Refuses option combinations Tavily does not accept, and returns `maxAge` in whole hours. */
70
77
  const checkSearch = (o) => {
71
78
  checkFilters(o);
72
79
  if (o.chunksPerSource !== void 0 && o.searchDepth === "ultra-fast") throw invalidRequest(provider, "chunksPerSource is not available with searchDepth \"ultra-fast\"");
@@ -75,10 +82,15 @@ const checkSearch = (o) => {
75
82
  if (maxAgeHours !== void 0 && maxAgeHours > 720) throw invalidRequest(provider, "keeps cached copies for at most 30 days (2,592,000 seconds)");
76
83
  return maxAgeHours;
77
84
  };
85
+ /** Tavily's `include_raw_content`: `true` asks for Markdown, `false` for none. */
78
86
  const rawContent = (content) => {
79
87
  if (content === true) return "markdown";
80
88
  return content === false ? void 0 : content;
81
89
  };
90
+ /**
91
+ * The `/search` body. It always asks for usage, so credits are reported, and
92
+ * asks for each result's published date whenever a date window or `recency` is set.
93
+ */
82
94
  const searchBody = (query, o) => {
83
95
  const maxAgeHours = checkSearch(o);
84
96
  const dated = o.recency !== void 0 || o.publishedAfter !== void 0 || o.publishedBefore !== void 0;
@@ -110,6 +122,7 @@ const searchBody = (query, o) => {
110
122
  topic: o.topic
111
123
  });
112
124
  };
125
+ /** Search results: Tavily's `content` (passages) is the `snippet`, its `raw_content` (page text) the `content`. */
113
126
  const searchResults = (body) => body.results.map((result) => compact({
114
127
  content: result.raw_content,
115
128
  favicon: result.favicon,
@@ -119,10 +132,16 @@ const searchResults = (body) => body.results.map((result) => compact({
119
132
  title: result.title,
120
133
  url: result.url ?? ""
121
134
  }));
135
+ /** The URLs Tavily could not read. An entry without a URL is dropped. */
122
136
  const failures = (failed) => failed.flatMap((failure) => failure.url === void 0 ? [] : [{
123
137
  error: failure.error ?? "no content returned",
124
138
  url: failure.url
125
139
  }]);
140
+ /**
141
+ * A page from `/extract` or `/crawl`. When `query` is true, passages were asked
142
+ * for (a `query` on read, `instructions` on crawl) and the text goes to
143
+ * `excerpts`; otherwise it is the page's `markdown`.
144
+ */
126
145
  const page = (entry, query) => {
127
146
  const result = entry.value;
128
147
  return compact({
@@ -134,6 +153,7 @@ const page = (entry, query) => {
134
153
  url: result.url ?? ""
135
154
  });
136
155
  };
156
+ /** The `/extract` body for one or more URLs. `chunksPerSource` needs a `query`. */
137
157
  const extractBody = (urls, o) => {
138
158
  if (o.chunksPerSource !== void 0 && o.query === void 0) throw invalidRequest(provider, "chunksPerSource needs query");
139
159
  return compact({
@@ -148,6 +168,7 @@ const extractBody = (urls, o) => {
148
168
  urls
149
169
  });
150
170
  };
171
+ /** The body fields `map` and `crawl` share. */
151
172
  const traversal = (o) => compact({
152
173
  allow_external: o.allowExternal,
153
174
  exclude_domains: o.excludeDomainPatterns,
@@ -161,6 +182,7 @@ const traversal = (o) => compact({
161
182
  select_paths: o.selectPathPatterns,
162
183
  timeout: o.serverTimeout
163
184
  });
185
+ /** Base64 of the bytes, encoded in 32 KiB steps so a large file does not exceed the argument limit of `fromCodePoint`. */
164
186
  const base64 = (bytes) => {
165
187
  let binary = "";
166
188
  for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCodePoint(...bytes.subarray(index, index + 32768));
@@ -182,6 +204,7 @@ const Image = z.union([z.pipe(z.string(), z.transform((url) => url === "" ? void
182
204
  description: image.description,
183
205
  url: image.url
184
206
  })))]);
207
+ /** A search result. `content` holds Tavily's passages and `raw_content` the page text. */
185
208
  const SearchResult = looseObject({
186
209
  content: optionalString,
187
210
  favicon: optionalString,
@@ -198,12 +221,14 @@ const SearchResponse = looseObject({
198
221
  images: arrayOf(Image),
199
222
  results: arrayOf(SearchResult)
200
223
  });
224
+ /** A page from `/extract` or `/crawl`. `raw_content` is the page text, or passages when a query or instructions were given. */
201
225
  const PageResult = looseObject({
202
226
  favicon: optionalString,
203
227
  images: arrayOf(z.string()),
204
228
  raw_content: optionalString,
205
229
  url: optionalString
206
230
  });
231
+ /** A URL Tavily could not read, with its reason. */
207
232
  const FailedResult = looseObject({
208
233
  error: optionalString,
209
234
  url: optionalString
@@ -246,6 +271,11 @@ const UsageResponse = looseObject({
246
271
  key: looseObject({ usage: optionalNumber })
247
272
  });
248
273
  // src/adapters/tavily.ts
274
+ const RESEARCH_STATES = {
275
+ done: ["completed"],
276
+ failed: ["failed"],
277
+ running: ["pending", "in_progress"]
278
+ };
249
279
  /**
250
280
  * An adapter for Tavily: search, images, read, readMany, map, crawl, answer, research and usage. Pass it to `new Fieldwork({ adapter })`.
251
281
  *
@@ -407,20 +437,23 @@ const tavily = (config = {}) => {
407
437
  query: { include_usage: true }
408
438
  });
409
439
  const parsed = z.parse(ResearchRun, current);
410
- if (parsed.status === "failed") throw new FieldworkError("JobFailed", `tavily research ${id} failed`, {
440
+ const state = jobState(provider, id, RESEARCH_STATES, {
441
+ original: current,
442
+ value: parsed.status
443
+ });
444
+ if (state === "failed") throw new FieldworkError("JobFailed", `tavily research ${id} failed`, {
411
445
  cause: current,
412
446
  provider
413
447
  });
414
- return parsed.status === "completed" ? {
448
+ return state === "done" ? {
415
449
  body: parsed,
416
450
  response: current
417
451
  } : void 0;
418
452
  },
419
453
  finish: async ({ body: run, response }, id) => {
420
- const { content } = run;
421
- if (content === void 0 || content === null || content === "") throw new FieldworkError("JobFailed", `tavily research ${id} finished without output`, {
422
- cause: response,
423
- provider
454
+ const content = requireOutput(provider, id, {
455
+ original: response,
456
+ value: run.content
424
457
  });
425
458
  return compact({
426
459
  id,
@@ -434,8 +467,7 @@ const tavily = (config = {}) => {
434
467
  status: "completed"
435
468
  });
436
469
  },
437
- start: async () => requireJobId(provider, z.parse(ResearchStart, await raw.request("POST", "/research", {
438
- creates: true,
470
+ start: async () => await startJob(raw, "/research", {
439
471
  ...call,
440
472
  body: compact({
441
473
  citation_format: o.citationFormat,
@@ -448,7 +480,7 @@ const tavily = (config = {}) => {
448
480
  output_schema: o.schema === void 0 ? void 0 : jsonSchemaOf(o.schema),
449
481
  stream: false
450
482
  })
451
- })).request_id)
483
+ }, ResearchStart, (reply) => reply.request_id)
452
484
  }, {
453
485
  ...call,
454
486
  interval: o.interval,