@howells/fieldwork-sdk 0.3.1 → 0.5.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.
@@ -1,6 +1,46 @@
1
- import { t as defineAdapter } from "./adapter-CEAQuT7F.js";
2
- import { t as FieldworkError } from "./errors-BiIBG9zN.js";
3
- import { S as requireKey, b as createRawClient, c as num, h as requireId, i as compact, m as refuseTogether, o as list, p as record, s as meta, t as callSettings, u as presentPage, v as text } from "./util-YaZYZDSk.js";
1
+ import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
+ import { r as invalidRequest } from "./errors-Yvk42oZH.js";
3
+ import { C as createRawClient, D as segment, E as requireKey, F as presentPage, N as meta, O as callSettings, R as refuseTogether, S as withOriginal, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, j as compact, m as optionalScalar, r as arrayOf, s as optionalAnyString, z as requireJobId } from "./parse-D4SMt-Ip.js";
4
+ import * as z from "zod/mini";
5
+ // src/adapters/browserbase/response.ts
6
+ /** `POST /v1/sessions`. The id keeps the value as it arrived, for the error raised when there is none. */
7
+ const SessionResponse = looseObject({
8
+ connectUrl: optionalString,
9
+ expiresAt: optionalString,
10
+ id: withOriginal(optionalId)
11
+ });
12
+ /** `GET /v1/sessions/{id}/debug`. */
13
+ const DebugResponse = looseObject({
14
+ debuggerFullscreenUrl: optionalString,
15
+ debuggerUrl: optionalString
16
+ });
17
+ /** `POST /v1/fetch`. An empty `content` is kept as it is. */
18
+ const FetchResponse = looseObject({
19
+ content: optionalAnyString,
20
+ contentType: optionalString,
21
+ encoding: optionalString,
22
+ id: optionalScalar,
23
+ statusCode: optionalNumber
24
+ });
25
+ /** `POST /v1/search`. */
26
+ const SearchResponse = looseObject({
27
+ requestId: optionalScalar,
28
+ results: arrayOf(looseObject({
29
+ author: optionalString,
30
+ favicon: optionalString,
31
+ image: optionalString,
32
+ publishedDate: optionalString,
33
+ title: optionalString,
34
+ url: optionalString
35
+ }))
36
+ });
37
+ /** `GET /v1/projects/{id}/usage`. */
38
+ const UsageResponse = looseObject({
39
+ browserMinutes: optionalNumber,
40
+ proxyBytes: optionalNumber
41
+ });
42
+ /** `GET /v1/projects`: an array of projects. */
43
+ const ProjectsResponse = arrayOf(looseObject({ id: withOriginal(optionalId) }));
4
44
  // src/adapters/browserbase.ts
