@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.
@@ -0,0 +1,510 @@
1
+ import { i as withJob, n as codeForStatus, t as FieldworkError } from "./errors-Yvk42oZH.js";
2
+ import * as z from "zod/mini";
3
+ // src/util.ts
4
+ const isJson = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5
+ const record = (value) => isJson(value) ? value : {};
6
+ const compact = (value) => Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0));
7
+ /**
8
+ * Splits an operation's options into the provider's own and the call's
9
+ * settings. The call's `signal` also carries its `timeout` as a deadline, set
10
+ * now, so every request the operation makes (a start, each poll, a result
11
+ * download) shares one budget instead of restarting it. An empty `resume`
12
+ * names no job, so it is refused here, once for every adapter.
13
+ *
14
+ * `grace` extends the deadline past `timeout` for an operation that sends the
15
+ * timeout to the provider and needs a moment more to hear its report.
16
+ */
17
+ const callSettings = (options, grace = 0) => {
18
+ const { retries, signal, timeout, ...rest } = options ?? {};
19
+ if ("resume" in rest && rest.resume === "") throw new FieldworkError("InvalidRequest", "resume is empty: pass the jobId an earlier call returned, or leave resume out to start a job");
20
+ return {
21
+ call: {
22
+ retries,
23
+ signal: timeout === void 0 ? signal : AbortSignal.any([...signal === void 0 ? [] : [signal], AbortSignal.timeout(timeout + grace)]),
24
+ timeout
25
+ },
26
+ rest
27
+ };
28
+ };
29
+ const parseJson = (provider, value) => {
30
+ if (typeof value !== "string") return value;
31
+ try {
32
+ return JSON.parse(value);
33
+ } catch (error) {
34
+ throw new FieldworkError("ProviderError", `${provider} returned output that is not valid JSON`, {
35
+ cause: error,
36
+ provider
37
+ });
38
+ }
39
+ };
40
+ const uniqueCitations = (all) => {
41
+ const seen = /* @__PURE__ */ new Map();
42
+ for (const item of all) if (!seen.has(item.url)) seen.set(item.url, item);
43
+ return [...seen.values()];
44
+ };
45
+ /** The citation a parsed source amounts to, or undefined when it has no URL. */
46
+ const citationOf = (source) => source.url === void 0 ? void 0 : compact({
47
+ excerpts: source.excerpts,
48
+ title: source.title,
49
+ url: source.url
50
+ });
51
+ /** The citations the parsed sources amount to; a source without a URL is left out. */
52
+ const citationsOf = (sources) => sources.map((source) => citationOf(source)).filter((item) => item !== void 0);
53
+ /** The job id a start call returned, or a ProviderError carrying the value as it arrived. */
54
+ const requireJobId = (provider, id) => {
55
+ if (id.value === void 0) throw new FieldworkError("ProviderError", `${provider} did not return a job id`, {
56
+ cause: id.original,
57
+ provider
58
+ });
59
+ return id.value;
60
+ };
61
+ const meta = (parts) => {
62
+ const units = Object.fromEntries(Object.entries(parts.units ?? {}).filter((entry) => entry[1] !== void 0));
63
+ const usage = compact({
64
+ costUsd: parts.costUsd,
65
+ credits: parts.credits,
66
+ units: Object.keys(units).length > 0 ? units : void 0
67
+ });
68
+ const warnings = [parts.warnings ?? []].flat();
69
+ const result = compact({
70
+ requestId: parts.requestId,
71
+ usage: Object.keys(usage).length > 0 ? usage : void 0,
72
+ warnings: warnings.length > 0 ? warnings : void 0
73
+ });
74
+ return Object.keys(result).length > 0 ? result : void 0;
75
+ };
76
+ const refuseTogether = (provider, options, ...names) => {
77
+ const set = names.filter((name) => options[name] !== void 0);
78
+ if (set.length > 1) throw new FieldworkError("InvalidRequest", `${provider} does not accept ${set.join(" and ")} together; pass one`, { provider });
79
+ };
80
+ const hours = (seconds) => seconds === void 0 ? void 0 : seconds < 0 ? -1 : Math.ceil(seconds / 3600);
81
+ /** Statuses that mean the page is not there, so a read of it has no page to return. */
82
+ const GONE = /* @__PURE__ */ new Set([404, 410]);
83
+ /**
84
+ * A read whose page answered 404 or 410 fails as NotFound, as it does on
85
+ * providers that return no page at all, instead of returning the error page
86
+ * as if it were the content.
87
+ */
88
+ const presentPage = (provider, page) => {
89
+ if (page.statusCode !== void 0 && GONE.has(page.statusCode)) throw new FieldworkError("NotFound", `${provider} could not read ${page.url}: the page returned ${page.statusCode}`, {
90
+ provider,
91
+ status: page.statusCode
92
+ });
93
+ return page;
94
+ };
95
+ /** Splits a batch's pages into those present and those that answered 404 or 410. */
96
+ const presentPages = (pages) => ({
97
+ gone: pages.filter((page) => page.statusCode !== void 0 && GONE.has(page.statusCode)).map((page) => ({
98
+ error: `the page returned ${page.statusCode}`,
99
+ url: page.url
100
+ })),
101
+ pages: pages.filter((page) => page.statusCode === void 0 || !GONE.has(page.statusCode))
102
+ });
103
+ const sleep = async (ms, signal) => {
104
+ await new Promise((resolve) => {
105
+ const timer = setTimeout(resolve, ms);
106
+ signal?.addEventListener("abort", () => {
107
+ clearTimeout(timer);
108
+ resolve();
109
+ }, { once: true });
110
+ });
111
+ };
112
+ /** The longest wait between attempts; a provider asking for longer gets the error instead. */
113
+ const MAX_RETRY_WAIT = 3e4;
114
+ const FIRST_RETRY_WAIT = 500;
115
+ /**
116
+ * Milliseconds to wait before repeating a failed request, or undefined when it
117
+ * should not be repeated: the attempts are used up, the call was cancelled or
118
+ * timed out, the failure would recur, or the request created something.
119
+ */
120
+ const retryDelay = (error, state) => {
121
+ if (state.count >= state.retries || state.signal?.aborted === true || !error.retryable || error.code === "Timeout" && error.status === void 0 || state.creates && error.code !== "RateLimited") return;
122
+ if (error.retryAfter !== void 0) {
123
+ const asked = error.retryAfter * 1e3;
124
+ return asked > MAX_RETRY_WAIT ? void 0 : asked;
125
+ }
126
+ const ceiling = Math.min(MAX_RETRY_WAIT, FIRST_RETRY_WAIT * 2 ** state.count);
127
+ return ceiling / 2 + Math.random() * (ceiling / 2);
128
+ };
129
+ /** Whether a stopped signal's deadline ran out, rather than its caller cancelling. */
130
+ const timedOut = (signal) => signal.reason instanceof DOMException && signal.reason.name === "TimeoutError";
131
+ /**
132
+ * The error for a call its signal stopped: `Timeout` when the signal's
133
+ * deadline ran out (a call's `timeout` is a deadline signal across all its
134
+ * requests), `Aborted` when the caller cancelled.
135
+ */
136
+ const stopped = (signal, message, options) => new FieldworkError(timedOut(signal) ? "Timeout" : "Aborted", message, options);
137
+ const transportError = (provider, error, signal) => {
138
+ if (signal?.aborted === true) return stopped(signal, `${provider} request stopped: ${timedOut(signal) ? "timed out" : "cancelled"}`, {
139
+ cause: error,
140
+ provider
141
+ });
142
+ if (error instanceof DOMException && error.name === "TimeoutError") return new FieldworkError("Timeout", `${provider} request timed out`, {
143
+ cause: error,
144
+ provider
145
+ });
146
+ return new FieldworkError("ProviderError", `${provider} request failed: ${String(error)}`, {
147
+ cause: error,
148
+ provider,
149
+ retryable: true
150
+ });
151
+ };
152
+ /** A response's body; a connection lost while it streams is a transport error like any other. */
153
+ const readText = async (provider, response, signal) => {
154
+ try {
155
+ return await response.text();
156
+ } catch (error) {
157
+ throw transportError(provider, error, signal);
158
+ }
159
+ };
160
+ const createRawClient = (config) => {
161
+ const doFetch = config.fetch ?? globalThis.fetch;
162
+ return {
163
+ baseUrl: config.baseUrl,
164
+ provider: config.provider,
165
+ async request(method, path, options = {}) {
166
+ const url = new URL(config.baseUrl.replace(/\/$/u, "") + path);
167
+ for (const [key, value] of Object.entries(options.query ?? {})) if (value !== void 0) url.searchParams.set(key, String(value));
168
+ const headers = new Headers({
169
+ accept: "application/json",
170
+ ...config.headers
171
+ });
172
+ let body;
173
+ if (options.form) body = options.form;
174
+ else if (options.body !== void 0) {
175
+ headers.set("content-type", "application/json");
176
+ body = JSON.stringify(options.body);
177
+ }
178
+ const signal = combineSignals(options.signal, options.timeout);
179
+ const send = async (request) => {
180
+ try {
181
+ return await doFetch(request.url, {
182
+ body: request.body,
183
+ headers,
184
+ method: request.method,
185
+ redirect: "manual",
186
+ signal
187
+ });
188
+ } catch (error) {
189
+ throw transportError(config.provider, error, options.signal);
190
+ }
191
+ };
192
+ const once = async () => {
193
+ const response = await followRedirects(config.provider, send, {
194
+ body,
195
+ method,
196
+ url
197
+ });
198
+ const text = await readText(config.provider, response, signal);
199
+ const json = jsonOf(text);
200
+ const parsed = json === void 0 ? text : json.value;
201
+ if (response.ok) {
202
+ if (options.text !== true && json === void 0) throw new FieldworkError("ProviderError", `${config.provider} ${method} ${path} returned ${response.status} with a body that is not JSON: ${text.slice(0, 300)}`, {
203
+ cause: text,
204
+ provider: config.provider,
205
+ status: response.status
206
+ });
207
+ return options.text === true ? text : parsed;
208
+ }
209
+ throw new FieldworkError(codeForStatus(response.status), `${config.provider} ${method} ${path} returned ${response.status}: ${describe(parsed, text)}`, {
210
+ cause: parsed,
211
+ provider: config.provider,
212
+ retryAfter: retryAfterSeconds(response.headers.get("retry-after")),
213
+ status: response.status
214
+ });
215
+ };
216
+ const retries = options.retries ?? config.retries ?? 2;
217
+ const deadline = options.timeout === void 0 ? void 0 : Date.now() + options.timeout;
218
+ const attempt = async (count) => {
219
+ try {
220
+ return await once();
221
+ } catch (error) {
222
+ if (!(error instanceof FieldworkError)) throw error;
223
+ const wait = retryDelay(error, {
224
+ count,
225
+ creates: options.creates === true,
226
+ retries,
227
+ signal
228
+ });
229
+ if (wait === void 0 || deadline !== void 0 && Date.now() + wait >= deadline) throw error;
230
+ await sleep(wait, signal);
231
+ if (options.signal?.aborted === true) throw stopped(options.signal, `${config.provider} request stopped while waiting to retry`, {
232
+ cause: error,
233
+ provider: config.provider
234
+ });
235
+ return await attempt(count + 1);
236
+ }
237
+ };
238
+ return await attempt(0);
239
+ }
240
+ };
241
+ };
242
+ const REDIRECTS = /* @__PURE__ */ new Set([
243
+ 301,
244
+ 302,
245
+ 303,
246
+ 307,
247
+ 308
248
+ ]);
249
+ const MAX_REDIRECTS = 5;
250
+ /**
251
+ * Follows a provider's redirects only within its own origin, so the key in
252
+ * the request's headers or query never reaches another host. A redirect to
253
+ * another origin, scheme or port fails before anything is sent there.
254
+ */
255
+ const followRedirects = async (provider, send, first) => {
256
+ let hop = first;
257
+ for (let count = 0; count <= MAX_REDIRECTS; count += 1) {
258
+ const response = await send(hop);
259
+ if (response.type === "opaqueredirect") throw new FieldworkError("ProviderError", `${provider} redirected the request, and this runtime hides where to; Fieldwork does not follow it`, { provider });
260
+ const location = response.headers.get("location");
261
+ if (!REDIRECTS.has(response.status) || location === null) return response;
262
+ const target = new URL(location, hop.url);
263
+ if (target.origin !== first.url.origin) throw new FieldworkError("ProviderError", `${provider} redirected the request to ${target.origin}; Fieldwork follows redirects only within ${first.url.origin}, so the key was not sent`, {
264
+ provider,
265
+ status: response.status
266
+ });
267
+ hop = response.status === 303 || (response.status === 301 || response.status === 302) && hop.method === "POST" ? {
268
+ body: void 0,
269
+ method: "GET",
270
+ url: target
271
+ } : {
272
+ ...hop,
273
+ url: target
274
+ };
275
+ }
276
+ throw new FieldworkError("ProviderError", `${provider} redirected the request more than ${MAX_REDIRECTS} times`, { provider });
277
+ };
278
+ const combineSignals = (signal, timeout) => {
279
+ const signals = [signal, timeout === void 0 ? void 0 : AbortSignal.timeout(timeout)].filter((value) => value !== void 0);
280
+ return signals.length <= 1 ? signals[0] : AbortSignal.any(signals);
281
+ };
282
+ /** The body's JSON, or undefined when the body is not JSON. An empty body is JSON with no value. */
283
+ const jsonOf = (text) => {
284
+ if (text === "") return { value: void 0 };
285
+ try {
286
+ return { value: JSON.parse(text) };
287
+ } catch {
288
+ return;
289
+ }
290
+ };
291
+ const describe = (parsed, text) => {
292
+ const body = record(parsed);
293
+ for (const key of [
294
+ "error",
295
+ "message",
296
+ "detail"
297
+ ]) {
298
+ const value = body[key];
299
+ if (typeof value === "string") return value;
300
+ if (typeof value === "object" && value !== null) return JSON.stringify(value).slice(0, 300);
301
+ }
302
+ return text.slice(0, 300);
303
+ };
304
+ const retryAfterSeconds = (header, now = Date.now()) => {
305
+ if (header === null || header === "") return;
306
+ const seconds = Number(header);
307
+ if (Number.isFinite(seconds)) return seconds;
308
+ const date = Date.parse(header);
309
+ return Number.isNaN(date) ? void 0 : Math.max(0, Math.ceil((date - now) / 1e3));
310
+ };
311
+ /**
312
+ * Checks a job until `check` returns its result. Each check is given the
313
+ * settings for its request: the call's signal, which carries the call's whole
314
+ * deadline, and its retries. A check that throws, a cancellation and a
315
+ * timeout all surface with `jobId`, so the caller can resume the job.
316
+ */
317
+ const poll = async (provider, jobId, check, options = {}) => {
318
+ const interval = options.interval ?? 2e3;
319
+ const deadline = Date.now() + (options.timeout ?? 6e5);
320
+ const request = {
321
+ retries: options.retries,
322
+ signal: options.signal
323
+ };
324
+ for (;;) {
325
+ if (options.signal?.aborted === true) throw stopped(options.signal, `stopped waiting for ${provider} job ${jobId}; it may still be running`, {
326
+ jobId,
327
+ provider
328
+ });
329
+ let value;
330
+ try {
331
+ value = await check(request);
332
+ } catch (error) {
333
+ throw withJob(error, jobId);
334
+ }
335
+ if (value !== void 0) return value;
336
+ if (Date.now() + interval > deadline) throw new FieldworkError("Timeout", `${provider} job ${jobId} did not finish in time; it may still be running`, {
337
+ jobId,
338
+ provider
339
+ });
340
+ await sleep(interval, options.signal);
341
+ }
342
+ };
343
+ /** An id as one path segment, so a caller's `resume` cannot reach another endpoint. */
344
+ const segment = (id) => encodeURIComponent(id);
345
+ const requireKey = (provider, given, envName) => {
346
+ const key = given ?? process.env[envName];
347
+ if (key === void 0 || key === "") throw new FieldworkError("Unauthorized", `${provider} needs an API key: pass apiKey or set ${envName}`, { provider });
348
+ return key;
349
+ };
350
+ /**
351
+ * Fetches a presigned URL a provider returned, such as a large result on
352
+ * storage, and returns its body as text. Nothing of the provider's client is
353
+ * sent with it: the URL carries its own authorization, and the key must not
354
+ * reach another host.
355
+ */
356
+ const readSigned = async (provider, url, options) => {
357
+ const doFetch = options.fetch ?? globalThis.fetch;
358
+ let response;
359
+ try {
360
+ response = await doFetch(url, { signal: options.signal });
361
+ } catch (error) {
362
+ throw transportError(provider, error, options.signal);
363
+ }
364
+ const text = await readText(provider, response, options.signal);
365
+ if (!response.ok) throw new FieldworkError(codeForStatus(response.status), `${provider} result at ${new URL(url).origin} returned ${response.status}: ${text.slice(0, 300)}`, {
366
+ provider,
367
+ status: response.status
368
+ });
369
+ return text;
370
+ };
371
+ // src/parse.ts
372
+ /**
373
+ * Building blocks for the schemas that parse a provider's response at the
374
+ * boundary. Every block is lenient: it never fails, so a provider that adds,
375
+ * removes or retypes a field cannot make a working call throw. A field of the
376
+ * wrong type reads as absent, and unknown keys pass through. Build each
377
+ * adapter's response schema only from these, then `z.parse` the response once.
378
+ * The provider's untouched response still goes in `raw`; the parsed value is
379
+ * for reading only.
380
+ */
381
+ /** The result of a field that is absent or of the wrong type. */
382
+ const nothing = () => void 0;
383
+ /** Reads any value as absent. A union's last member, so a value of the wrong type does not fail. */
384
+ const absent = z.pipe(z.unknown(), z.transform(nothing));
385
+ /** A string that is not empty; any other value fails. Use inside `arrayOf`. */
386
+ const nonEmptyString = z.string().check(z.minLength(1));
387
+ /** The string, or undefined when the value is absent, empty or not a string. */
388
+ const optionalString = z.optional(z.union([nonEmptyString, absent]));
389
+ /** The string, an empty one too, or undefined when the value is absent or not a string. */
390
+ const optionalAnyString = z.optional(z.union([z.string(), absent]));
391
+ /** The number, or undefined when the value is absent, not a number, NaN or infinite. */
392
+ const optionalNumber = z.optional(z.union([z.number(), absent]));
393
+ /** The boolean, or undefined when the value is absent or not a boolean. */
394
+ const optionalBoolean = z.optional(z.union([z.boolean(), absent]));
395
+ /**
396
+ * An object that keeps unknown keys. A value that is not an object (absent,
397
+ * null, an array, a string) reads as an object with every field absent, so
398
+ * nested reads need no `?.`. Declare every field with these blocks, so the
399
+ * object itself never fails.
400
+ */
401
+ const looseObject = (shape) => {
402
+ const object = z.looseObject(shape);
403
+ return z.prefault(z.union([object, z.pipe(z.pipe(z.unknown(), z.transform(() => ({}))), object)]), {});
404
+ };
405
+ /**
406
+ * An array of the items that parse. A value that is not an array, or is
407
+ * absent, reads as an empty one. An item schema built from the blocks above
408
+ * never fails, so every position is kept; a strict one such as
409
+ * `nonEmptyString` drops the bad items.
410
+ */
411
+ const arrayOf = (item) => z.prefault(z.union([z.pipe(z.array(z.unknown()), z.transform((entries) => entries.flatMap((entry) => {
412
+ const parsed = z.safeParse(item, entry);
413
+ return parsed.success ? [parsed.data] : [];
414
+ }))), z.pipe(z.unknown(), z.transform(() => []))]), []);
415
+ /**
416
+ * A dictionary keyed by string, its values read through `item`. A value that
417
+ * is not an object, or is absent, reads as an empty dictionary.
418
+ */
419
+ const recordOf = (item) => z.prefault(z.union([z.record(z.string(), item), z.pipe(z.unknown(), z.transform(() => ({})))]), {});
420
+ /**
421
+ * A string, number or boolean read as a string: `"a"` is `"a"` (an empty
422
+ * string stays empty), `3` is `"3"` and `true` is `"true"`. Any other value,
423
+ * or an absent one, reads as undefined. Numbers must be finite.
424
+ */
425
+ const optionalScalar = z.optional(z.union([
426
+ z.string(),
427
+ z.pipe(z.number(), z.transform(String)),
428
+ z.pipe(z.boolean(), z.transform(String)),
429
+ absent
430
+ ]));
431
+ /** A warning entry: a string as it is, or an object's non-empty `message`, else its non-empty `detail`. */
432
+ const warningEntry = z.union([z.string(), z.pipe(looseObject({
433
+ detail: optionalString,
434
+ message: optionalString
435
+ }), z.transform((entry) => entry.message ?? entry.detail))]);
436
+ /**
437
+ * The warnings a provider reports, as a list of strings. A string (an empty
438
+ * one too) is one warning. An array gives its strings as they are and, for
439
+ * each object, its non-empty `message` or else its non-empty `detail`; any
440
+ * other entry is dropped. Anything else, or an absent value, is no warnings.
441
+ */
442
+ const warnings = z.pipe(z.union([z.pipe(z.string(), z.transform((message) => [message])), arrayOf(warningEntry)]), z.transform((entries) => entries.filter((entry) => entry !== void 0)));
443
+ /** Any value, as it arrived. Absent reads as undefined. */
444
+ const anything = z.optional(z.unknown());
445
+ /**
446
+ * The item read through `item`, and the value as it arrived beside it, for a
447
+ * result that must keep its own `raw`. An absent value gives an `original` of
448
+ * undefined. `item` must never fail, so build it from the blocks above.
449
+ */
450
+ const withOriginal = (item) => z.prefault(z.pipe(z.unknown(), z.transform((original) => ({
451
+ original,
452
+ value: z.parse(item, original)
453
+ }))), nothing);
454
+ /**
455
+ * An id that is a finite number or a non-empty string, as a string: `7`
456
+ * is `"7"`. Any other value, or an absent one, reads as undefined.
457
+ */
458
+ const optionalId = z.optional(z.union([
459
+ z.pipe(z.number(), z.transform(String)),
460
+ nonEmptyString,
461
+ absent
462
+ ]));
463
+ /**
464
+ * One value read two ways at once, for a key a provider's result needs
465
+ * twice: `first` is the value through `first`, `second` through `second`.
466
+ */
467
+ const both = (first, second) => z.prefault(z.pipe(z.unknown(), z.transform((value) => ({
468
+ first: z.parse(first, value),
469
+ second: z.parse(second, value)
470
+ }))), nothing);
471
+ /** What a provider says about a cited source: its URL, title and excerpts. */
472
+ const sourceShape = {
473
+ excerpts: z.pipe(z.union([z.pipe(z.string(), z.transform((passage) => [passage])), arrayOf(z.string())]), z.transform((passages) => passages.length > 0 ? passages : void 0)),
474
+ title: optionalString,
475
+ url: optionalString
476
+ };
477
+ /** A cited source. */
478
+ const Source = looseObject(sourceShape);
479
+ /** A non-empty string, else a finite number, else undefined. */
480
+ const optionalStringOrNumber = z.optional(z.union([
481
+ nonEmptyString,
482
+ z.number(),
483
+ absent
484
+ ]));
485
+ /** An object or an array as it arrived, or undefined for any other value, or an absent one. */
486
+ const optionalStructure = z.optional(z.union([
487
+ z.array(z.unknown()),
488
+ z.record(z.string(), z.unknown()),
489
+ absent
490
+ ]));
491
+ /**
492
+ * A non-empty string; or, for an array, its first non-empty string. Any other
493
+ * value, or an absent one, reads as undefined.
494
+ */
495
+ const optionalFirstString = z.optional(z.union([nonEmptyString, z.pipe(arrayOf(nonEmptyString), z.transform((items) => items[0]))]));
496
+ /**
497
+ * An object that keeps unknown keys, or undefined when the value is absent or
498
+ * is not an object (null, an array, a string). Declare every field with the
499
+ * blocks above, so an object never fails.
500
+ */
501
+ const optionalObject = (shape) => z.optional(z.union([z.looseObject(shape), absent]));
502
+ /**
503
+ * Like `arrayOf`, but a value that is not an array, or is absent, reads as
504
+ * undefined instead of an empty array.
505
+ */
506
+ const optionalArrayOf = (item) => z.optional(z.union([z.pipe(z.array(z.unknown()), z.transform((entries) => entries.flatMap((entry) => {
507
+ const parsed = z.safeParse(item, entry);
508
+ return parsed.success ? [parsed.data] : [];
509
+ }))), absent]));
510
+ export { citationsOf as A, uniqueCitations as B, createRawClient as C, segment as D, requireKey as E, presentPage as F, presentPages as I, record as L, hours as M, meta as N, callSettings as O, parseJson as P, refuseTogether as R, withOriginal as S, readSigned as T, optionalStructure as _, looseObject as a, warningEntry as b, optionalArrayOf as c, optionalId as d, optionalNumber as f, optionalStringOrNumber as g, optionalString as h, both as i, compact as j, citationOf as k, optionalBoolean as l, optionalScalar as m, anything as n, nonEmptyString as o, optionalObject as p, arrayOf as r, optionalAnyString as s, Source as t, optionalFirstString as u, recordOf as v, poll as w, warnings as x, sourceShape as y, requireJobId as z };
@@ -1,9 +1,12 @@
1
- import { A as JsonSchema, G as Research, W as Recency, a as RawClient, f as CallOptions, l as Answer, q as SearchResponse, t as Adapter, v as DecisionQuestion, y as Decisions } from "./adapter-DGehHCMo.js";
2
- export interface PerplexityConfig {
1
+ import { K as Recency, Y as SearchResponse, a as RawClient, b as Decisions, l as Answer, p as CallOptions, q as Research, t as Adapter, y as DecisionQuestion } from "./adapter-BgdfLBs-.js";
2
+ import { t as OutputSchema } from "./schema-Cupy7-7q.js";
3
+ interface PerplexityConfig {
3
4
  /** Defaults to the PERPLEXITY_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
  /** The filters Perplexity applies to web search, on `/search` and inside the Agent API's `web_search` tool. */
9
12
  interface PerplexityFilters {
@@ -21,7 +24,7 @@ interface PerplexityFilters {
21
24
  lastUpdatedBefore?: string;
22
25
  recency?: Recency;
23
26
  }
24
- export interface PerplexitySearchOptions extends CallOptions, PerplexityFilters {
27
+ interface PerplexitySearchOptions extends CallOptions, PerplexityFilters {
25
28
  /** Results to return: up to 20, or up to 50 with `searchType: "people"`. */
26
29
  limit?: number;
27
30
  /**
@@ -42,11 +45,12 @@ export interface PerplexitySearchOptions extends CallOptions, PerplexityFilters
42
45
  }
43
46
  /** An effort level, or a name pinned to a version such as `fast@2026-10-16.0`. */
44
47
  type Pinned<Name extends string> = Name | `${Name}@${string}`;
45
- export interface PerplexityAnswerOptions extends CallOptions {
48
+ interface PerplexityAnswerOptions<T = unknown> extends CallOptions {
46
49
  /** Defaults to "fast". Answers are synchronous, so only the quicker levels are offered. */
47
50
  effort?: Pinned<"fast" | "low" | "medium">;
48
51
  instructions?: string;
49
- schema?: JsonSchema;
52
+ /** A JSON Schema, or a Zod, Valibot or ArkType schema that types and checks `output`. */
53
+ schema?: OutputSchema<T>;
50
54
  /** The `continuationId` of an earlier answer or research result. */
51
55
  continueFrom?: string;
52
56
  }
@@ -54,9 +58,9 @@ export interface PerplexityAnswerOptions extends CallOptions {
54
58
  * Perplexity's effort levels. The names change slowly, so the type is open:
55
59
  * `ultra-preview` and version pins (`high@2026-10-28.0`) are accepted too.
56
60
  */
57
- export type PerplexityEffort = "fast" | "low" | "medium" | "high" | "xhigh" | "ultra-preview" | (string & {});
58
- export interface PerplexityResearchOptions extends CallOptions, PerplexityFilters {
59
- schema?: JsonSchema;
61
+ type PerplexityEffort = "fast" | "low" | "medium" | "high" | "xhigh" | "ultra-preview" | (string & {});
62
+ interface PerplexityResearchOptions<T = unknown> extends CallOptions, PerplexityFilters {
63
+ schema?: OutputSchema<T>;
60
64
  /**
61
65
  * The configuration to run: a model, tools, system prompt and step budget in
62
66
  * one name. Defaults to "high" when neither `effort`, `model` nor `models` is
@@ -86,16 +90,21 @@ export interface PerplexityResearchOptions extends CallOptions, PerplexityFilter
86
90
  /** Milliseconds between checks. Defaults to 2000. */
87
91
  interval?: number;
88
92
  }
89
- export type PerplexityDeciderModel = "pplx-decider-v1.2" | "pplx-decider-flash-v1.2" | "pplx-decider-latest" | "pplx-decider-flash-latest" | (string & {});
90
- export interface PerplexityDecideOptions extends CallOptions {
93
+ type PerplexityDeciderModel = "pplx-decider-v1.2" | "pplx-decider-flash-v1.2" | "pplx-decider-latest" | "pplx-decider-flash-latest" | (string & {});
94
+ interface PerplexityDecideOptions extends CallOptions {
91
95
  /** Defaults to "pplx-decider-latest". The flash models are smaller and cheaper. */
92
96
  model?: PerplexityDeciderModel;
93
97
  }
94
- export interface PerplexityOperations {
95
- search(query: string, options?: PerplexitySearchOptions): Promise<SearchResponse>;
96
- answer<T = unknown>(question: string, options?: PerplexityAnswerOptions): Promise<Answer<T>>;
97
- research<T = unknown>(question: string, options?: PerplexityResearchOptions): Promise<Research<T>>;
98
- decide(context: unknown, questions: Record<string, DecisionQuestion>, options?: PerplexityDecideOptions): Promise<Decisions>;
98
+ interface PerplexityOperations {
99
+ search: (query: string, options?: PerplexitySearchOptions) => Promise<SearchResponse>;
100
+ answer: <T = unknown>(question: string, options?: PerplexityAnswerOptions<T>) => Promise<Answer<T>>;
101
+ research: <T = unknown>(question: string, options?: PerplexityResearchOptions<T>) => Promise<Research<T>>;
102
+ decide: (context: unknown, questions: Record<string, DecisionQuestion>, options?: PerplexityDecideOptions) => Promise<Decisions>;
99
103
  }
104
+ /**
105
+ * An adapter for Perplexity: search, answer, research and decide. Pass it to `new Fieldwork({ adapter })`.
106
+ *
107
+ * Throws `Unauthorized` when neither `apiKey` nor `PERPLEXITY_API_KEY` is set.
108
+ */
100
109
  export declare const perplexity: (config?: PerplexityConfig) => Adapter<"perplexity", PerplexityOperations, RawClient>;
101
- export {};
110
+ export type { PerplexityAnswerOptions, PerplexityConfig, PerplexityDecideOptions, PerplexityDeciderModel, PerplexityEffort, PerplexityOperations, PerplexityResearchOptions, PerplexitySearchOptions };