@howells/fieldwork-sdk 0.3.1 → 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/README.md +32 -2
- package/dist/{adapter-DGehHCMo.d.ts → adapter-CDY8qczv.d.ts} +16 -2
- package/dist/brave.d.ts +6 -4
- package/dist/brave.js +199 -116
- package/dist/browserbase.d.ts +8 -6
- package/dist/browserbase.js +85 -39
- package/dist/exa.d.ts +23 -19
- package/dist/exa.js +300 -160
- package/dist/{fieldwork-B3x3cxDJ.d.ts → fieldwork-DTNVIOzp.d.ts} +3 -3
- package/dist/firecrawl.d.ts +28 -25
- package/dist/firecrawl.js +589 -305
- package/dist/index.d.ts +4 -3
- package/dist/index.js +25 -11
- package/dist/parallel.d.ts +31 -26
- package/dist/parallel.js +407 -203
- package/dist/parse-CxOri73y.js +441 -0
- package/dist/perplexity.d.ts +13 -9
- package/dist/perplexity.js +145 -77
- package/dist/schema-EZlBkY5B.d.ts +90 -0
- package/dist/schema-teOy7Od-.js +45 -0
- package/dist/serpapi.d.ts +7 -4
- package/dist/serpapi.js +264 -162
- package/dist/tavily.d.ts +15 -12
- package/dist/tavily.js +191 -117
- package/dist/tools.d.ts +2 -2
- package/dist/util-DhYr1OS3.d.ts +1 -0
- package/package.json +4 -1
- package/dist/util-YaZYZDSk.js +0 -287
|
@@ -0,0 +1,441 @@
|
|
|
1
|
+
import { n as codeForStatus, r as withJob, t as FieldworkError } from "./errors-BiIBG9zN.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
|
+
const callSettings = (options) => {
|
|
8
|
+
const { retries, signal, timeout, ...rest } = options ?? {};
|
|
9
|
+
return {
|
|
10
|
+
call: {
|
|
11
|
+
retries,
|
|
12
|
+
signal,
|
|
13
|
+
timeout
|
|
14
|
+
},
|
|
15
|
+
rest
|
|
16
|
+
};
|
|
17
|
+
};
|
|
18
|
+
const parseJson = (provider, value) => {
|
|
19
|
+
if (typeof value !== "string") return value;
|
|
20
|
+
try {
|
|
21
|
+
return JSON.parse(value);
|
|
22
|
+
} catch (error) {
|
|
23
|
+
throw new FieldworkError("ProviderError", `${provider} returned output that is not valid JSON`, {
|
|
24
|
+
cause: error,
|
|
25
|
+
provider
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
const uniqueCitations = (all) => {
|
|
30
|
+
const seen = /* @__PURE__ */ new Map();
|
|
31
|
+
for (const item of all) if (!seen.has(item.url)) seen.set(item.url, item);
|
|
32
|
+
return [...seen.values()];
|
|
33
|
+
};
|
|
34
|
+
/** The citation a parsed source amounts to, or undefined when it has no URL. */
|
|
35
|
+
const citationOf = (source) => source.url === void 0 ? void 0 : compact({
|
|
36
|
+
excerpts: source.excerpts,
|
|
37
|
+
title: source.title,
|
|
38
|
+
url: source.url
|
|
39
|
+
});
|
|
40
|
+
/** The citations the parsed sources amount to; a source without a URL is left out. */
|
|
41
|
+
const citationsOf = (sources) => sources.map((source) => citationOf(source)).filter((item) => item !== void 0);
|
|
42
|
+
/** The job id a start call returned, or a ProviderError carrying the value as it arrived. */
|
|
43
|
+
const requireJobId = (provider, id) => {
|
|
44
|
+
if (id.value === void 0) throw new FieldworkError("ProviderError", `${provider} did not return a job id`, {
|
|
45
|
+
cause: id.original,
|
|
46
|
+
provider
|
|
47
|
+
});
|
|
48
|
+
return id.value;
|
|
49
|
+
};
|
|
50
|
+
const meta = (parts) => {
|
|
51
|
+
const units = Object.fromEntries(Object.entries(parts.units ?? {}).filter((entry) => entry[1] !== void 0));
|
|
52
|
+
const usage = compact({
|
|
53
|
+
costUsd: parts.costUsd,
|
|
54
|
+
credits: parts.credits,
|
|
55
|
+
units: Object.keys(units).length > 0 ? units : void 0
|
|
56
|
+
});
|
|
57
|
+
const warnings = [parts.warnings ?? []].flat();
|
|
58
|
+
const result = compact({
|
|
59
|
+
requestId: parts.requestId,
|
|
60
|
+
usage: Object.keys(usage).length > 0 ? usage : void 0,
|
|
61
|
+
warnings: warnings.length > 0 ? warnings : void 0
|
|
62
|
+
});
|
|
63
|
+
return Object.keys(result).length > 0 ? result : void 0;
|
|
64
|
+
};
|
|
65
|
+
const refuseTogether = (provider, options, ...names) => {
|
|
66
|
+
const set = names.filter((name) => options[name] !== void 0);
|
|
67
|
+
if (set.length > 1) throw new FieldworkError("InvalidRequest", `${provider} does not accept ${set.join(" and ")} together; pass one`, { provider });
|
|
68
|
+
};
|
|
69
|
+
const hours = (seconds) => seconds === void 0 ? void 0 : seconds < 0 ? -1 : Math.ceil(seconds / 3600);
|
|
70
|
+
/** Statuses that mean the page is not there, so a read of it has no page to return. */
|
|
71
|
+
const GONE = /* @__PURE__ */ new Set([404, 410]);
|
|
72
|
+
/**
|
|
73
|
+
* A read whose page answered 404 or 410 fails as NotFound, as it does on
|
|
74
|
+
* providers that return no page at all, instead of returning the error page
|
|
75
|
+
* as if it were the content.
|
|
76
|
+
*/
|
|
77
|
+
const presentPage = (provider, page) => {
|
|
78
|
+
if (page.statusCode !== void 0 && GONE.has(page.statusCode)) throw new FieldworkError("NotFound", `${provider} could not read ${page.url}: the page returned ${page.statusCode}`, {
|
|
79
|
+
provider,
|
|
80
|
+
status: page.statusCode
|
|
81
|
+
});
|
|
82
|
+
return page;
|
|
83
|
+
};
|
|
84
|
+
/** Splits a batch's pages into those present and those that answered 404 or 410. */
|
|
85
|
+
const presentPages = (pages) => ({
|
|
86
|
+
gone: pages.filter((page) => page.statusCode !== void 0 && GONE.has(page.statusCode)).map((page) => ({
|
|
87
|
+
error: `the page returned ${page.statusCode}`,
|
|
88
|
+
url: page.url
|
|
89
|
+
})),
|
|
90
|
+
pages: pages.filter((page) => page.statusCode === void 0 || !GONE.has(page.statusCode))
|
|
91
|
+
});
|
|
92
|
+
const sleep = async (ms, signal) => {
|
|
93
|
+
await new Promise((resolve) => {
|
|
94
|
+
const timer = setTimeout(resolve, ms);
|
|
95
|
+
signal?.addEventListener("abort", () => {
|
|
96
|
+
clearTimeout(timer);
|
|
97
|
+
resolve();
|
|
98
|
+
}, { once: true });
|
|
99
|
+
});
|
|
100
|
+
};
|
|
101
|
+
/** The longest wait between attempts; a provider asking for longer gets the error instead. */
|
|
102
|
+
const MAX_RETRY_WAIT = 3e4;
|
|
103
|
+
const FIRST_RETRY_WAIT = 500;
|
|
104
|
+
/**
|
|
105
|
+
* Milliseconds to wait before repeating a failed request, or undefined when it
|
|
106
|
+
* should not be repeated: the attempts are used up, the call was cancelled or
|
|
107
|
+
* timed out, the failure would recur, or the request created something.
|
|
108
|
+
*/
|
|
109
|
+
const retryDelay = (error, state) => {
|
|
110
|
+
if (state.count >= state.retries || state.signal?.aborted === true || !error.retryable || error.code === "Timeout" || state.creates && error.code !== "RateLimited") return;
|
|
111
|
+
if (error.retryAfter !== void 0) {
|
|
112
|
+
const asked = error.retryAfter * 1e3;
|
|
113
|
+
return asked > MAX_RETRY_WAIT ? void 0 : asked;
|
|
114
|
+
}
|
|
115
|
+
const ceiling = Math.min(MAX_RETRY_WAIT, FIRST_RETRY_WAIT * 2 ** state.count);
|
|
116
|
+
return ceiling / 2 + Math.random() * (ceiling / 2);
|
|
117
|
+
};
|
|
118
|
+
const createRawClient = (config) => {
|
|
119
|
+
const doFetch = config.fetch ?? globalThis.fetch;
|
|
120
|
+
return {
|
|
121
|
+
baseUrl: config.baseUrl,
|
|
122
|
+
provider: config.provider,
|
|
123
|
+
async request(method, path, options = {}) {
|
|
124
|
+
const url = new URL(config.baseUrl.replace(/\/$/u, "") + path);
|
|
125
|
+
for (const [key, value] of Object.entries(options.query ?? {})) if (value !== void 0) url.searchParams.set(key, String(value));
|
|
126
|
+
const headers = new Headers({
|
|
127
|
+
accept: "application/json",
|
|
128
|
+
...config.headers
|
|
129
|
+
});
|
|
130
|
+
let body;
|
|
131
|
+
if (options.form) body = options.form;
|
|
132
|
+
else if (options.body !== void 0) {
|
|
133
|
+
headers.set("content-type", "application/json");
|
|
134
|
+
body = JSON.stringify(options.body);
|
|
135
|
+
}
|
|
136
|
+
const signal = combineSignals(options.signal, options.timeout);
|
|
137
|
+
const send = async (request) => {
|
|
138
|
+
try {
|
|
139
|
+
return await doFetch(request.url, {
|
|
140
|
+
body: request.body,
|
|
141
|
+
headers,
|
|
142
|
+
method: request.method,
|
|
143
|
+
redirect: "manual",
|
|
144
|
+
signal
|
|
145
|
+
});
|
|
146
|
+
} catch (error) {
|
|
147
|
+
throw transportError(config.provider, error, options.signal);
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
const once = async () => {
|
|
151
|
+
const response = await followRedirects(config.provider, send, {
|
|
152
|
+
body,
|
|
153
|
+
method,
|
|
154
|
+
url
|
|
155
|
+
});
|
|
156
|
+
const text = await response.text();
|
|
157
|
+
const parsed = parseBody(text);
|
|
158
|
+
if (response.ok) return parsed;
|
|
159
|
+
throw new FieldworkError(codeForStatus(response.status), `${config.provider} ${method} ${path} returned ${response.status}: ${describe(parsed, text)}`, {
|
|
160
|
+
cause: parsed,
|
|
161
|
+
provider: config.provider,
|
|
162
|
+
retryAfter: retryAfterSeconds(response.headers.get("retry-after")),
|
|
163
|
+
status: response.status
|
|
164
|
+
});
|
|
165
|
+
};
|
|
166
|
+
const retries = options.retries ?? config.retries ?? 2;
|
|
167
|
+
const deadline = options.timeout === void 0 ? void 0 : Date.now() + options.timeout;
|
|
168
|
+
const attempt = async (count) => {
|
|
169
|
+
try {
|
|
170
|
+
return await once();
|
|
171
|
+
} catch (error) {
|
|
172
|
+
if (!(error instanceof FieldworkError)) throw error;
|
|
173
|
+
const wait = retryDelay(error, {
|
|
174
|
+
count,
|
|
175
|
+
creates: options.creates === true,
|
|
176
|
+
retries,
|
|
177
|
+
signal
|
|
178
|
+
});
|
|
179
|
+
if (wait === void 0 || deadline !== void 0 && Date.now() + wait >= deadline) throw error;
|
|
180
|
+
await sleep(wait, signal);
|
|
181
|
+
if (options.signal?.aborted === true) throw new FieldworkError("Aborted", `${config.provider} request was cancelled while waiting to retry`, {
|
|
182
|
+
cause: error,
|
|
183
|
+
provider: config.provider
|
|
184
|
+
});
|
|
185
|
+
return await attempt(count + 1);
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
return await attempt(0);
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
};
|
|
192
|
+
const REDIRECTS = /* @__PURE__ */ new Set([
|
|
193
|
+
301,
|
|
194
|
+
302,
|
|
195
|
+
303,
|
|
196
|
+
307,
|
|
197
|
+
308
|
|
198
|
+
]);
|
|
199
|
+
const MAX_REDIRECTS = 5;
|
|
200
|
+
/**
|
|
201
|
+
* Follows a provider's redirects only within its own origin, so the key in
|
|
202
|
+
* the request's headers or query never reaches another host. A redirect to
|
|
203
|
+
* another origin, scheme or port fails before anything is sent there.
|
|
204
|
+
*/
|
|
205
|
+
const followRedirects = async (provider, send, first) => {
|
|
206
|
+
let hop = first;
|
|
207
|
+
for (let count = 0; count <= MAX_REDIRECTS; count += 1) {
|
|
208
|
+
const response = await send(hop);
|
|
209
|
+
if (response.type === "opaqueredirect") throw new FieldworkError("ProviderError", `${provider} redirected the request, and this runtime hides where to; Fieldwork does not follow it`, { provider });
|
|
210
|
+
const location = response.headers.get("location");
|
|
211
|
+
if (!REDIRECTS.has(response.status) || location === null) return response;
|
|
212
|
+
const target = new URL(location, hop.url);
|
|
213
|
+
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`, {
|
|
214
|
+
provider,
|
|
215
|
+
status: response.status
|
|
216
|
+
});
|
|
217
|
+
hop = response.status === 303 || (response.status === 301 || response.status === 302) && hop.method === "POST" ? {
|
|
218
|
+
body: void 0,
|
|
219
|
+
method: "GET",
|
|
220
|
+
url: target
|
|
221
|
+
} : {
|
|
222
|
+
...hop,
|
|
223
|
+
url: target
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
throw new FieldworkError("ProviderError", `${provider} redirected the request more than ${MAX_REDIRECTS} times`, { provider });
|
|
227
|
+
};
|
|
228
|
+
const combineSignals = (signal, timeout) => {
|
|
229
|
+
const signals = [signal, timeout === void 0 ? void 0 : AbortSignal.timeout(timeout)].filter((value) => value !== void 0);
|
|
230
|
+
return signals.length <= 1 ? signals[0] : AbortSignal.any(signals);
|
|
231
|
+
};
|
|
232
|
+
const transportError = (provider, error, signal) => {
|
|
233
|
+
if (signal?.aborted === true) return new FieldworkError("Aborted", `${provider} request was cancelled`, {
|
|
234
|
+
cause: error,
|
|
235
|
+
provider
|
|
236
|
+
});
|
|
237
|
+
if (error instanceof DOMException && error.name === "TimeoutError") return new FieldworkError("Timeout", `${provider} request timed out`, {
|
|
238
|
+
cause: error,
|
|
239
|
+
provider
|
|
240
|
+
});
|
|
241
|
+
return new FieldworkError("ProviderError", `${provider} request failed: ${String(error)}`, {
|
|
242
|
+
cause: error,
|
|
243
|
+
provider,
|
|
244
|
+
retryable: true
|
|
245
|
+
});
|
|
246
|
+
};
|
|
247
|
+
const parseBody = (text) => {
|
|
248
|
+
if (text === "") return;
|
|
249
|
+
try {
|
|
250
|
+
return JSON.parse(text);
|
|
251
|
+
} catch {
|
|
252
|
+
return text;
|
|
253
|
+
}
|
|
254
|
+
};
|
|
255
|
+
const describe = (parsed, text) => {
|
|
256
|
+
const body = record(parsed);
|
|
257
|
+
for (const key of [
|
|
258
|
+
"error",
|
|
259
|
+
"message",
|
|
260
|
+
"detail"
|
|
261
|
+
]) {
|
|
262
|
+
const value = body[key];
|
|
263
|
+
if (typeof value === "string") return value;
|
|
264
|
+
if (typeof value === "object" && value !== null) return JSON.stringify(value).slice(0, 300);
|
|
265
|
+
}
|
|
266
|
+
return text.slice(0, 300);
|
|
267
|
+
};
|
|
268
|
+
const retryAfterSeconds = (header, now = Date.now()) => {
|
|
269
|
+
if (header === null || header === "") return;
|
|
270
|
+
const seconds = Number(header);
|
|
271
|
+
if (Number.isFinite(seconds)) return seconds;
|
|
272
|
+
const date = Date.parse(header);
|
|
273
|
+
return Number.isNaN(date) ? void 0 : Math.max(0, Math.ceil((date - now) / 1e3));
|
|
274
|
+
};
|
|
275
|
+
const poll = async (provider, jobId, check, options = {}) => {
|
|
276
|
+
const interval = options.interval ?? 2e3;
|
|
277
|
+
const deadline = Date.now() + (options.timeout ?? 6e5);
|
|
278
|
+
for (;;) {
|
|
279
|
+
if (options.signal?.aborted === true) throw new FieldworkError("Aborted", `stopped waiting for ${provider} job ${jobId}; it may still be running`, {
|
|
280
|
+
jobId,
|
|
281
|
+
provider
|
|
282
|
+
});
|
|
283
|
+
let value;
|
|
284
|
+
try {
|
|
285
|
+
value = await check();
|
|
286
|
+
} catch (error) {
|
|
287
|
+
throw withJob(error, jobId);
|
|
288
|
+
}
|
|
289
|
+
if (value !== void 0) return value;
|
|
290
|
+
if (Date.now() + interval > deadline) throw new FieldworkError("Timeout", `${provider} job ${jobId} did not finish in time; it may still be running`, {
|
|
291
|
+
jobId,
|
|
292
|
+
provider
|
|
293
|
+
});
|
|
294
|
+
await sleep(interval, options.signal);
|
|
295
|
+
}
|
|
296
|
+
};
|
|
297
|
+
const requireKey = (provider, given, envName) => {
|
|
298
|
+
const key = given ?? process.env[envName];
|
|
299
|
+
if (key === void 0 || key === "") throw new FieldworkError("Unauthorized", `${provider} needs an API key: pass apiKey or set ${envName}`, { provider });
|
|
300
|
+
return key;
|
|
301
|
+
};
|
|
302
|
+
// src/parse.ts
|
|
303
|
+
/**
|
|
304
|
+
* Building blocks for the schemas that parse a provider's response at the
|
|
305
|
+
* boundary. Every block is lenient: it never fails, so a provider that adds,
|
|
306
|
+
* removes or retypes a field cannot make a working call throw. A field of the
|
|
307
|
+
* wrong type reads as absent, and unknown keys pass through. Build each
|
|
308
|
+
* adapter's response schema only from these, then `z.parse` the response once.
|
|
309
|
+
* The provider's untouched response still goes in `raw`; the parsed value is
|
|
310
|
+
* for reading only.
|
|
311
|
+
*/
|
|
312
|
+
/** The result of a field that is absent or of the wrong type. */
|
|
313
|
+
const nothing = () => void 0;
|
|
314
|
+
/** Reads any value as absent. A union's last member, so a value of the wrong type does not fail. */
|
|
315
|
+
const absent = z.pipe(z.unknown(), z.transform(nothing));
|
|
316
|
+
/** A string that is not empty; any other value fails. Use inside `arrayOf`. */
|
|
317
|
+
const nonEmptyString = z.string().check(z.minLength(1));
|
|
318
|
+
/** The string, or undefined when the value is absent, empty or not a string. */
|
|
319
|
+
const optionalString = z.optional(z.union([nonEmptyString, absent]));
|
|
320
|
+
/** The string, an empty one too, or undefined when the value is absent or not a string. */
|
|
321
|
+
const optionalAnyString = z.optional(z.union([z.string(), absent]));
|
|
322
|
+
/** The number, or undefined when the value is absent, not a number, NaN or infinite. */
|
|
323
|
+
const optionalNumber = z.optional(z.union([z.number(), absent]));
|
|
324
|
+
/** The boolean, or undefined when the value is absent or not a boolean. */
|
|
325
|
+
const optionalBoolean = z.optional(z.union([z.boolean(), absent]));
|
|
326
|
+
/**
|
|
327
|
+
* An object that keeps unknown keys. A value that is not an object (absent,
|
|
328
|
+
* null, an array, a string) reads as an object with every field absent, so
|
|
329
|
+
* nested reads need no `?.`. Declare every field with these blocks, so the
|
|
330
|
+
* object itself never fails.
|
|
331
|
+
*/
|
|
332
|
+
const looseObject = (shape) => {
|
|
333
|
+
const object = z.looseObject(shape);
|
|
334
|
+
return z.prefault(z.union([object, z.pipe(z.pipe(z.unknown(), z.transform(() => ({}))), object)]), {});
|
|
335
|
+
};
|
|
336
|
+
/**
|
|
337
|
+
* An array of the items that parse. A value that is not an array, or is
|
|
338
|
+
* absent, reads as an empty one. An item schema built from the blocks above
|
|
339
|
+
* never fails, so every position is kept; a strict one such as
|
|
340
|
+
* `nonEmptyString` drops the bad items.
|
|
341
|
+
*/
|
|
342
|
+
const arrayOf = (item) => z.prefault(z.union([z.pipe(z.array(z.unknown()), z.transform((entries) => entries.flatMap((entry) => {
|
|
343
|
+
const parsed = z.safeParse(item, entry);
|
|
344
|
+
return parsed.success ? [parsed.data] : [];
|
|
345
|
+
}))), z.pipe(z.unknown(), z.transform(() => []))]), []);
|
|
346
|
+
/**
|
|
347
|
+
* A dictionary keyed by string, its values read through `item`. A value that
|
|
348
|
+
* is not an object, or is absent, reads as an empty dictionary.
|
|
349
|
+
*/
|
|
350
|
+
const recordOf = (item) => z.prefault(z.union([z.record(z.string(), item), z.pipe(z.unknown(), z.transform(() => ({})))]), {});
|
|
351
|
+
/**
|
|
352
|
+
* A string, number or boolean read as a string: `"a"` is `"a"` (an empty
|
|
353
|
+
* string stays empty), `3` is `"3"` and `true` is `"true"`. Any other value,
|
|
354
|
+
* or an absent one, reads as undefined. Numbers must be finite.
|
|
355
|
+
*/
|
|
356
|
+
const optionalScalar = z.optional(z.union([
|
|
357
|
+
z.string(),
|
|
358
|
+
z.pipe(z.number(), z.transform(String)),
|
|
359
|
+
z.pipe(z.boolean(), z.transform(String)),
|
|
360
|
+
absent
|
|
361
|
+
]));
|
|
362
|
+
/** A warning entry: a string as it is, or an object's non-empty `message`, else its non-empty `detail`. */
|
|
363
|
+
const warningEntry = z.union([z.string(), z.pipe(looseObject({
|
|
364
|
+
detail: optionalString,
|
|
365
|
+
message: optionalString
|
|
366
|
+
}), z.transform((entry) => entry.message ?? entry.detail))]);
|
|
367
|
+
/**
|
|
368
|
+
* The warnings a provider reports, as a list of strings. A string (an empty
|
|
369
|
+
* one too) is one warning. An array gives its strings as they are and, for
|
|
370
|
+
* each object, its non-empty `message` or else its non-empty `detail`; any
|
|
371
|
+
* other entry is dropped. Anything else, or an absent value, is no warnings.
|
|
372
|
+
*/
|
|
373
|
+
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)));
|
|
374
|
+
/** Any value, as it arrived. Absent reads as undefined. */
|
|
375
|
+
const anything = z.optional(z.unknown());
|
|
376
|
+
/**
|
|
377
|
+
* The item read through `item`, and the value as it arrived beside it, for a
|
|
378
|
+
* result that must keep its own `raw`. An absent value gives an `original` of
|
|
379
|
+
* undefined. `item` must never fail, so build it from the blocks above.
|
|
380
|
+
*/
|
|
381
|
+
const withOriginal = (item) => z.prefault(z.pipe(z.unknown(), z.transform((original) => ({
|
|
382
|
+
original,
|
|
383
|
+
value: z.parse(item, original)
|
|
384
|
+
}))), nothing);
|
|
385
|
+
/**
|
|
386
|
+
* An id that is a finite number or a non-empty string, as a string: `7`
|
|
387
|
+
* is `"7"`. Any other value, or an absent one, reads as undefined.
|
|
388
|
+
*/
|
|
389
|
+
const optionalId = z.optional(z.union([
|
|
390
|
+
z.pipe(z.number(), z.transform(String)),
|
|
391
|
+
nonEmptyString,
|
|
392
|
+
absent
|
|
393
|
+
]));
|
|
394
|
+
/**
|
|
395
|
+
* One value read two ways at once, for a key a provider's result needs
|
|
396
|
+
* twice: `first` is the value through `first`, `second` through `second`.
|
|
397
|
+
*/
|
|
398
|
+
const both = (first, second) => z.prefault(z.pipe(z.unknown(), z.transform((value) => ({
|
|
399
|
+
first: z.parse(first, value),
|
|
400
|
+
second: z.parse(second, value)
|
|
401
|
+
}))), nothing);
|
|
402
|
+
/** What a provider says about a cited source: its URL, title and excerpts. */
|
|
403
|
+
const sourceShape = {
|
|
404
|
+
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)),
|
|
405
|
+
title: optionalString,
|
|
406
|
+
url: optionalString
|
|
407
|
+
};
|
|
408
|
+
/** A cited source. */
|
|
409
|
+
const Source = looseObject(sourceShape);
|
|
410
|
+
/** A non-empty string, else a finite number, else undefined. */
|
|
411
|
+
const optionalStringOrNumber = z.optional(z.union([
|
|
412
|
+
nonEmptyString,
|
|
413
|
+
z.number(),
|
|
414
|
+
absent
|
|
415
|
+
]));
|
|
416
|
+
/** An object or an array as it arrived, or undefined for any other value, or an absent one. */
|
|
417
|
+
const optionalStructure = z.optional(z.union([
|
|
418
|
+
z.array(z.unknown()),
|
|
419
|
+
z.record(z.string(), z.unknown()),
|
|
420
|
+
absent
|
|
421
|
+
]));
|
|
422
|
+
/**
|
|
423
|
+
* A non-empty string; or, for an array, its first non-empty string. Any other
|
|
424
|
+
* value, or an absent one, reads as undefined.
|
|
425
|
+
*/
|
|
426
|
+
const optionalFirstString = z.optional(z.union([nonEmptyString, z.pipe(arrayOf(nonEmptyString), z.transform((items) => items[0]))]));
|
|
427
|
+
/**
|
|
428
|
+
* An object that keeps unknown keys, or undefined when the value is absent or
|
|
429
|
+
* is not an object (null, an array, a string). Declare every field with the
|
|
430
|
+
* blocks above, so an object never fails.
|
|
431
|
+
*/
|
|
432
|
+
const optionalObject = (shape) => z.optional(z.union([z.looseObject(shape), absent]));
|
|
433
|
+
/**
|
|
434
|
+
* Like `arrayOf`, but a value that is not an array, or is absent, reads as
|
|
435
|
+
* undefined instead of an empty array.
|
|
436
|
+
*/
|
|
437
|
+
const optionalArrayOf = (item) => z.optional(z.union([z.pipe(z.array(z.unknown()), z.transform((entries) => entries.flatMap((entry) => {
|
|
438
|
+
const parsed = z.safeParse(item, entry);
|
|
439
|
+
return parsed.success ? [parsed.data] : [];
|
|
440
|
+
}))), absent]));
|
|
441
|
+
export { hours as A, createRawClient as C, citationOf as D, callSettings as E, record as F, refuseTogether as I, requireJobId as L, parseJson as M, presentPage as N, citationsOf as O, presentPages as P, uniqueCitations as R, withOriginal as S, requireKey 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, meta as j, compact 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 };
|
package/dist/perplexity.d.ts
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { 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-CDY8qczv.js";
|
|
2
|
+
import { t as OutputSchema } from "./schema-EZlBkY5B.js";
|
|
2
3
|
export 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 {
|
|
@@ -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
|
+
export 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
|
|
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
|
}
|
|
@@ -55,8 +59,8 @@ export interface PerplexityAnswerOptions extends CallOptions {
|
|
|
55
59
|
* `ultra-preview` and version pins (`high@2026-10-28.0`) are accepted too.
|
|
56
60
|
*/
|
|
57
61
|
export type PerplexityEffort = "fast" | "low" | "medium" | "high" | "xhigh" | "ultra-preview" | (string & {});
|
|
58
|
-
export interface PerplexityResearchOptions extends CallOptions, PerplexityFilters {
|
|
59
|
-
schema?:
|
|
62
|
+
export 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
|
|
@@ -92,10 +96,10 @@ export interface PerplexityDecideOptions extends CallOptions {
|
|
|
92
96
|
model?: PerplexityDeciderModel;
|
|
93
97
|
}
|
|
94
98
|
export interface PerplexityOperations {
|
|
95
|
-
search(query: string, options?: PerplexitySearchOptions)
|
|
96
|
-
answer<T = unknown>(question: string, options?: PerplexityAnswerOptions)
|
|
97
|
-
research<T = unknown>(question: string, options?: PerplexityResearchOptions)
|
|
98
|
-
decide(context: unknown, questions: Record<string, DecisionQuestion>, options?: PerplexityDecideOptions)
|
|
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
|
}
|
|
100
104
|
export declare const perplexity: (config?: PerplexityConfig) => Adapter<"perplexity", PerplexityOperations, RawClient>;
|
|
101
105
|
export {};
|