5
45
  const SEARCH_MODES = {
6
46
  exa: [
@@ -10,30 +50,33 @@ const SEARCH_MODES = {
10
50
  ],
11
51
  parallel: ["fast", "advanced"]
12
52
  };
53
+ /**
54
+ * An adapter for Browserbase: search, read, browser and usage. Pass it to `new Fieldwork({ adapter })`.
55
+ *
56
+ * Throws `Unauthorized` when neither `apiKey` nor `BROWSERBASE_API_KEY` is set.
57
+ */
13
58
  const browserbase = (config = {}) => {
14
59
  const provider = "browserbase";
15
60
  const raw = createRawClient({
16
61
  baseUrl: config.baseUrl ?? "https://api.browserbase.com",
17
62
  fetch: config.fetch,
18
63
  headers: { "x-bb-api-key": requireKey(provider, config.apiKey, "BROWSERBASE_API_KEY") },
19
- provider
64
+ provider,
65
+ retries: config.retries
20
66
  });
21
- const projectId = config.projectId ?? process.env.BROWSERBASE_PROJECT_ID;
22
- const invalid = (message) => {
23
- throw new FieldworkError("InvalidRequest", `${provider} ${message}`, { provider });
24
- };
67
+ const { projectId } = config;
25
68
  const fetchProxies = (o) => {
26
69
  refuseTogether(provider, o, "proxies", "country");
27
70
  const geolocation = o.country === void 0 ? void 0 : { country: o.country.toUpperCase() };
28
71
  const proxies = o.proxies ?? (geolocation ? { geolocation } : void 0);
29
72
  const place = typeof proxies === "object" ? proxies.geolocation : void 0;
30
- if (place?.state && place.country.toUpperCase() !== "US") invalid("accepts a proxy state only with country US");
73
+ if (place !== void 0 && place.state !== void 0 && place.state !== "" && place.country.toUpperCase() !== "US") throw invalidRequest(provider, "accepts a proxy state only with country US");
31
74
  return proxies;
32
75
  };
33
76
  const liveView = async (id, call) => {
34
77
  try {
35
- const urls = record(await raw.request("GET", `/v1/sessions/${encodeURIComponent(id)}/debug`, call));
36
- return { url: text(urls.debuggerFullscreenUrl) ?? text(urls.debuggerUrl) };
78
+ const urls = z.parse(DebugResponse, await raw.request("GET", `/v1/sessions/${segment(id)}/debug`, call));
79
+ return { url: urls.debuggerFullscreenUrl ?? urls.debuggerUrl };
37
80
  } catch (error) {
38
81
  return { warning: `could not get the live view URL: ${error instanceof Error ? error.message : String(error)}` };
39
82
  }
@@ -42,7 +85,7 @@ const browserbase = (config = {}) => {
42
85
  browser: {
43
86
  async close(id, options) {
44
87
  const { call } = callSettings(options);
45
- await raw.request("POST", `/v1/sessions/${encodeURIComponent(id)}`, {
88
+ await raw.request("POST", `/v1/sessions/${segment(id)}`, {
46
89
  ...call,
47
90
  body: { status: "REQUEST_RELEASE" }
48
91
  });
@@ -68,7 +111,8 @@ const browserbase = (config = {}) => {
68
111
  verified: o.verified,
69
112
  viewport: o.viewport
70
113
  });
71
- const session = record(await raw.request("POST", "/v1/sessions", {
114
+ const response = await raw.request("POST", "/v1/sessions", {
115
+ creates: true,
72
116
  ...call,
73
117
  body: compact({
74
118
  browserSettings: Object.keys(browserSettings).length > 0 ? browserSettings : void 0,
@@ -79,23 +123,24 @@ const browserbase = (config = {}) => {
79
123
  timeout: o.ttl,
80
124
  userMetadata: o.userMetadata
81
125
  })
82
- }));
83
- const id = requireId(provider, session.id);
126
+ });
127
+ const session = z.parse(SessionResponse, response);
128
+ const id = requireJobId(provider, session.id);
84
129
  const view = await liveView(id, call);
85
130
  return compact({
86
- cdpUrl: text(session.connectUrl),
87
- expiresAt: text(session.expiresAt),
131
+ cdpUrl: session.connectUrl,
132
+ expiresAt: session.expiresAt,
88
133
  id,
89
134
  liveViewUrl: view.url,
90
135
  meta: meta({ warnings: view.warning }),
91
- raw: session
136
+ raw: response
92
137
  });
93
138
  }
94
139
  },
95
140
  async read(url, options) {
96
141
  const { call, rest: o } = callSettings(options);
97
142
  const format = o.format ?? "markdown";
98
- const response = record(await raw.request("POST", "/v1/fetch", {
143
+ const response = await raw.request("POST", "/v1/fetch", {
99
144
  ...call,
100
145
  body: compact({
101
146
  allowInsecureSsl: o.allowInsecureSsl,
@@ -105,30 +150,31 @@ const browserbase = (config = {}) => {
105
150
  proxies: fetchProxies(o),
106
151
  url
107
152
  })
108
- }));
109
- const content = typeof response.content === "string" ? response.content : void 0;
110
- const binary = response.encoding === "base64";
111
- const contentType = text(response.contentType) ?? "";
153
+ });
154
+ const body = z.parse(FetchResponse, response);
155
+ const { content } = body;
156
+ const binary = body.encoding === "base64";
157
+ const contentType = body.contentType ?? "";
112
158
  return presentPage(provider, compact({
113
159
  markdown: format === "markdown" && !binary ? content : void 0,
114
160
  meta: meta({
115
- requestId: response.id,
161
+ requestId: body.id,
116
162
  warnings: binary ? ["the response is binary; its Base64 content is in raw"] : void 0
117
163
  }),
118
164
  raw: response,
119
165
  rawHtml: format === "raw" && !binary && contentType.includes("html") ? content : void 0,
120
- statusCode: num(response.statusCode),
166
+ statusCode: body.statusCode,
121
167
  url
122
168
  }));
123
169
  },
124
170
  async search(query, options) {
125
171
  const { call, rest: o } = callSettings(options);
126
172
  if (o.mode !== void 0) {
127
- if (o.provider === void 0) invalid("accepts a search mode only together with provider");
173
+ if (o.provider === void 0) throw invalidRequest(provider, "accepts a search mode only together with provider");
128
174
  const allowed = SEARCH_MODES[o.provider];
129
- if (!allowed.includes(o.mode)) invalid(`search provider ${o.provider} has no mode ${o.mode}; use ${allowed.join(", ")}`);
175
+ if (!allowed.includes(o.mode)) throw invalidRequest(provider, `search provider ${o.provider} has no mode ${o.mode}; use ${allowed.join(", ")}`);
130
176
  }
131
- const response = record(await raw.request("POST", "/v1/search", {
177
+ const response = await raw.request("POST", "/v1/search", {
132
178
  ...call,
133
179
  body: compact({
134
180
  mode: o.mode,
@@ -136,40 +182,42 @@ const browserbase = (config = {}) => {
136
182
  provider: o.provider,
137
183
  query
138
184
  })
139
- }));
185
+ });
186
+ const body = z.parse(SearchResponse, response);
140
187
  return compact({
141
- meta: meta({ requestId: response.requestId }),
188
+ meta: meta({ requestId: body.requestId }),
142
189
  raw: response,
143
- results: list(response.results).map((item) => {
144
- const result = record(item);
145
- return compact({
146
- author: text(result.author),
147
- favicon: text(result.favicon),
148
- image: text(result.image),
149
- publishedAt: text(result.publishedDate),
150
- title: text(result.title),
151
- url: text(result.url) ?? ""
152
- });
153
- })
190
+ results: body.results.map((result) => compact({
191
+ author: result.author,
192
+ favicon: result.favicon,
193
+ image: result.image,
194
+ publishedAt: result.publishedDate,
195
+ title: result.title,
196
+ url: result.url ?? ""
197
+ }))
154
198
  });
155
199
  },
156
200
  async usage(options) {
157
201
  const { call } = callSettings(options);
158
202
  const id = projectId ?? await onlyProject(call);
159
- const response = record(await raw.request("GET", `/v1/projects/${encodeURIComponent(id)}/usage`, call));
203
+ const response = await raw.request("GET", `/v1/projects/${segment(id)}/usage`, call);
204
+ const body = z.parse(UsageResponse, response);
160
205
  return compact({
161
- breakdown: compact({
162
- browserMinutes: num(response.browserMinutes),
163
- proxyBytes: num(response.proxyBytes)
164
- }),
206
+ breakdown: Object.fromEntries(Object.entries({
207
+ browserMinutes: body.browserMinutes,
208
+ proxyBytes: body.proxyBytes
209
+ }).filter((entry) => entry[1] !== void 0)),
165
210
  raw: response
166
211
  });
167
212
  }
168
213
  };
169
214
  const onlyProject = async (call) => {
170
- const projects = list(await raw.request("GET", "/v1/projects", call));
171
- if (projects.length !== 1) invalid(`usage needs a project: pass projectId or set BROWSERBASE_PROJECT_ID (this key has ${projects.length} projects)`);
172
- return requireId(provider, record(projects[0]).id);
215
+ const projects = z.parse(ProjectsResponse, await raw.request("GET", "/v1/projects", call));
216
+ if (projects.length !== 1) throw invalidRequest(provider, `usage needs a project: pass projectId (this key has ${projects.length} projects)`);
217
+ return requireJobId(provider, projects[0]?.id ?? {
218
+ original: void 0,
219
+ value: void 0
220
+ });
173
221
  };
174
222
  return defineAdapter({
175
223
  name: provider,
@@ -0,0 +1,51 @@
1
+ import { t as FieldworkError } from "./errors-Yvk42oZH.js";
2
+ // src/document.ts
3
+ /** Content types of the document files parsers commonly take, by extension. */
4
+ const MEDIA_TYPES = new Map(Object.entries({
5
+ csv: "text/csv",
6
+ doc: "application/msword",
7
+ docm: "application/vnd.ms-word.document.macroEnabled.12",
8
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
9
+ epub: "application/epub+zip",
10
+ htm: "text/html",
11
+ html: "text/html",
12
+ odp: "application/vnd.oasis.opendocument.presentation",
13
+ ods: "application/vnd.oasis.opendocument.spreadsheet",
14
+ odt: "application/vnd.oasis.opendocument.text",
15
+ pdf: "application/pdf",
16
+ ppt: "application/vnd.ms-powerpoint",
17
+ pptm: "application/vnd.ms-powerpoint.presentation.macroEnabled.12",
18
+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
19
+ rtf: "application/rtf",
20
+ xhtml: "application/xhtml+xml",
21
+ xls: "application/vnd.ms-excel",
22
+ xlsb: "application/vnd.ms-excel.sheet.binary.macroEnabled.12",
23
+ xlsm: "application/vnd.ms-excel.sheet.macroEnabled.12",
24
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
25
+ }));
26
+ /** The content type the file's extension names, or undefined for one not listed. */
27
+ const mediaTypeOf = (name) => MEDIA_TYPES.get(name.split(".").pop()?.toLowerCase() ?? "");
28
+ /** Refuses a file larger than the provider takes, before it is sent. */
29
+ const refuseLarger = (provider, document, maxMegabytes) => {
30
+ const size = document.data instanceof Blob ? document.data.size : document.data.byteLength;
31
+ if (size > maxMegabytes * 1024 * 1024) throw new FieldworkError("InvalidRequest", `${provider} parses files up to ${maxMegabytes} MB; ${document.name} is ${(size / 1024 / 1024).toFixed(1)} MB`, { provider });
32
+ };
33
+ /** The file's bytes as a multipart part, with the content type its extension names. */
34
+ const documentPart = (document) => {
35
+ const part = document.data instanceof Uint8Array ? new Uint8Array(document.data) : document.data;
36
+ return new Blob([part], { type: mediaTypeOf(document.name) ?? "application/octet-stream" });
37
+ };
38
+ /** The smallest box that holds every one of `boxes`, or undefined when there are none. */
39
+ const enclosing = (boxes) => {
40
+ if (boxes.length <= 1) return boxes[0];
41
+ const left = Math.min(...boxes.map((box) => box.left));
42
+ const top = Math.min(...boxes.map((box) => box.top));
43
+ const right = Math.max(...boxes.map((box) => box.left + box.width));
44
+ return {
45
+ height: Math.max(...boxes.map((box) => box.top + box.height)) - top,
46
+ left,
47
+ top,
48
+ width: right - left
49
+ };
50
+ };
51
+ export { refuseLarger as a, mediaTypeOf as i, documentPart as n, enclosing as r, MEDIA_TYPES as t };
@@ -62,4 +62,6 @@ const codeForStatus = (status) => {
62
62
  if (status === 400 || status === 422) return "InvalidRequest";
63
63
  return "ProviderError";
64
64
  };
65
- export { codeForStatus as n, withJob as r, FieldworkError as t };
65
+ /** A request refused before it is sent, with the provider's name leading the message. */
66
+ const invalidRequest = (provider, message) => new FieldworkError("InvalidRequest", `${provider} ${message}`, { provider });
67
+ export { withJob as i, codeForStatus as n, invalidRequest as r, FieldworkError as t };
package/dist/exa.d.ts CHANGED
@@ -1,9 +1,12 @@
1
- import { A as JsonSchema, F as MonitorSchedule, G as Research, I as Page, L as PageBatch, N as MonitorEvents, P as MonitorInfo, a as RawClient, f as CallOptions, l as Answer, q as SearchResponse, t as Adapter, w as Extraction } from "./adapter-DGehHCMo.js";
1
+ import { E as Extraction, F as MonitorEvents, I as MonitorInfo, L as MonitorSchedule, R as Page, Y as SearchResponse, a as RawClient, l as Answer, p as CallOptions, q as Research, t as Adapter, z as PageBatch } from "./adapter-BgdfLBs-.js";
2
+ import { t as OutputSchema } from "./schema-Cupy7-7q.js";
2
3
  interface ExaConfig {
3
4
  /** Defaults to the EXA_API_KEY environment variable. */
4
5
  apiKey?: string;
5
6
  baseUrl?: string;
6
7
  fetch?: typeof fetch;
8
+ /** Repeats of a request that can succeed on repeat; 2 unless set. `0` turns retrying off. */
9
+ retries?: number;
7
10
  }
8
11
  /**
9
12
  * Exa's `outputSchema` for generated output: free text, or an object schema.
@@ -100,23 +103,24 @@ interface ExaReadOptions extends CallOptions {
100
103
  imageLimit?: number;
101
104
  }
102
105
  type ExaReadManyOptions = ExaReadOptions;
103
- interface ExaExtractOptions extends CallOptions {
104
- schema: JsonSchema;
106
+ interface ExaExtractOptions<T = unknown> extends CallOptions {
107
+ /** A JSON Schema, or a Zod, Valibot or ArkType schema that types and checks `data`. */
108
+ schema: OutputSchema<T>;
105
109
  /** What to extract, in plain words. */
106
110
  prompt?: string;
107
111
  /** Seconds a cached copy may be old; 0 fetches fresh. */
108
112
  maxAge?: number;
109
113
  }
110
- interface ExaAnswerOptions extends CallOptions {
111
- /** JSON Schema (draft 7) for the answer; the answer comes back as an object. */
112
- schema?: JsonSchema;
114
+ interface ExaAnswerOptions<T = unknown> extends CallOptions {
115
+ /** JSON Schema (draft 7) or a Standard Schema for the answer; the answer comes back as an object. */
116
+ schema?: OutputSchema<T>;
113
117
  systemPrompt?: string;
114
118
  /** Two-letter country code that localizes the search. */
115
119
  country?: string;
116
120
  model?: "exa" | "exa-pro" | "exa-research" | "exa-fast";
117
121
  }
118
- interface ExaResearchOptions extends CallOptions {
119
- schema?: JsonSchema;
122
+ interface ExaResearchOptions<T = unknown> extends CallOptions {
123
+ schema?: OutputSchema<T>;
120
124
  /** Cost and reasoning preference. Defaults to `auto`. */
121
125
  effort?: "minimal" | "low" | "medium" | "high" | "xhigh" | "auto" | "ultra";
122
126
  /** Spend cap in dollars, 1 to 100. Only `auto` and `ultra` accept it. */
@@ -172,20 +176,25 @@ interface ExaMonitorEventsOptions extends CallOptions {
172
176
  limit?: number;
173
177
  }
174
178
  type ExaMonitor = {
175
- create(options: ExaMonitorCreateOptions): Promise<MonitorInfo>;
176
- get(id: string, options?: CallOptions): Promise<MonitorInfo>;
177
- list(options?: CallOptions): Promise<MonitorInfo[]>;
178
- delete(id: string, options?: CallOptions): Promise<void>;
179
- events(id: string, options?: ExaMonitorEventsOptions): Promise<MonitorEvents>;
179
+ create: (options: ExaMonitorCreateOptions) => Promise<MonitorInfo>;
180
+ get: (id: string, options?: CallOptions) => Promise<MonitorInfo>;
181
+ list: (options?: CallOptions) => Promise<MonitorInfo[]>;
182
+ delete: (id: string, options?: CallOptions) => Promise<void>;
183
+ events: (id: string, options?: ExaMonitorEventsOptions) => Promise<MonitorEvents>;
180
184
  };
181
185
  interface ExaOperations {
182
- search(query: string, options?: ExaSearchOptions): Promise<SearchResponse>;
183
- read(url: string, options?: ExaReadOptions): Promise<Page>;
184
- readMany(urls: string[], options?: ExaReadManyOptions): Promise<PageBatch>;
185
- extract<T = unknown>(url: string, options: ExaExtractOptions): Promise<Extraction<T>>;
186
- answer<T = unknown>(question: string, options?: ExaAnswerOptions): Promise<Answer<T>>;
187
- research<T = unknown>(question: string, options?: ExaResearchOptions): Promise<Research<T>>;
186
+ search: (query: string, options?: ExaSearchOptions) => Promise<SearchResponse>;
187
+ read: (url: string, options?: ExaReadOptions) => Promise<Page>;
188
+ readMany: (urls: string[], options?: ExaReadManyOptions) => Promise<PageBatch>;
189
+ extract: <T = unknown>(url: string, options: ExaExtractOptions<T>) => Promise<Extraction<T>>;
190
+ answer: <T = unknown>(question: string, options?: ExaAnswerOptions<T>) => Promise<Answer<T>>;
191
+ research: <T = unknown>(question: string, options?: ExaResearchOptions<T>) => Promise<Research<T>>;
188
192
  monitor: ExaMonitor;
189
193
  }
194
+ /**
195
+ * An adapter for Exa: search, read, readMany, extract, answer, research and monitor. Pass it to `new Fieldwork({ adapter })`.
196
+ *
197
+ * Throws `Unauthorized` when neither `apiKey` nor `EXA_API_KEY` is set.
198
+ */
190
199
  export declare const exa: (config?: ExaConfig) => Adapter<"exa", ExaOperations, RawClient>;
191
200
  export type { ExaAnswerOptions, ExaConfig, ExaExtractOptions, ExaHighlightOptions, ExaMonitor, ExaMonitorCreateOptions, ExaMonitorEventsOptions, ExaOperations, ExaOutputSchema, ExaReadManyOptions, ExaReadOptions, ExaResearchOptions, ExaSearchOptions, ExaWebhookEvent };