@victor-software-house/exa-cli 0.0.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/CHANGELOG.md +1 -0
- package/LICENSE +21 -0
- package/README.md +67 -0
- package/dist/cli.d.mts +1 -0
- package/dist/cli.mjs +1546 -0
- package/dist/cli.mjs.map +1 -0
- package/package.json +94 -0
- package/skills/exa/SKILL.md +50 -0
package/dist/cli.mjs
ADDED
|
@@ -0,0 +1,1546 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
import "zod/compile";
|
|
3
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { Database } from "bun:sqlite";
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import * as z from "zod";
|
|
8
|
+
import { createHash } from "node:crypto";
|
|
9
|
+
import { match } from "ts-pattern";
|
|
10
|
+
import { createColors } from "picocolors";
|
|
11
|
+
import { object, or } from "@optique/core/constructs";
|
|
12
|
+
import { message } from "@optique/core/message";
|
|
13
|
+
import { multiple, optional, withDefault } from "@optique/core/modifiers";
|
|
14
|
+
import { argument, command, constant, flag, negatableFlag, option } from "@optique/core/primitives";
|
|
15
|
+
import { choice } from "@optique/core/valueparser";
|
|
16
|
+
import { bindEnv, createEnvContext } from "@optique/env";
|
|
17
|
+
import { path } from "@optique/run/valueparser";
|
|
18
|
+
import { zod } from "@optique/zod";
|
|
19
|
+
import { run } from "@optique/run";
|
|
20
|
+
//#region src/env.ts
|
|
21
|
+
const blankableSchema = z.string().trim().optional().transform((value) => {
|
|
22
|
+
if (value === void 0 || value === "") return;
|
|
23
|
+
return value;
|
|
24
|
+
});
|
|
25
|
+
const processEnvSchema = z.looseObject({
|
|
26
|
+
CI: blankableSchema,
|
|
27
|
+
EXA_API_KEY: blankableSchema,
|
|
28
|
+
EXA_API_URL: blankableSchema,
|
|
29
|
+
FORCE_COLOR: z.string().trim().optional(),
|
|
30
|
+
NO_COLOR: z.string().trim().optional(),
|
|
31
|
+
XDG_CACHE_HOME: blankableSchema
|
|
32
|
+
});
|
|
33
|
+
function parseEnv(source = process.env) {
|
|
34
|
+
return processEnvSchema.parse(source);
|
|
35
|
+
}
|
|
36
|
+
const env = parseEnv();
|
|
37
|
+
function defaultCacheDir() {
|
|
38
|
+
if (env.XDG_CACHE_HOME !== void 0) return join(env.XDG_CACHE_HOME, "exa-cli");
|
|
39
|
+
return join(homedir(), ".cache", "exa-cli");
|
|
40
|
+
}
|
|
41
|
+
function defaultCachePath() {
|
|
42
|
+
return join(defaultCacheDir(), "cache.sqlite");
|
|
43
|
+
}
|
|
44
|
+
var CacheStore = class {
|
|
45
|
+
path;
|
|
46
|
+
#db;
|
|
47
|
+
constructor(path) {
|
|
48
|
+
mkdirSync(join(path, ".."), { recursive: true });
|
|
49
|
+
this.path = path;
|
|
50
|
+
this.#db = new Database(path);
|
|
51
|
+
this.#db.run("PRAGMA journal_mode = WAL");
|
|
52
|
+
this.#db.run(`
|
|
53
|
+
CREATE TABLE IF NOT EXISTS entries (
|
|
54
|
+
key TEXT PRIMARY KEY NOT NULL,
|
|
55
|
+
body TEXT NOT NULL,
|
|
56
|
+
created_at INTEGER NOT NULL
|
|
57
|
+
)
|
|
58
|
+
`);
|
|
59
|
+
}
|
|
60
|
+
get(key, ttlSeconds, now = Date.now()) {
|
|
61
|
+
const row = this.#db.query("SELECT key, body, created_at FROM entries WHERE key = ?").get(key);
|
|
62
|
+
if (row === null) return;
|
|
63
|
+
if (now - row.created_at > ttlSeconds * 1e3) {
|
|
64
|
+
this.#db.query("DELETE FROM entries WHERE key = ?").run(key);
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
return {
|
|
68
|
+
key: row.key,
|
|
69
|
+
body: row.body,
|
|
70
|
+
createdAt: row.created_at
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
set(key, body, now = Date.now()) {
|
|
74
|
+
this.#db.query(`INSERT INTO entries (key, body, created_at)
|
|
75
|
+
VALUES (?, ?, ?)
|
|
76
|
+
ON CONFLICT(key) DO UPDATE SET body = excluded.body, created_at = excluded.created_at`).run(key, body, now);
|
|
77
|
+
}
|
|
78
|
+
count() {
|
|
79
|
+
const row = this.#db.query("SELECT COUNT(*) AS n FROM entries").get();
|
|
80
|
+
if (row === null) return 0;
|
|
81
|
+
return row.n;
|
|
82
|
+
}
|
|
83
|
+
close() {
|
|
84
|
+
this.#db.close();
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
//#endregion
|
|
88
|
+
//#region src/generated/core/bodySerializer.gen.ts
|
|
89
|
+
const jsonBodySerializer = { bodySerializer: (body) => JSON.stringify(body, (_key, value) => typeof value === "bigint" ? value.toString() : value) };
|
|
90
|
+
Object.entries({
|
|
91
|
+
$body_: "body",
|
|
92
|
+
$headers_: "headers",
|
|
93
|
+
$path_: "path",
|
|
94
|
+
$query_: "query"
|
|
95
|
+
});
|
|
96
|
+
//#endregion
|
|
97
|
+
//#region src/generated/core/serverSentEvents.gen.ts
|
|
98
|
+
function createSseClient({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }) {
|
|
99
|
+
let lastEventId;
|
|
100
|
+
const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
101
|
+
const createStream = async function* () {
|
|
102
|
+
let retryDelay = sseDefaultRetryDelay ?? 3e3;
|
|
103
|
+
let attempt = 0;
|
|
104
|
+
const signal = options.signal ?? new AbortController().signal;
|
|
105
|
+
while (true) {
|
|
106
|
+
if (signal.aborted) break;
|
|
107
|
+
attempt++;
|
|
108
|
+
const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
|
|
109
|
+
if (lastEventId !== void 0) headers.set("Last-Event-ID", lastEventId);
|
|
110
|
+
try {
|
|
111
|
+
const requestInit = {
|
|
112
|
+
redirect: "follow",
|
|
113
|
+
...options,
|
|
114
|
+
body: options.serializedBody,
|
|
115
|
+
headers,
|
|
116
|
+
signal
|
|
117
|
+
};
|
|
118
|
+
let request = new Request(url, requestInit);
|
|
119
|
+
if (onRequest) request = await onRequest(url, requestInit);
|
|
120
|
+
const response = await (options.fetch ?? globalThis.fetch)(request);
|
|
121
|
+
if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
|
|
122
|
+
if (!response.body) throw new Error("No body in SSE response");
|
|
123
|
+
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
|
|
124
|
+
let buffer = "";
|
|
125
|
+
const abortHandler = () => {
|
|
126
|
+
try {
|
|
127
|
+
reader.cancel();
|
|
128
|
+
} catch {}
|
|
129
|
+
};
|
|
130
|
+
signal.addEventListener("abort", abortHandler);
|
|
131
|
+
try {
|
|
132
|
+
while (true) {
|
|
133
|
+
const { done, value } = await reader.read();
|
|
134
|
+
if (done) break;
|
|
135
|
+
buffer += value;
|
|
136
|
+
buffer = buffer.replace(/\r\n?/g, "\n");
|
|
137
|
+
const chunks = buffer.split("\n\n");
|
|
138
|
+
buffer = chunks.pop() ?? "";
|
|
139
|
+
for (const chunk of chunks) {
|
|
140
|
+
const lines = chunk.split("\n");
|
|
141
|
+
const dataLines = [];
|
|
142
|
+
let eventName;
|
|
143
|
+
for (const line of lines) if (line.startsWith("data:")) dataLines.push(line.replace(/^data:\s*/, ""));
|
|
144
|
+
else if (line.startsWith("event:")) eventName = line.replace(/^event:\s*/, "");
|
|
145
|
+
else if (line.startsWith("id:")) lastEventId = line.replace(/^id:\s*/, "");
|
|
146
|
+
else if (line.startsWith("retry:")) {
|
|
147
|
+
const parsed = Number.parseInt(line.replace(/^retry:\s*/, ""), 10);
|
|
148
|
+
if (!Number.isNaN(parsed)) retryDelay = parsed;
|
|
149
|
+
}
|
|
150
|
+
let data;
|
|
151
|
+
let parsedJson = false;
|
|
152
|
+
if (dataLines.length) {
|
|
153
|
+
const rawData = dataLines.join("\n");
|
|
154
|
+
try {
|
|
155
|
+
data = JSON.parse(rawData);
|
|
156
|
+
parsedJson = true;
|
|
157
|
+
} catch {
|
|
158
|
+
data = rawData;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
if (parsedJson) {
|
|
162
|
+
if (responseValidator) await responseValidator(data);
|
|
163
|
+
if (responseTransformer) data = await responseTransformer(data);
|
|
164
|
+
}
|
|
165
|
+
onSseEvent?.({
|
|
166
|
+
data,
|
|
167
|
+
event: eventName,
|
|
168
|
+
id: lastEventId,
|
|
169
|
+
retry: retryDelay
|
|
170
|
+
});
|
|
171
|
+
if (dataLines.length) yield data;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
} finally {
|
|
175
|
+
signal.removeEventListener("abort", abortHandler);
|
|
176
|
+
reader.releaseLock();
|
|
177
|
+
}
|
|
178
|
+
break;
|
|
179
|
+
} catch (error) {
|
|
180
|
+
onSseError?.(error);
|
|
181
|
+
if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) break;
|
|
182
|
+
const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 3e4);
|
|
183
|
+
await sleep(backoff);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
return { stream: createStream() };
|
|
188
|
+
}
|
|
189
|
+
//#endregion
|
|
190
|
+
//#region src/generated/core/pathSerializer.gen.ts
|
|
191
|
+
const separatorArrayExplode = (style) => {
|
|
192
|
+
switch (style) {
|
|
193
|
+
case "label": return ".";
|
|
194
|
+
case "matrix": return ";";
|
|
195
|
+
case "simple": return ",";
|
|
196
|
+
default: return "&";
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
const separatorArrayNoExplode = (style) => {
|
|
200
|
+
switch (style) {
|
|
201
|
+
case "form": return ",";
|
|
202
|
+
case "pipeDelimited": return "|";
|
|
203
|
+
case "spaceDelimited": return "%20";
|
|
204
|
+
default: return ",";
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
const separatorObjectExplode = (style) => {
|
|
208
|
+
switch (style) {
|
|
209
|
+
case "label": return ".";
|
|
210
|
+
case "matrix": return ";";
|
|
211
|
+
case "simple": return ",";
|
|
212
|
+
default: return "&";
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
const serializeArrayParam = ({ allowReserved, explode, name, style, value }) => {
|
|
216
|
+
if (!explode) {
|
|
217
|
+
const joinedValues = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
|
|
218
|
+
switch (style) {
|
|
219
|
+
case "label": return `.${joinedValues}`;
|
|
220
|
+
case "matrix": return `;${name}=${joinedValues}`;
|
|
221
|
+
case "simple": return joinedValues;
|
|
222
|
+
default: return `${name}=${joinedValues}`;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
const separator = separatorArrayExplode(style);
|
|
226
|
+
const joinedValues = value.map((v) => {
|
|
227
|
+
if (style === "label" || style === "simple") return allowReserved ? v : encodeURIComponent(v);
|
|
228
|
+
return serializePrimitiveParam({
|
|
229
|
+
allowReserved,
|
|
230
|
+
name,
|
|
231
|
+
value: v
|
|
232
|
+
});
|
|
233
|
+
}).join(separator);
|
|
234
|
+
return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
|
|
235
|
+
};
|
|
236
|
+
const serializePrimitiveParam = ({ allowReserved, name, value }) => {
|
|
237
|
+
if (value === void 0 || value === null) return "";
|
|
238
|
+
if (typeof value === "object") throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");
|
|
239
|
+
return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
|
|
240
|
+
};
|
|
241
|
+
const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly }) => {
|
|
242
|
+
if (value instanceof Date) return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
|
|
243
|
+
if (style !== "deepObject" && !explode) {
|
|
244
|
+
let values = [];
|
|
245
|
+
Object.entries(value).forEach(([key, v]) => {
|
|
246
|
+
values = [
|
|
247
|
+
...values,
|
|
248
|
+
key,
|
|
249
|
+
allowReserved ? v : encodeURIComponent(v)
|
|
250
|
+
];
|
|
251
|
+
});
|
|
252
|
+
const joinedValues = values.join(",");
|
|
253
|
+
switch (style) {
|
|
254
|
+
case "form": return `${name}=${joinedValues}`;
|
|
255
|
+
case "label": return `.${joinedValues}`;
|
|
256
|
+
case "matrix": return `;${name}=${joinedValues}`;
|
|
257
|
+
default: return joinedValues;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
const separator = separatorObjectExplode(style);
|
|
261
|
+
const joinedValues = Object.entries(value).map(([key, v]) => serializePrimitiveParam({
|
|
262
|
+
allowReserved,
|
|
263
|
+
name: style === "deepObject" ? `${name}[${key}]` : key,
|
|
264
|
+
value: v
|
|
265
|
+
})).join(separator);
|
|
266
|
+
return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
|
|
267
|
+
};
|
|
268
|
+
//#endregion
|
|
269
|
+
//#region src/generated/core/utils.gen.ts
|
|
270
|
+
const PATH_PARAM_RE = /\{[^{}]+\}/g;
|
|
271
|
+
const defaultPathSerializer = ({ path, url: _url }) => {
|
|
272
|
+
let url = _url;
|
|
273
|
+
const matches = _url.match(PATH_PARAM_RE);
|
|
274
|
+
if (matches) for (const match of matches) {
|
|
275
|
+
let explode = false;
|
|
276
|
+
let name = match.substring(1, match.length - 1);
|
|
277
|
+
let style = "simple";
|
|
278
|
+
if (name.endsWith("*")) {
|
|
279
|
+
explode = true;
|
|
280
|
+
name = name.substring(0, name.length - 1);
|
|
281
|
+
}
|
|
282
|
+
if (name.startsWith(".")) {
|
|
283
|
+
name = name.substring(1);
|
|
284
|
+
style = "label";
|
|
285
|
+
} else if (name.startsWith(";")) {
|
|
286
|
+
name = name.substring(1);
|
|
287
|
+
style = "matrix";
|
|
288
|
+
}
|
|
289
|
+
const value = path[name];
|
|
290
|
+
if (value === void 0 || value === null) continue;
|
|
291
|
+
if (Array.isArray(value)) {
|
|
292
|
+
url = url.replace(match, serializeArrayParam({
|
|
293
|
+
explode,
|
|
294
|
+
name,
|
|
295
|
+
style,
|
|
296
|
+
value
|
|
297
|
+
}));
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
if (typeof value === "object") {
|
|
301
|
+
url = url.replace(match, serializeObjectParam({
|
|
302
|
+
explode,
|
|
303
|
+
name,
|
|
304
|
+
style,
|
|
305
|
+
value,
|
|
306
|
+
valueOnly: true
|
|
307
|
+
}));
|
|
308
|
+
continue;
|
|
309
|
+
}
|
|
310
|
+
if (style === "matrix") {
|
|
311
|
+
url = url.replace(match, `;${serializePrimitiveParam({
|
|
312
|
+
name,
|
|
313
|
+
value
|
|
314
|
+
})}`);
|
|
315
|
+
continue;
|
|
316
|
+
}
|
|
317
|
+
const replaceValue = encodeURIComponent(style === "label" ? `.${value}` : value);
|
|
318
|
+
url = url.replace(match, replaceValue);
|
|
319
|
+
}
|
|
320
|
+
return url;
|
|
321
|
+
};
|
|
322
|
+
const getUrl = ({ baseUrl, path, query, querySerializer, url: _url }) => {
|
|
323
|
+
const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
|
|
324
|
+
let url = (baseUrl ?? "") + pathUrl;
|
|
325
|
+
if (path) url = defaultPathSerializer({
|
|
326
|
+
path,
|
|
327
|
+
url
|
|
328
|
+
});
|
|
329
|
+
let search = query ? querySerializer(query) : "";
|
|
330
|
+
if (search.startsWith("?")) search = search.substring(1);
|
|
331
|
+
if (search) url += `?${search}`;
|
|
332
|
+
return url;
|
|
333
|
+
};
|
|
334
|
+
function getValidRequestBody(options) {
|
|
335
|
+
const hasBody = options.body !== void 0;
|
|
336
|
+
if (hasBody && options.bodySerializer) {
|
|
337
|
+
if ("serializedBody" in options) return options.serializedBody !== void 0 && options.serializedBody !== "" ? options.serializedBody : null;
|
|
338
|
+
return options.body !== "" ? options.body : null;
|
|
339
|
+
}
|
|
340
|
+
if (hasBody) return options.body;
|
|
341
|
+
}
|
|
342
|
+
//#endregion
|
|
343
|
+
//#region src/generated/core/auth.gen.ts
|
|
344
|
+
const getAuthToken = async (auth, callback) => {
|
|
345
|
+
const token = typeof callback === "function" ? await callback(auth) : callback;
|
|
346
|
+
if (!token) return;
|
|
347
|
+
if (auth.scheme === "bearer") return `Bearer ${token}`;
|
|
348
|
+
if (auth.scheme === "basic") return `Basic ${btoa(token)}`;
|
|
349
|
+
return token;
|
|
350
|
+
};
|
|
351
|
+
//#endregion
|
|
352
|
+
//#region src/generated/client/utils.gen.ts
|
|
353
|
+
const createQuerySerializer = ({ parameters = {}, ...args } = {}) => {
|
|
354
|
+
const querySerializer = (queryParams) => {
|
|
355
|
+
const search = [];
|
|
356
|
+
if (queryParams && typeof queryParams === "object") for (const name in queryParams) {
|
|
357
|
+
const value = queryParams[name];
|
|
358
|
+
if (value === void 0 || value === null) continue;
|
|
359
|
+
const options = parameters[name] || args;
|
|
360
|
+
if (Array.isArray(value)) {
|
|
361
|
+
const serializedArray = serializeArrayParam({
|
|
362
|
+
allowReserved: options.allowReserved,
|
|
363
|
+
explode: true,
|
|
364
|
+
name,
|
|
365
|
+
style: "form",
|
|
366
|
+
value,
|
|
367
|
+
...options.array
|
|
368
|
+
});
|
|
369
|
+
if (serializedArray) search.push(serializedArray);
|
|
370
|
+
} else if (typeof value === "object") {
|
|
371
|
+
const serializedObject = serializeObjectParam({
|
|
372
|
+
allowReserved: options.allowReserved,
|
|
373
|
+
explode: true,
|
|
374
|
+
name,
|
|
375
|
+
style: "deepObject",
|
|
376
|
+
value,
|
|
377
|
+
...options.object
|
|
378
|
+
});
|
|
379
|
+
if (serializedObject) search.push(serializedObject);
|
|
380
|
+
} else {
|
|
381
|
+
const serializedPrimitive = serializePrimitiveParam({
|
|
382
|
+
allowReserved: options.allowReserved,
|
|
383
|
+
name,
|
|
384
|
+
value
|
|
385
|
+
});
|
|
386
|
+
if (serializedPrimitive) search.push(serializedPrimitive);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
return search.join("&");
|
|
390
|
+
};
|
|
391
|
+
return querySerializer;
|
|
392
|
+
};
|
|
393
|
+
/**
|
|
394
|
+
* Infers parseAs value from provided Content-Type header.
|
|
395
|
+
*/
|
|
396
|
+
const getParseAs = (contentType) => {
|
|
397
|
+
if (!contentType) return "stream";
|
|
398
|
+
const cleanContent = contentType.split(";")[0]?.trim();
|
|
399
|
+
if (!cleanContent) return;
|
|
400
|
+
if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) return "json";
|
|
401
|
+
if (cleanContent === "multipart/form-data") return "formData";
|
|
402
|
+
if ([
|
|
403
|
+
"application/",
|
|
404
|
+
"audio/",
|
|
405
|
+
"image/",
|
|
406
|
+
"video/"
|
|
407
|
+
].some((type) => cleanContent.startsWith(type))) return "blob";
|
|
408
|
+
if (cleanContent.startsWith("text/")) return "text";
|
|
409
|
+
};
|
|
410
|
+
const checkForExistence = (options, name) => {
|
|
411
|
+
if (!name) return false;
|
|
412
|
+
if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) return true;
|
|
413
|
+
return false;
|
|
414
|
+
};
|
|
415
|
+
async function setAuthParams(options) {
|
|
416
|
+
for (const auth of options.security ?? []) {
|
|
417
|
+
if (checkForExistence(options, auth.name)) continue;
|
|
418
|
+
const token = await getAuthToken(auth, options.auth);
|
|
419
|
+
if (!token) continue;
|
|
420
|
+
const name = auth.name ?? "Authorization";
|
|
421
|
+
switch (auth.in) {
|
|
422
|
+
case "query":
|
|
423
|
+
if (!options.query) options.query = {};
|
|
424
|
+
options.query[name] = token;
|
|
425
|
+
break;
|
|
426
|
+
case "cookie":
|
|
427
|
+
options.headers.append("Cookie", `${name}=${token}`);
|
|
428
|
+
break;
|
|
429
|
+
default: options.headers.set(name, token);
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
const buildUrl = (options) => getUrl({
|
|
434
|
+
baseUrl: options.baseUrl,
|
|
435
|
+
path: options.path,
|
|
436
|
+
query: options.query,
|
|
437
|
+
querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
|
|
438
|
+
url: options.url
|
|
439
|
+
});
|
|
440
|
+
const mergeConfigs = (a, b) => {
|
|
441
|
+
const config = {
|
|
442
|
+
...a,
|
|
443
|
+
...b
|
|
444
|
+
};
|
|
445
|
+
if (config.baseUrl?.endsWith("/")) config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
|
|
446
|
+
config.headers = mergeHeaders(a.headers, b.headers);
|
|
447
|
+
return config;
|
|
448
|
+
};
|
|
449
|
+
const headersEntries = (headers) => {
|
|
450
|
+
const entries = [];
|
|
451
|
+
headers.forEach((value, key) => {
|
|
452
|
+
entries.push([key, value]);
|
|
453
|
+
});
|
|
454
|
+
return entries;
|
|
455
|
+
};
|
|
456
|
+
const mergeHeaders = (...headers) => {
|
|
457
|
+
const mergedHeaders = new Headers();
|
|
458
|
+
for (const header of headers) {
|
|
459
|
+
if (!header) continue;
|
|
460
|
+
const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
|
|
461
|
+
for (const [key, value] of iterator) if (value === null) mergedHeaders.delete(key);
|
|
462
|
+
else if (Array.isArray(value)) for (const v of value) mergedHeaders.append(key, v);
|
|
463
|
+
else if (value !== void 0) mergedHeaders.set(key, typeof value === "object" ? JSON.stringify(value) : value);
|
|
464
|
+
}
|
|
465
|
+
return mergedHeaders;
|
|
466
|
+
};
|
|
467
|
+
var Interceptors = class {
|
|
468
|
+
fns = [];
|
|
469
|
+
clear() {
|
|
470
|
+
this.fns = [];
|
|
471
|
+
}
|
|
472
|
+
eject(id) {
|
|
473
|
+
const index = this.getInterceptorIndex(id);
|
|
474
|
+
if (this.fns[index]) this.fns[index] = null;
|
|
475
|
+
}
|
|
476
|
+
exists(id) {
|
|
477
|
+
const index = this.getInterceptorIndex(id);
|
|
478
|
+
return Boolean(this.fns[index]);
|
|
479
|
+
}
|
|
480
|
+
getInterceptorIndex(id) {
|
|
481
|
+
if (typeof id === "number") return this.fns[id] ? id : -1;
|
|
482
|
+
return this.fns.indexOf(id);
|
|
483
|
+
}
|
|
484
|
+
update(id, fn) {
|
|
485
|
+
const index = this.getInterceptorIndex(id);
|
|
486
|
+
if (this.fns[index]) {
|
|
487
|
+
this.fns[index] = fn;
|
|
488
|
+
return id;
|
|
489
|
+
}
|
|
490
|
+
return false;
|
|
491
|
+
}
|
|
492
|
+
use(fn) {
|
|
493
|
+
this.fns.push(fn);
|
|
494
|
+
return this.fns.length - 1;
|
|
495
|
+
}
|
|
496
|
+
};
|
|
497
|
+
const createInterceptors = () => ({
|
|
498
|
+
error: new Interceptors(),
|
|
499
|
+
request: new Interceptors(),
|
|
500
|
+
response: new Interceptors()
|
|
501
|
+
});
|
|
502
|
+
const defaultQuerySerializer = createQuerySerializer({
|
|
503
|
+
allowReserved: false,
|
|
504
|
+
array: {
|
|
505
|
+
explode: true,
|
|
506
|
+
style: "form"
|
|
507
|
+
},
|
|
508
|
+
object: {
|
|
509
|
+
explode: true,
|
|
510
|
+
style: "deepObject"
|
|
511
|
+
}
|
|
512
|
+
});
|
|
513
|
+
const defaultHeaders = { "Content-Type": "application/json" };
|
|
514
|
+
const createConfig = (override = {}) => ({
|
|
515
|
+
...jsonBodySerializer,
|
|
516
|
+
headers: defaultHeaders,
|
|
517
|
+
parseAs: "auto",
|
|
518
|
+
querySerializer: defaultQuerySerializer,
|
|
519
|
+
...override
|
|
520
|
+
});
|
|
521
|
+
//#endregion
|
|
522
|
+
//#region src/generated/client/client.gen.ts
|
|
523
|
+
const createClient = (config = {}) => {
|
|
524
|
+
let _config = mergeConfigs(createConfig(), config);
|
|
525
|
+
const getConfig = () => ({ ..._config });
|
|
526
|
+
const setConfig = (config) => {
|
|
527
|
+
_config = mergeConfigs(_config, config);
|
|
528
|
+
return getConfig();
|
|
529
|
+
};
|
|
530
|
+
const interceptors = createInterceptors();
|
|
531
|
+
const beforeRequest = async (options) => {
|
|
532
|
+
const opts = {
|
|
533
|
+
..._config,
|
|
534
|
+
...options,
|
|
535
|
+
fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
|
|
536
|
+
headers: mergeHeaders(_config.headers, options.headers),
|
|
537
|
+
serializedBody: void 0
|
|
538
|
+
};
|
|
539
|
+
if (opts.security) await setAuthParams(opts);
|
|
540
|
+
if (opts.requestValidator) await opts.requestValidator(opts);
|
|
541
|
+
if (opts.body !== void 0 && opts.bodySerializer) opts.serializedBody = opts.bodySerializer(opts.body);
|
|
542
|
+
if (opts.body === void 0 || opts.serializedBody === "") opts.headers.delete("Content-Type");
|
|
543
|
+
const resolvedOpts = opts;
|
|
544
|
+
return {
|
|
545
|
+
opts: resolvedOpts,
|
|
546
|
+
url: buildUrl(resolvedOpts)
|
|
547
|
+
};
|
|
548
|
+
};
|
|
549
|
+
const request = async (options) => {
|
|
550
|
+
const throwOnError = options.throwOnError ?? _config.throwOnError;
|
|
551
|
+
const responseStyle = options.responseStyle ?? _config.responseStyle;
|
|
552
|
+
let request;
|
|
553
|
+
let response;
|
|
554
|
+
try {
|
|
555
|
+
const { opts, url } = await beforeRequest(options);
|
|
556
|
+
const requestInit = {
|
|
557
|
+
redirect: "follow",
|
|
558
|
+
...opts,
|
|
559
|
+
body: getValidRequestBody(opts)
|
|
560
|
+
};
|
|
561
|
+
request = new Request(url, requestInit);
|
|
562
|
+
for (const fn of interceptors.request.fns) if (fn) request = await fn(request, opts);
|
|
563
|
+
const _fetch = opts.fetch;
|
|
564
|
+
response = await _fetch(request);
|
|
565
|
+
for (const fn of interceptors.response.fns) if (fn) response = await fn(response, request, opts);
|
|
566
|
+
const result = {
|
|
567
|
+
request,
|
|
568
|
+
response
|
|
569
|
+
};
|
|
570
|
+
if (response.ok) {
|
|
571
|
+
const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
|
|
572
|
+
if (response.status === 204 || response.headers.get("Content-Length") === "0") {
|
|
573
|
+
let emptyData;
|
|
574
|
+
switch (parseAs) {
|
|
575
|
+
case "arrayBuffer":
|
|
576
|
+
case "blob":
|
|
577
|
+
case "text":
|
|
578
|
+
emptyData = await response[parseAs]();
|
|
579
|
+
break;
|
|
580
|
+
case "formData":
|
|
581
|
+
emptyData = new FormData();
|
|
582
|
+
break;
|
|
583
|
+
case "stream":
|
|
584
|
+
emptyData = response.body;
|
|
585
|
+
break;
|
|
586
|
+
default: emptyData = {};
|
|
587
|
+
}
|
|
588
|
+
return opts.responseStyle === "data" ? emptyData : {
|
|
589
|
+
data: emptyData,
|
|
590
|
+
...result
|
|
591
|
+
};
|
|
592
|
+
}
|
|
593
|
+
let data;
|
|
594
|
+
switch (parseAs) {
|
|
595
|
+
case "arrayBuffer":
|
|
596
|
+
case "blob":
|
|
597
|
+
case "formData":
|
|
598
|
+
case "text":
|
|
599
|
+
data = await response[parseAs]();
|
|
600
|
+
break;
|
|
601
|
+
case "json": {
|
|
602
|
+
const text = await response.text();
|
|
603
|
+
data = text ? JSON.parse(text) : {};
|
|
604
|
+
break;
|
|
605
|
+
}
|
|
606
|
+
case "stream": return opts.responseStyle === "data" ? response.body : {
|
|
607
|
+
data: response.body,
|
|
608
|
+
...result
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
if (parseAs === "json") {
|
|
612
|
+
if (opts.responseValidator) await opts.responseValidator(data);
|
|
613
|
+
if (opts.responseTransformer) data = await opts.responseTransformer(data);
|
|
614
|
+
}
|
|
615
|
+
return opts.responseStyle === "data" ? data : {
|
|
616
|
+
data,
|
|
617
|
+
...result
|
|
618
|
+
};
|
|
619
|
+
}
|
|
620
|
+
const textError = await response.text();
|
|
621
|
+
let jsonError;
|
|
622
|
+
try {
|
|
623
|
+
jsonError = JSON.parse(textError);
|
|
624
|
+
} catch {}
|
|
625
|
+
throw jsonError ?? textError;
|
|
626
|
+
} catch (error) {
|
|
627
|
+
let finalError = error;
|
|
628
|
+
for (const fn of interceptors.error.fns) if (fn) finalError = await fn(finalError, response, request, options);
|
|
629
|
+
finalError = finalError || {};
|
|
630
|
+
if (throwOnError) throw finalError;
|
|
631
|
+
return responseStyle === "data" ? void 0 : {
|
|
632
|
+
error: finalError,
|
|
633
|
+
request,
|
|
634
|
+
response
|
|
635
|
+
};
|
|
636
|
+
}
|
|
637
|
+
};
|
|
638
|
+
const makeMethodFn = (method) => (options) => request({
|
|
639
|
+
...options,
|
|
640
|
+
method
|
|
641
|
+
});
|
|
642
|
+
const makeSseFn = (method) => async (options) => {
|
|
643
|
+
const { opts, url } = await beforeRequest(options);
|
|
644
|
+
return createSseClient({
|
|
645
|
+
...opts,
|
|
646
|
+
body: opts.body,
|
|
647
|
+
method,
|
|
648
|
+
onRequest: async (url, init) => {
|
|
649
|
+
let request = new Request(url, init);
|
|
650
|
+
for (const fn of interceptors.request.fns) if (fn) request = await fn(request, opts);
|
|
651
|
+
return request;
|
|
652
|
+
},
|
|
653
|
+
serializedBody: getValidRequestBody(opts),
|
|
654
|
+
url
|
|
655
|
+
});
|
|
656
|
+
};
|
|
657
|
+
const _buildUrl = (options) => buildUrl({
|
|
658
|
+
..._config,
|
|
659
|
+
...options
|
|
660
|
+
});
|
|
661
|
+
return {
|
|
662
|
+
buildUrl: _buildUrl,
|
|
663
|
+
connect: makeMethodFn("CONNECT"),
|
|
664
|
+
delete: makeMethodFn("DELETE"),
|
|
665
|
+
get: makeMethodFn("GET"),
|
|
666
|
+
getConfig,
|
|
667
|
+
head: makeMethodFn("HEAD"),
|
|
668
|
+
interceptors,
|
|
669
|
+
options: makeMethodFn("OPTIONS"),
|
|
670
|
+
patch: makeMethodFn("PATCH"),
|
|
671
|
+
post: makeMethodFn("POST"),
|
|
672
|
+
put: makeMethodFn("PUT"),
|
|
673
|
+
request,
|
|
674
|
+
setConfig,
|
|
675
|
+
sse: {
|
|
676
|
+
connect: makeSseFn("CONNECT"),
|
|
677
|
+
delete: makeSseFn("DELETE"),
|
|
678
|
+
get: makeSseFn("GET"),
|
|
679
|
+
head: makeSseFn("HEAD"),
|
|
680
|
+
options: makeSseFn("OPTIONS"),
|
|
681
|
+
patch: makeSseFn("PATCH"),
|
|
682
|
+
post: makeSseFn("POST"),
|
|
683
|
+
put: makeSseFn("PUT"),
|
|
684
|
+
trace: makeSseFn("TRACE")
|
|
685
|
+
},
|
|
686
|
+
trace: makeMethodFn("TRACE")
|
|
687
|
+
};
|
|
688
|
+
};
|
|
689
|
+
//#endregion
|
|
690
|
+
//#region src/generated/client.gen.ts
|
|
691
|
+
const client = createClient(createConfig({
|
|
692
|
+
baseUrl: "https://api.exa.ai",
|
|
693
|
+
throwOnError: true
|
|
694
|
+
}));
|
|
695
|
+
//#endregion
|
|
696
|
+
//#region src/generated/zod.gen.ts
|
|
697
|
+
const zAnswerCitation = z.object({
|
|
698
|
+
id: z.string().optional(),
|
|
699
|
+
url: z.url().optional(),
|
|
700
|
+
title: z.string().optional(),
|
|
701
|
+
author: z.string().nullish(),
|
|
702
|
+
publishedDate: z.string().nullish(),
|
|
703
|
+
text: z.string().optional(),
|
|
704
|
+
image: z.url().optional(),
|
|
705
|
+
favicon: z.url().optional()
|
|
706
|
+
});
|
|
707
|
+
const zAnswerResult = z.object({
|
|
708
|
+
answer: z.union([z.string(), z.record(z.string(), z.unknown())]).optional(),
|
|
709
|
+
citations: z.array(zAnswerCitation).optional()
|
|
710
|
+
});
|
|
711
|
+
const zContentsRequest = z.object({
|
|
712
|
+
text: z.union([z.boolean(), z.object({
|
|
713
|
+
maxCharacters: z.int().optional(),
|
|
714
|
+
includeHtmlTags: z.boolean().optional().default(false),
|
|
715
|
+
verbosity: z.enum([
|
|
716
|
+
"compact",
|
|
717
|
+
"standard",
|
|
718
|
+
"full"
|
|
719
|
+
]).optional().default("compact"),
|
|
720
|
+
includeSections: z.array(z.enum([
|
|
721
|
+
"header",
|
|
722
|
+
"navigation",
|
|
723
|
+
"banner",
|
|
724
|
+
"body",
|
|
725
|
+
"sidebar",
|
|
726
|
+
"footer",
|
|
727
|
+
"metadata"
|
|
728
|
+
])).optional(),
|
|
729
|
+
excludeSections: z.array(z.enum([
|
|
730
|
+
"header",
|
|
731
|
+
"navigation",
|
|
732
|
+
"banner",
|
|
733
|
+
"body",
|
|
734
|
+
"sidebar",
|
|
735
|
+
"footer",
|
|
736
|
+
"metadata"
|
|
737
|
+
])).optional()
|
|
738
|
+
})]).optional(),
|
|
739
|
+
highlights: z.union([z.boolean(), z.object({
|
|
740
|
+
maxCharacters: z.int().gte(1).optional(),
|
|
741
|
+
numSentences: z.int().gte(1).optional(),
|
|
742
|
+
highlightsPerUrl: z.int().gte(1).optional(),
|
|
743
|
+
query: z.string().optional()
|
|
744
|
+
})]).optional(),
|
|
745
|
+
summary: z.object({
|
|
746
|
+
query: z.string().optional(),
|
|
747
|
+
schema: z.record(z.string(), z.unknown()).optional()
|
|
748
|
+
}).optional(),
|
|
749
|
+
livecrawl: z.enum([
|
|
750
|
+
"never",
|
|
751
|
+
"fallback",
|
|
752
|
+
"preferred",
|
|
753
|
+
"always"
|
|
754
|
+
]).optional(),
|
|
755
|
+
livecrawlTimeout: z.int().optional().default(1e4),
|
|
756
|
+
maxAgeHours: z.int().optional(),
|
|
757
|
+
subpages: z.int().optional().default(0),
|
|
758
|
+
subpageTarget: z.union([z.string(), z.array(z.string())]).optional(),
|
|
759
|
+
extras: z.object({
|
|
760
|
+
links: z.int().optional().default(0),
|
|
761
|
+
imageLinks: z.int().optional().default(0)
|
|
762
|
+
}).optional(),
|
|
763
|
+
context: z.union([z.boolean(), z.object({ maxCharacters: z.int().optional() })]).optional()
|
|
764
|
+
});
|
|
765
|
+
const zCommonRequest = z.object({
|
|
766
|
+
numResults: z.int().gte(1).lte(100).optional().default(10),
|
|
767
|
+
includeDomains: z.array(z.string()).optional(),
|
|
768
|
+
excludeDomains: z.array(z.string()).optional(),
|
|
769
|
+
startCrawlDate: z.iso.datetime().optional(),
|
|
770
|
+
endCrawlDate: z.iso.datetime().optional(),
|
|
771
|
+
startPublishedDate: z.iso.datetime().optional(),
|
|
772
|
+
endPublishedDate: z.iso.datetime().optional(),
|
|
773
|
+
includeText: z.array(z.string()).optional(),
|
|
774
|
+
excludeText: z.array(z.string()).optional(),
|
|
775
|
+
context: z.union([z.boolean(), z.object({ maxCharacters: z.int().optional() })]).optional(),
|
|
776
|
+
moderation: z.boolean().optional().default(false),
|
|
777
|
+
contents: zContentsRequest.optional()
|
|
778
|
+
});
|
|
779
|
+
/**
|
|
780
|
+
* Company workforce information.
|
|
781
|
+
*/
|
|
782
|
+
const zEntityCompanyPropertiesWorkforce = z.object({ total: z.int().nullish() });
|
|
783
|
+
/**
|
|
784
|
+
* Company headquarters information.
|
|
785
|
+
*/
|
|
786
|
+
const zEntityCompanyPropertiesHeadquarters = z.object({
|
|
787
|
+
address: z.string().nullish(),
|
|
788
|
+
city: z.string().nullish(),
|
|
789
|
+
postalCode: z.string().nullish(),
|
|
790
|
+
country: z.string().nullish()
|
|
791
|
+
});
|
|
792
|
+
/**
|
|
793
|
+
* Funding round information.
|
|
794
|
+
*/
|
|
795
|
+
const zEntityCompanyPropertiesFundingRound = z.object({
|
|
796
|
+
name: z.string().nullish(),
|
|
797
|
+
date: z.string().nullish(),
|
|
798
|
+
amount: z.int().nullish()
|
|
799
|
+
});
|
|
800
|
+
/**
|
|
801
|
+
* Company financial information.
|
|
802
|
+
*/
|
|
803
|
+
const zEntityCompanyPropertiesFinancials = z.object({
|
|
804
|
+
revenueAnnual: z.int().nullish(),
|
|
805
|
+
fundingTotal: z.int().nullish(),
|
|
806
|
+
fundingLatestRound: zEntityCompanyPropertiesFundingRound.nullish()
|
|
807
|
+
});
|
|
808
|
+
/**
|
|
809
|
+
* Company web traffic information.
|
|
810
|
+
*/
|
|
811
|
+
const zEntityCompanyPropertiesWebTraffic = z.object({ visitsMonthly: z.int().nullish() });
|
|
812
|
+
/**
|
|
813
|
+
* Structured properties for a company entity.
|
|
814
|
+
*/
|
|
815
|
+
const zEntityCompanyProperties = z.object({
|
|
816
|
+
name: z.string().nullish(),
|
|
817
|
+
foundedYear: z.int().nullish(),
|
|
818
|
+
description: z.string().nullish(),
|
|
819
|
+
workforce: zEntityCompanyPropertiesWorkforce.nullish(),
|
|
820
|
+
headquarters: zEntityCompanyPropertiesHeadquarters.nullish(),
|
|
821
|
+
financials: zEntityCompanyPropertiesFinancials.nullish(),
|
|
822
|
+
webTraffic: zEntityCompanyPropertiesWebTraffic.nullish()
|
|
823
|
+
});
|
|
824
|
+
/**
|
|
825
|
+
* Date range for work history entries.
|
|
826
|
+
*/
|
|
827
|
+
const zEntityDateRange = z.object({
|
|
828
|
+
from: z.string().nullish(),
|
|
829
|
+
to: z.string().nullish()
|
|
830
|
+
});
|
|
831
|
+
/**
|
|
832
|
+
* Reference to a company in work history.
|
|
833
|
+
*/
|
|
834
|
+
const zEntityPersonPropertiesCompanyRef = z.object({
|
|
835
|
+
id: z.string().nullish(),
|
|
836
|
+
name: z.string().nullish()
|
|
837
|
+
});
|
|
838
|
+
/**
|
|
839
|
+
* A single work history entry for a person.
|
|
840
|
+
*/
|
|
841
|
+
const zEntityPersonPropertiesWorkHistoryEntry = z.object({
|
|
842
|
+
title: z.string().nullish(),
|
|
843
|
+
location: z.string().nullish(),
|
|
844
|
+
dates: zEntityDateRange.nullish(),
|
|
845
|
+
company: zEntityPersonPropertiesCompanyRef.nullish()
|
|
846
|
+
});
|
|
847
|
+
/**
|
|
848
|
+
* Structured properties for a person entity.
|
|
849
|
+
*/
|
|
850
|
+
const zEntityPersonProperties = z.object({
|
|
851
|
+
name: z.string().nullish(),
|
|
852
|
+
location: z.string().nullish(),
|
|
853
|
+
workHistory: z.array(zEntityPersonPropertiesWorkHistoryEntry).optional()
|
|
854
|
+
});
|
|
855
|
+
/**
|
|
856
|
+
* Structured entity data for a company.
|
|
857
|
+
*/
|
|
858
|
+
const zCompanyEntity = z.object({
|
|
859
|
+
id: z.string(),
|
|
860
|
+
type: z.enum(["company"]),
|
|
861
|
+
version: z.int(),
|
|
862
|
+
properties: zEntityCompanyProperties
|
|
863
|
+
});
|
|
864
|
+
/**
|
|
865
|
+
* Structured entity data for a person.
|
|
866
|
+
*/
|
|
867
|
+
const zPersonEntity = z.object({
|
|
868
|
+
id: z.string(),
|
|
869
|
+
type: z.enum(["person"]),
|
|
870
|
+
version: z.int(),
|
|
871
|
+
properties: zEntityPersonProperties
|
|
872
|
+
});
|
|
873
|
+
/**
|
|
874
|
+
* Structured entity data for company or person search results. Only returned for category=company or category=people searches.
|
|
875
|
+
*/
|
|
876
|
+
const zEntity = z.discriminatedUnion("type", [zCompanyEntity.extend({ type: z.literal("company") }), zPersonEntity.extend({ type: z.literal("person") })]);
|
|
877
|
+
const zResultWithContent = z.object({
|
|
878
|
+
title: z.string().optional(),
|
|
879
|
+
url: z.url().optional(),
|
|
880
|
+
publishedDate: z.string().nullish(),
|
|
881
|
+
author: z.string().nullish(),
|
|
882
|
+
score: z.number().nullish(),
|
|
883
|
+
id: z.string().optional(),
|
|
884
|
+
image: z.url().optional(),
|
|
885
|
+
favicon: z.url().optional()
|
|
886
|
+
}).and(z.lazy(() => z.object({
|
|
887
|
+
text: z.string().optional(),
|
|
888
|
+
highlights: z.array(z.string()).optional(),
|
|
889
|
+
highlightScores: z.array(z.number()).optional(),
|
|
890
|
+
summary: z.string().optional(),
|
|
891
|
+
subpages: z.array(z.lazy(() => zResultWithContent)).optional(),
|
|
892
|
+
extras: z.object({ links: z.array(z.string()).optional() }).optional(),
|
|
893
|
+
entities: z.array(zEntity).optional()
|
|
894
|
+
})));
|
|
895
|
+
const zCostDollars = z.object({
|
|
896
|
+
total: z.number().optional(),
|
|
897
|
+
breakDown: z.array(z.object({
|
|
898
|
+
search: z.number().optional(),
|
|
899
|
+
contents: z.number().optional(),
|
|
900
|
+
breakdown: z.object({
|
|
901
|
+
neuralSearch: z.number().optional(),
|
|
902
|
+
deepSearch: z.number().optional(),
|
|
903
|
+
contentText: z.number().optional(),
|
|
904
|
+
contentHighlight: z.number().optional(),
|
|
905
|
+
contentSummary: z.number().optional()
|
|
906
|
+
}).optional()
|
|
907
|
+
})).optional(),
|
|
908
|
+
perRequestPrices: z.object({
|
|
909
|
+
neuralSearch_1_25_results: z.number().optional(),
|
|
910
|
+
neuralSearch_26_100_results: z.number().optional(),
|
|
911
|
+
neuralSearch_100_plus_results: z.number().optional(),
|
|
912
|
+
deepSearch_1_25_results: z.number().optional(),
|
|
913
|
+
deepSearch_26_100_results: z.number().optional()
|
|
914
|
+
}).optional(),
|
|
915
|
+
perPagePrices: z.object({
|
|
916
|
+
contentText: z.number().optional(),
|
|
917
|
+
contentHighlight: z.number().optional(),
|
|
918
|
+
contentSummary: z.number().optional()
|
|
919
|
+
}).optional()
|
|
920
|
+
});
|
|
921
|
+
const zResearchTaskDto = z.object({
|
|
922
|
+
id: z.string(),
|
|
923
|
+
status: z.enum([
|
|
924
|
+
"running",
|
|
925
|
+
"completed",
|
|
926
|
+
"failed"
|
|
927
|
+
]),
|
|
928
|
+
instructions: z.string(),
|
|
929
|
+
schema: z.record(z.string(), z.unknown()).optional(),
|
|
930
|
+
data: z.record(z.string(), z.unknown()).optional(),
|
|
931
|
+
citations: z.record(z.string(), z.array(z.object({
|
|
932
|
+
id: z.string(),
|
|
933
|
+
url: z.string(),
|
|
934
|
+
title: z.string().optional(),
|
|
935
|
+
snippet: z.string()
|
|
936
|
+
}))).optional()
|
|
937
|
+
});
|
|
938
|
+
const zSearchBody = z.object({
|
|
939
|
+
query: z.string(),
|
|
940
|
+
additionalQueries: z.array(z.string()).optional(),
|
|
941
|
+
type: z.enum([
|
|
942
|
+
"neural",
|
|
943
|
+
"fast",
|
|
944
|
+
"auto",
|
|
945
|
+
"deep",
|
|
946
|
+
"deep-reasoning",
|
|
947
|
+
"instant"
|
|
948
|
+
]).optional().default("auto"),
|
|
949
|
+
outputSchema: z.record(z.string(), z.unknown()).optional(),
|
|
950
|
+
category: z.enum([
|
|
951
|
+
"company",
|
|
952
|
+
"research paper",
|
|
953
|
+
"news",
|
|
954
|
+
"pdf",
|
|
955
|
+
"github",
|
|
956
|
+
"personal site",
|
|
957
|
+
"people",
|
|
958
|
+
"financial report"
|
|
959
|
+
]).optional(),
|
|
960
|
+
userLocation: z.string().optional()
|
|
961
|
+
}).and(zCommonRequest);
|
|
962
|
+
/**
|
|
963
|
+
* OK
|
|
964
|
+
*/
|
|
965
|
+
const zSearchResponse = z.object({
|
|
966
|
+
requestId: z.string().optional(),
|
|
967
|
+
results: z.array(zResultWithContent).optional(),
|
|
968
|
+
searchType: z.enum([
|
|
969
|
+
"neural",
|
|
970
|
+
"deep",
|
|
971
|
+
"deep-reasoning"
|
|
972
|
+
]).optional(),
|
|
973
|
+
context: z.string().optional(),
|
|
974
|
+
output: z.object({
|
|
975
|
+
content: z.union([z.string(), z.record(z.string(), z.unknown())]),
|
|
976
|
+
grounding: z.array(z.object({
|
|
977
|
+
field: z.string(),
|
|
978
|
+
citations: z.array(z.object({
|
|
979
|
+
url: z.string(),
|
|
980
|
+
title: z.string()
|
|
981
|
+
})),
|
|
982
|
+
confidence: z.enum([
|
|
983
|
+
"low",
|
|
984
|
+
"medium",
|
|
985
|
+
"high"
|
|
986
|
+
])
|
|
987
|
+
}))
|
|
988
|
+
}).optional(),
|
|
989
|
+
costDollars: zCostDollars.optional()
|
|
990
|
+
});
|
|
991
|
+
z.object({
|
|
992
|
+
url: z.string(),
|
|
993
|
+
excludeSourceDomain: z.boolean().optional()
|
|
994
|
+
}).and(zCommonRequest);
|
|
995
|
+
z.object({
|
|
996
|
+
requestId: z.string().optional(),
|
|
997
|
+
context: z.string().optional(),
|
|
998
|
+
results: z.array(zResultWithContent).optional(),
|
|
999
|
+
costDollars: zCostDollars.optional()
|
|
1000
|
+
});
|
|
1001
|
+
const zGetContentsBody = z.object({
|
|
1002
|
+
urls: z.array(z.string()),
|
|
1003
|
+
ids: z.array(z.string()).optional()
|
|
1004
|
+
}).and(zContentsRequest);
|
|
1005
|
+
/**
|
|
1006
|
+
* OK
|
|
1007
|
+
*/
|
|
1008
|
+
const zGetContentsResponse = z.object({
|
|
1009
|
+
requestId: z.string().optional(),
|
|
1010
|
+
results: z.array(zResultWithContent).optional(),
|
|
1011
|
+
context: z.string().optional(),
|
|
1012
|
+
statuses: z.array(z.object({
|
|
1013
|
+
id: z.string().optional(),
|
|
1014
|
+
status: z.enum(["success", "error"]).optional(),
|
|
1015
|
+
error: z.object({
|
|
1016
|
+
tag: z.enum([
|
|
1017
|
+
"CRAWL_NOT_FOUND",
|
|
1018
|
+
"CRAWL_TIMEOUT",
|
|
1019
|
+
"CRAWL_LIVECRAWL_TIMEOUT",
|
|
1020
|
+
"SOURCE_NOT_AVAILABLE",
|
|
1021
|
+
"UNSUPPORTED_URL",
|
|
1022
|
+
"CRAWL_UNKNOWN_ERROR"
|
|
1023
|
+
]).optional(),
|
|
1024
|
+
httpStatusCode: z.int().optional()
|
|
1025
|
+
}).optional()
|
|
1026
|
+
})).optional(),
|
|
1027
|
+
costDollars: zCostDollars.optional()
|
|
1028
|
+
});
|
|
1029
|
+
const zAnswerBody = z.object({
|
|
1030
|
+
query: z.string().min(1),
|
|
1031
|
+
stream: z.boolean().optional().default(false),
|
|
1032
|
+
text: z.boolean().optional().default(false),
|
|
1033
|
+
outputSchema: z.object({
|
|
1034
|
+
type: z.string().optional(),
|
|
1035
|
+
properties: z.record(z.string(), z.unknown()).optional(),
|
|
1036
|
+
required: z.array(z.string()).optional(),
|
|
1037
|
+
description: z.string().optional(),
|
|
1038
|
+
additionalProperties: z.boolean().optional().default(false)
|
|
1039
|
+
}).optional()
|
|
1040
|
+
});
|
|
1041
|
+
/**
|
|
1042
|
+
* OK
|
|
1043
|
+
*/
|
|
1044
|
+
const zAnswerResponse = zAnswerResult.and(z.object({ costDollars: zCostDollars.optional() }));
|
|
1045
|
+
z.object({
|
|
1046
|
+
cursor: z.string().min(1).optional(),
|
|
1047
|
+
limit: z.number().gte(1).lte(200).optional().default(25)
|
|
1048
|
+
});
|
|
1049
|
+
z.object({
|
|
1050
|
+
requestId: z.string().optional(),
|
|
1051
|
+
data: z.array(zResearchTaskDto).optional(),
|
|
1052
|
+
hasMore: z.boolean().optional(),
|
|
1053
|
+
nextCursor: z.string().optional()
|
|
1054
|
+
});
|
|
1055
|
+
z.object({
|
|
1056
|
+
instructions: z.string().max(4096),
|
|
1057
|
+
model: z.enum(["exa-research", "exa-research-pro"]).optional().default("exa-research"),
|
|
1058
|
+
output: z.object({
|
|
1059
|
+
schema: z.unknown().optional(),
|
|
1060
|
+
inferSchema: z.boolean().optional()
|
|
1061
|
+
}).optional()
|
|
1062
|
+
});
|
|
1063
|
+
z.object({ id: z.string().optional() });
|
|
1064
|
+
z.object({ id: z.string() });
|
|
1065
|
+
//#endregion
|
|
1066
|
+
//#region src/generated/sdk.gen.ts
|
|
1067
|
+
/**
|
|
1068
|
+
* Search
|
|
1069
|
+
*
|
|
1070
|
+
* Perform a search with a Exa prompt-engineered query and retrieve a list of relevant results. Optionally get contents.
|
|
1071
|
+
*/
|
|
1072
|
+
const search = (options) => (options.client ?? client).post({
|
|
1073
|
+
requestValidator: async (data) => await z.object({
|
|
1074
|
+
body: zSearchBody,
|
|
1075
|
+
path: z.never().optional(),
|
|
1076
|
+
query: z.never().optional()
|
|
1077
|
+
}).parseAsync(data),
|
|
1078
|
+
responseValidator: async (data) => await zSearchResponse.parseAsync(data),
|
|
1079
|
+
responseStyle: "data",
|
|
1080
|
+
security: [{
|
|
1081
|
+
name: "x-api-key",
|
|
1082
|
+
type: "apiKey"
|
|
1083
|
+
}],
|
|
1084
|
+
url: "/search",
|
|
1085
|
+
...options,
|
|
1086
|
+
headers: {
|
|
1087
|
+
"Content-Type": "application/json",
|
|
1088
|
+
...options.headers
|
|
1089
|
+
}
|
|
1090
|
+
});
|
|
1091
|
+
/**
|
|
1092
|
+
* Get Contents
|
|
1093
|
+
*/
|
|
1094
|
+
const getContents = (options) => (options.client ?? client).post({
|
|
1095
|
+
requestValidator: async (data) => await z.object({
|
|
1096
|
+
body: zGetContentsBody,
|
|
1097
|
+
path: z.never().optional(),
|
|
1098
|
+
query: z.never().optional()
|
|
1099
|
+
}).parseAsync(data),
|
|
1100
|
+
responseValidator: async (data) => await zGetContentsResponse.parseAsync(data),
|
|
1101
|
+
responseStyle: "data",
|
|
1102
|
+
security: [{
|
|
1103
|
+
name: "x-api-key",
|
|
1104
|
+
type: "apiKey"
|
|
1105
|
+
}],
|
|
1106
|
+
url: "/contents",
|
|
1107
|
+
...options,
|
|
1108
|
+
headers: {
|
|
1109
|
+
"Content-Type": "application/json",
|
|
1110
|
+
...options.headers
|
|
1111
|
+
}
|
|
1112
|
+
});
|
|
1113
|
+
/**
|
|
1114
|
+
* Generate an answer from search results
|
|
1115
|
+
*
|
|
1116
|
+
* Performs a search based on the query and generates either a direct answer or a detailed summary with citations, depending on the query type.
|
|
1117
|
+
*
|
|
1118
|
+
*/
|
|
1119
|
+
const answer = (options) => (options.client ?? client).post({
|
|
1120
|
+
requestValidator: async (data) => await z.object({
|
|
1121
|
+
body: zAnswerBody,
|
|
1122
|
+
path: z.never().optional(),
|
|
1123
|
+
query: z.never().optional()
|
|
1124
|
+
}).parseAsync(data),
|
|
1125
|
+
responseValidator: async (data) => await zAnswerResponse.parseAsync(data),
|
|
1126
|
+
responseStyle: "data",
|
|
1127
|
+
security: [{
|
|
1128
|
+
name: "x-api-key",
|
|
1129
|
+
type: "apiKey"
|
|
1130
|
+
}],
|
|
1131
|
+
url: "/answer",
|
|
1132
|
+
...options,
|
|
1133
|
+
headers: {
|
|
1134
|
+
"Content-Type": "application/json",
|
|
1135
|
+
...options.headers
|
|
1136
|
+
}
|
|
1137
|
+
});
|
|
1138
|
+
//#endregion
|
|
1139
|
+
//#region src/http/client.ts
|
|
1140
|
+
function createExaClient(options) {
|
|
1141
|
+
return createClient(createConfig({
|
|
1142
|
+
auth: () => options.apiKey,
|
|
1143
|
+
baseUrl: options.apiUrl,
|
|
1144
|
+
throwOnError: true
|
|
1145
|
+
}));
|
|
1146
|
+
}
|
|
1147
|
+
//#endregion
|
|
1148
|
+
//#region src/json.ts
|
|
1149
|
+
const jsonSchema = z.json();
|
|
1150
|
+
function parseJson(text) {
|
|
1151
|
+
return jsonSchema.parse(JSON.parse(text));
|
|
1152
|
+
}
|
|
1153
|
+
function isJsonObject(value) {
|
|
1154
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1155
|
+
}
|
|
1156
|
+
//#endregion
|
|
1157
|
+
//#region src/cache/key.ts
|
|
1158
|
+
function canonicalize(value) {
|
|
1159
|
+
if (Array.isArray(value)) return value.map((item) => canonicalize(item));
|
|
1160
|
+
if (isJsonObject(value)) return Object.fromEntries(Object.keys(value).toSorted().flatMap((key) => {
|
|
1161
|
+
const item = value[key];
|
|
1162
|
+
return item === void 0 ? [] : [[key, canonicalize(item)]];
|
|
1163
|
+
}));
|
|
1164
|
+
return value;
|
|
1165
|
+
}
|
|
1166
|
+
function cacheKey(identity) {
|
|
1167
|
+
const canonical = canonicalize({
|
|
1168
|
+
host: identity.host,
|
|
1169
|
+
operation: identity.operation,
|
|
1170
|
+
body: identity.body
|
|
1171
|
+
});
|
|
1172
|
+
return createHash("sha256").update(JSON.stringify(canonical)).digest("hex");
|
|
1173
|
+
}
|
|
1174
|
+
//#endregion
|
|
1175
|
+
//#region src/http/execute.ts
|
|
1176
|
+
async function executeCached(options) {
|
|
1177
|
+
const key = cacheKey({
|
|
1178
|
+
host: options.host,
|
|
1179
|
+
operation: options.operation,
|
|
1180
|
+
body: options.body
|
|
1181
|
+
});
|
|
1182
|
+
const cache = options.mode === "off" ? void 0 : options.cache;
|
|
1183
|
+
if (cache !== void 0 && options.mode === "default") {
|
|
1184
|
+
const hit = cache.get(key, options.ttlSeconds);
|
|
1185
|
+
if (hit !== void 0) return {
|
|
1186
|
+
payload: parseJson(hit.body),
|
|
1187
|
+
cacheHit: true,
|
|
1188
|
+
ageMs: Date.now() - hit.createdAt
|
|
1189
|
+
};
|
|
1190
|
+
}
|
|
1191
|
+
const payload = await options.fetchBody();
|
|
1192
|
+
if (cache !== void 0) cache.set(key, JSON.stringify(payload));
|
|
1193
|
+
return {
|
|
1194
|
+
payload,
|
|
1195
|
+
cacheHit: false,
|
|
1196
|
+
ageMs: void 0
|
|
1197
|
+
};
|
|
1198
|
+
}
|
|
1199
|
+
function cacheMode(flags) {
|
|
1200
|
+
return match(flags).returnType().with({ noCache: true }, () => "off").with({ refresh: true }, () => "refresh").otherwise(() => "default");
|
|
1201
|
+
}
|
|
1202
|
+
//#endregion
|
|
1203
|
+
//#region src/output/presenter.ts
|
|
1204
|
+
function resolveMode(options) {
|
|
1205
|
+
return match(options).returnType().when((value) => value.json || value.output?.endsWith(".json") === true || !value.stdoutIsTTY, () => "json").when((value) => value.pretty, () => "pretty").otherwise(() => "text");
|
|
1206
|
+
}
|
|
1207
|
+
function colorEnabled(options) {
|
|
1208
|
+
if (options.noColor || env.NO_COLOR !== void 0) return false;
|
|
1209
|
+
if (options.forceColor || env.FORCE_COLOR !== void 0) return true;
|
|
1210
|
+
return options.stdoutIsTTY;
|
|
1211
|
+
}
|
|
1212
|
+
function formatPayload(payload, mode, color) {
|
|
1213
|
+
return match(mode).with("json", () => `${JSON.stringify(payload)}\n`).with("pretty", () => `${JSON.stringify(payload, null, 2)}\n`).with("text", () => `${formatText(payload, color)}\n`).exhaustive();
|
|
1214
|
+
}
|
|
1215
|
+
function formatCacheHit(ageMs) {
|
|
1216
|
+
return `cache hit age=${formatAge(ageMs)}\n`;
|
|
1217
|
+
}
|
|
1218
|
+
function formatWrote(path) {
|
|
1219
|
+
return `wrote ${path}\n`;
|
|
1220
|
+
}
|
|
1221
|
+
function formatTiming(elapsedMs) {
|
|
1222
|
+
return `timing total=${Math.round(elapsedMs)}ms\n`;
|
|
1223
|
+
}
|
|
1224
|
+
function formatAge(ageMs) {
|
|
1225
|
+
const seconds = Math.max(0, Math.round(ageMs / 1e3));
|
|
1226
|
+
if (seconds < 60) return `${seconds}s`;
|
|
1227
|
+
const minutes = Math.round(seconds / 60);
|
|
1228
|
+
if (minutes < 60) return `${minutes}m`;
|
|
1229
|
+
return `${Math.round(minutes / 60)}h`;
|
|
1230
|
+
}
|
|
1231
|
+
function formatText(payload, color) {
|
|
1232
|
+
const pc = createColors(color);
|
|
1233
|
+
if (!isJsonObject(payload)) return JSON.stringify(payload, null, 2);
|
|
1234
|
+
return match(payload).when((value) => isStringField(value["answer"]) || Array.isArray(value["citations"]), (value) => formatAnswer(value, pc)).when((value) => Array.isArray(value["results"]), (value) => formatResults(asJsonArray(value["results"]), pc)).otherwise((value) => JSON.stringify(value, null, 2));
|
|
1235
|
+
}
|
|
1236
|
+
function formatResults(results, pc) {
|
|
1237
|
+
const lines = [];
|
|
1238
|
+
for (const result of results) {
|
|
1239
|
+
if (!isJsonObject(result)) continue;
|
|
1240
|
+
const url = result["url"];
|
|
1241
|
+
if (isStringField(url)) lines.push(pc.underline(url));
|
|
1242
|
+
const title = result["title"];
|
|
1243
|
+
if (isStringField(title)) lines.push(` ${pc.bold(title)}`);
|
|
1244
|
+
}
|
|
1245
|
+
return lines.join("\n");
|
|
1246
|
+
}
|
|
1247
|
+
function formatAnswer(payload, pc) {
|
|
1248
|
+
const lines = [];
|
|
1249
|
+
const answer = payload["answer"];
|
|
1250
|
+
if (isStringField(answer)) lines.push(answer);
|
|
1251
|
+
else if (answer !== void 0 && answer !== null) lines.push(JSON.stringify(answer, null, 2));
|
|
1252
|
+
const citations = payload["citations"];
|
|
1253
|
+
if (Array.isArray(citations)) for (const citation of citations) {
|
|
1254
|
+
if (!isJsonObject(citation)) continue;
|
|
1255
|
+
const url = citation["url"];
|
|
1256
|
+
if (isStringField(url)) lines.push(pc.underline(url));
|
|
1257
|
+
}
|
|
1258
|
+
return lines.join("\n");
|
|
1259
|
+
}
|
|
1260
|
+
function isStringField(value) {
|
|
1261
|
+
return z.string().trim().safeParse(value).success;
|
|
1262
|
+
}
|
|
1263
|
+
function asJsonArray(value) {
|
|
1264
|
+
return Array.isArray(value) ? value : [];
|
|
1265
|
+
}
|
|
1266
|
+
//#endregion
|
|
1267
|
+
//#region src/parser.ts
|
|
1268
|
+
const querySchema = z.string().trim().min(1, { error: "Query must not be empty." }).meta({ description: "Exa query" });
|
|
1269
|
+
const countSchema = z.coerce.number().positive({ error: "Expected a positive number." }).meta({ description: "Positive count" });
|
|
1270
|
+
function jsonBody(schema) {
|
|
1271
|
+
return z.string().trim().transform((raw, ctx) => {
|
|
1272
|
+
try {
|
|
1273
|
+
return schema.parse(parseJson(raw));
|
|
1274
|
+
} catch {
|
|
1275
|
+
ctx.addIssue({
|
|
1276
|
+
code: "custom",
|
|
1277
|
+
message: "Expected JSON."
|
|
1278
|
+
});
|
|
1279
|
+
return z.NEVER;
|
|
1280
|
+
}
|
|
1281
|
+
});
|
|
1282
|
+
}
|
|
1283
|
+
const envContext = createEnvContext();
|
|
1284
|
+
const apiKeyParser = bindEnv(optional(option("-k", "--api-key", zod(querySchema, { placeholder: "key" }), { description: message`Exa API key. Falls back to EXA_API_KEY.` })), {
|
|
1285
|
+
context: envContext,
|
|
1286
|
+
key: "EXA_API_KEY",
|
|
1287
|
+
parser: zod(querySchema, { placeholder: "key" })
|
|
1288
|
+
});
|
|
1289
|
+
const apiUrlParser = bindEnv(optional(option("--api-url", zod(querySchema, { placeholder: "https://api.exa.ai" }), { description: message`Exa API base URL.` })), {
|
|
1290
|
+
context: envContext,
|
|
1291
|
+
key: "EXA_API_URL",
|
|
1292
|
+
parser: zod(querySchema, { placeholder: "https://api.exa.ai" }),
|
|
1293
|
+
default: "https://api.exa.ai"
|
|
1294
|
+
});
|
|
1295
|
+
function globalFields() {
|
|
1296
|
+
return {
|
|
1297
|
+
apiKey: apiKeyParser,
|
|
1298
|
+
apiUrl: apiUrlParser,
|
|
1299
|
+
json: withDefault(flag("--json", { description: message`Write compact JSON to stdout.` }), false),
|
|
1300
|
+
pretty: withDefault(flag("--pretty", { description: message`Write indented JSON to stdout.` }), false),
|
|
1301
|
+
output: optional(option("-o", "--output", path({
|
|
1302
|
+
allowCreate: true,
|
|
1303
|
+
metavar: "FILE"
|
|
1304
|
+
}), { description: message`Write the payload to a file instead of stdout.` })),
|
|
1305
|
+
timing: withDefault(flag("--timing", { description: message`Print elapsed time on stderr.` }), false),
|
|
1306
|
+
refresh: withDefault(flag("--refresh", { description: message`Ignore cache reads and overwrite the stored response.` }), false),
|
|
1307
|
+
noCache: withDefault(flag("--no-cache", { description: message`Skip cache reads and writes.` }), false),
|
|
1308
|
+
ttl: optional(option("--ttl", zod(countSchema, { placeholder: 86400 }), { description: message`Cache TTL in seconds. Default 86400.` })),
|
|
1309
|
+
envelope: withDefault(flag("--envelope", { description: message`Wrap JSON output with cache metadata.` }), false),
|
|
1310
|
+
color: optional(negatableFlag({
|
|
1311
|
+
positive: "--color",
|
|
1312
|
+
negative: "--no-color"
|
|
1313
|
+
}, { description: message`Force or disable color.` }))
|
|
1314
|
+
};
|
|
1315
|
+
}
|
|
1316
|
+
const searchCommand = command("search", object({
|
|
1317
|
+
command: constant("search"),
|
|
1318
|
+
...globalFields(),
|
|
1319
|
+
query: optional(argument(zod(querySchema, { placeholder: "query" }), { description: message`Search query. Omit when using --request.` })),
|
|
1320
|
+
request: optional(option("--request", zod(jsonBody(zSearchBody), {
|
|
1321
|
+
metavar: "JSON",
|
|
1322
|
+
placeholder: zSearchBody.parse({ query: "query" })
|
|
1323
|
+
}), { description: message`JSON search body for /search.` })),
|
|
1324
|
+
numResults: optional(option("-n", "--num-results", zod(countSchema, { placeholder: 10 }), { description: message`Number of results.` })),
|
|
1325
|
+
type: optional(option("--type", choice([
|
|
1326
|
+
"neural",
|
|
1327
|
+
"fast",
|
|
1328
|
+
"auto",
|
|
1329
|
+
"deep",
|
|
1330
|
+
"deep-reasoning",
|
|
1331
|
+
"instant"
|
|
1332
|
+
]), { description: message`Search type.` })),
|
|
1333
|
+
includeDomain: multiple(option("--include-domain", zod(querySchema, { placeholder: "exa.ai" }), { description: message`Restrict results to this domain. Repeatable.` }))
|
|
1334
|
+
}));
|
|
1335
|
+
const contentsCommand = command("contents", object({
|
|
1336
|
+
command: constant("contents"),
|
|
1337
|
+
...globalFields(),
|
|
1338
|
+
urls: multiple(argument(zod(querySchema, { placeholder: "URL" }), { description: message`Page URL. Repeatable. Omit when using --request.` })),
|
|
1339
|
+
request: optional(option("--request", zod(jsonBody(zGetContentsBody), {
|
|
1340
|
+
metavar: "JSON",
|
|
1341
|
+
placeholder: zGetContentsBody.parse({ urls: ["https://exa.ai"] })
|
|
1342
|
+
}), { description: message`JSON contents body for /contents.` })),
|
|
1343
|
+
maxAgeHours: optional(option("--max-age-hours", zod(countSchema, { placeholder: 24 }), { description: message`Provider contents freshness window.` }))
|
|
1344
|
+
}));
|
|
1345
|
+
const answerCommand = command("answer", object({
|
|
1346
|
+
command: constant("answer"),
|
|
1347
|
+
...globalFields(),
|
|
1348
|
+
query: optional(argument(zod(querySchema, { placeholder: "query" }), { description: message`Question to answer. Omit when using --request.` })),
|
|
1349
|
+
request: optional(option("--request", zod(jsonBody(zAnswerBody), {
|
|
1350
|
+
metavar: "JSON",
|
|
1351
|
+
placeholder: zAnswerBody.parse({ query: "query" })
|
|
1352
|
+
}), { description: message`JSON answer body for /answer.` })),
|
|
1353
|
+
text: withDefault(flag("--text", { description: message`Include full text on citations.` }), false)
|
|
1354
|
+
}));
|
|
1355
|
+
const doctorCommand = command("doctor", object({
|
|
1356
|
+
command: constant("doctor"),
|
|
1357
|
+
...globalFields()
|
|
1358
|
+
}));
|
|
1359
|
+
const parser = or(searchCommand, contentsCommand, answerCommand, doctorCommand);
|
|
1360
|
+
const version = "0.0.0";
|
|
1361
|
+
//#endregion
|
|
1362
|
+
//#region src/app.ts
|
|
1363
|
+
async function runAppParse(args) {
|
|
1364
|
+
const options = {
|
|
1365
|
+
programName: "exa",
|
|
1366
|
+
brief: message`CLI for Exa search, contents, and answer.`,
|
|
1367
|
+
help: "both",
|
|
1368
|
+
version,
|
|
1369
|
+
completion: "both",
|
|
1370
|
+
contexts: [envContext]
|
|
1371
|
+
};
|
|
1372
|
+
if (args === void 0) return await run(parser, options);
|
|
1373
|
+
return await run(parser, {
|
|
1374
|
+
...options,
|
|
1375
|
+
args
|
|
1376
|
+
});
|
|
1377
|
+
}
|
|
1378
|
+
async function runApp(args) {
|
|
1379
|
+
await dispatch(await runAppParse(args));
|
|
1380
|
+
}
|
|
1381
|
+
async function dispatch(parsed) {
|
|
1382
|
+
await match(parsed).with({ command: "doctor" }, (value) => {
|
|
1383
|
+
runDoctor(value);
|
|
1384
|
+
return Promise.resolve();
|
|
1385
|
+
}).with({ command: "search" }, runSearch).with({ command: "contents" }, runContents).with({ command: "answer" }, runAnswer).exhaustive();
|
|
1386
|
+
}
|
|
1387
|
+
function runDoctor(parsed) {
|
|
1388
|
+
const cache = new CacheStore(defaultCachePath());
|
|
1389
|
+
const lines = [
|
|
1390
|
+
`api-key: ${parsed.apiKey === void 0 || parsed.apiKey === "" ? "missing" : "set"}`,
|
|
1391
|
+
`api-url: ${parsed.apiUrl ?? "https://api.exa.ai"}`,
|
|
1392
|
+
`cache: ${cache.path}`,
|
|
1393
|
+
`entries: ${String(cache.count())}`
|
|
1394
|
+
];
|
|
1395
|
+
cache.close();
|
|
1396
|
+
process.stdout.write(`${lines.join("\n")}\n`);
|
|
1397
|
+
}
|
|
1398
|
+
async function runSearch(parsed) {
|
|
1399
|
+
const started = Date.now();
|
|
1400
|
+
const body = parsed.request !== void 0 ? zSearchBody.parse(parsed.request) : flagSearchBody(parsed);
|
|
1401
|
+
await runOperation({
|
|
1402
|
+
parsed,
|
|
1403
|
+
operation: "search",
|
|
1404
|
+
body,
|
|
1405
|
+
started,
|
|
1406
|
+
fetchBody: async (client) => parseJson(JSON.stringify(await search({
|
|
1407
|
+
client,
|
|
1408
|
+
body
|
|
1409
|
+
})))
|
|
1410
|
+
});
|
|
1411
|
+
}
|
|
1412
|
+
async function runContents(parsed) {
|
|
1413
|
+
const started = Date.now();
|
|
1414
|
+
const body = parsed.request !== void 0 ? zGetContentsBody.parse(parsed.request) : flagContentsBody(parsed);
|
|
1415
|
+
await runOperation({
|
|
1416
|
+
parsed,
|
|
1417
|
+
operation: "contents",
|
|
1418
|
+
body,
|
|
1419
|
+
started,
|
|
1420
|
+
fetchBody: async (client) => parseJson(JSON.stringify(await getContents({
|
|
1421
|
+
client,
|
|
1422
|
+
body
|
|
1423
|
+
})))
|
|
1424
|
+
});
|
|
1425
|
+
}
|
|
1426
|
+
async function runAnswer(parsed) {
|
|
1427
|
+
const started = Date.now();
|
|
1428
|
+
const body = parsed.request !== void 0 ? zAnswerBody.parse(parsed.request) : flagAnswerBody(parsed);
|
|
1429
|
+
await runOperation({
|
|
1430
|
+
parsed,
|
|
1431
|
+
operation: "answer",
|
|
1432
|
+
body,
|
|
1433
|
+
started,
|
|
1434
|
+
fetchBody: async (client) => parseJson(JSON.stringify(await answer({
|
|
1435
|
+
client,
|
|
1436
|
+
body
|
|
1437
|
+
})))
|
|
1438
|
+
});
|
|
1439
|
+
}
|
|
1440
|
+
async function runOperation(options) {
|
|
1441
|
+
const apiKey = requireApiKey(options.parsed.apiKey);
|
|
1442
|
+
const apiUrl = options.parsed.apiUrl ?? "https://api.exa.ai";
|
|
1443
|
+
const host = new URL(apiUrl).host;
|
|
1444
|
+
const ttlSeconds = options.parsed.ttl ?? 86400;
|
|
1445
|
+
const mode = cacheMode({
|
|
1446
|
+
refresh: options.parsed.refresh,
|
|
1447
|
+
noCache: options.parsed.noCache
|
|
1448
|
+
});
|
|
1449
|
+
const cache = mode === "off" ? void 0 : new CacheStore(defaultCachePath());
|
|
1450
|
+
const client = createExaClient({
|
|
1451
|
+
apiKey,
|
|
1452
|
+
apiUrl
|
|
1453
|
+
});
|
|
1454
|
+
try {
|
|
1455
|
+
const executed = await executeCached({
|
|
1456
|
+
host,
|
|
1457
|
+
operation: options.operation,
|
|
1458
|
+
body: parseJson(JSON.stringify(options.body)),
|
|
1459
|
+
cache,
|
|
1460
|
+
mode,
|
|
1461
|
+
ttlSeconds,
|
|
1462
|
+
fetchBody: () => options.fetchBody(client)
|
|
1463
|
+
});
|
|
1464
|
+
writeOutput(options.parsed, executed.payload, executed.cacheHit, executed.ageMs, options.started);
|
|
1465
|
+
} catch (error) {
|
|
1466
|
+
fail(`${options.operation} failed: ${errorMessageSchema.parse(error)}`);
|
|
1467
|
+
} finally {
|
|
1468
|
+
cache?.close();
|
|
1469
|
+
}
|
|
1470
|
+
}
|
|
1471
|
+
function writeOutput(parsed, payload, cacheHit, ageMs, started) {
|
|
1472
|
+
const stdoutIsTTY = process.stdout.isTTY ?? false;
|
|
1473
|
+
const noColor = parsed.color === false;
|
|
1474
|
+
const forceColor = parsed.color === true;
|
|
1475
|
+
const presenter = {
|
|
1476
|
+
json: parsed.json,
|
|
1477
|
+
pretty: parsed.pretty,
|
|
1478
|
+
output: parsed.output,
|
|
1479
|
+
stdoutIsTTY,
|
|
1480
|
+
noColor,
|
|
1481
|
+
forceColor
|
|
1482
|
+
};
|
|
1483
|
+
const mode = resolveMode(presenter);
|
|
1484
|
+
const color = colorEnabled(presenter);
|
|
1485
|
+
const renderedPayload = parsed.envelope && (mode === "json" || mode === "pretty") ? {
|
|
1486
|
+
data: payload,
|
|
1487
|
+
cache: {
|
|
1488
|
+
hit: cacheHit,
|
|
1489
|
+
ageMs: ageMs ?? null
|
|
1490
|
+
}
|
|
1491
|
+
} : payload;
|
|
1492
|
+
const text = formatPayload(parseJson(JSON.stringify(renderedPayload)), mode, color && mode === "text");
|
|
1493
|
+
if (parsed.output !== void 0) {
|
|
1494
|
+
writeFileSync(parsed.output, text);
|
|
1495
|
+
process.stderr.write(formatWrote(parsed.output));
|
|
1496
|
+
} else process.stdout.write(text);
|
|
1497
|
+
if (cacheHit && ageMs !== void 0 && !parsed.envelope) process.stderr.write(formatCacheHit(ageMs));
|
|
1498
|
+
if (parsed.timing) process.stderr.write(formatTiming(Date.now() - started));
|
|
1499
|
+
}
|
|
1500
|
+
function flagSearchBody(parsed) {
|
|
1501
|
+
if (parsed.query === void 0) fail("search requires a query or --request.");
|
|
1502
|
+
const body = {
|
|
1503
|
+
query: parsed.query,
|
|
1504
|
+
contents: { highlights: true }
|
|
1505
|
+
};
|
|
1506
|
+
if (parsed.numResults !== void 0) body.numResults = parsed.numResults;
|
|
1507
|
+
if (parsed.type !== void 0) body.type = parsed.type;
|
|
1508
|
+
if (parsed.includeDomain.length > 0) body.includeDomains = [...parsed.includeDomain];
|
|
1509
|
+
return body;
|
|
1510
|
+
}
|
|
1511
|
+
function flagContentsBody(parsed) {
|
|
1512
|
+
if (parsed.urls.length === 0) fail("contents requires at least one URL or --request.");
|
|
1513
|
+
const body = {
|
|
1514
|
+
urls: [...parsed.urls],
|
|
1515
|
+
highlights: true
|
|
1516
|
+
};
|
|
1517
|
+
if (parsed.maxAgeHours !== void 0) body.maxAgeHours = parsed.maxAgeHours;
|
|
1518
|
+
return body;
|
|
1519
|
+
}
|
|
1520
|
+
function flagAnswerBody(parsed) {
|
|
1521
|
+
if (parsed.query === void 0) fail("answer requires a query or --request.");
|
|
1522
|
+
return {
|
|
1523
|
+
query: parsed.query,
|
|
1524
|
+
text: parsed.text
|
|
1525
|
+
};
|
|
1526
|
+
}
|
|
1527
|
+
function requireApiKey(apiKey) {
|
|
1528
|
+
if (apiKey === void 0 || apiKey === "") fail("Missing API key. Set EXA_API_KEY or pass --api-key.");
|
|
1529
|
+
return apiKey;
|
|
1530
|
+
}
|
|
1531
|
+
const errorMessageSchema = z.union([
|
|
1532
|
+
z.string().trim(),
|
|
1533
|
+
z.instanceof(Error).transform((error) => error.message),
|
|
1534
|
+
z.json().transform((value) => JSON.stringify(value))
|
|
1535
|
+
]);
|
|
1536
|
+
function fail(messageText) {
|
|
1537
|
+
process.stderr.write(`${messageText}\n`);
|
|
1538
|
+
process.exit(1);
|
|
1539
|
+
}
|
|
1540
|
+
//#endregion
|
|
1541
|
+
//#region src/cli.ts
|
|
1542
|
+
await runApp();
|
|
1543
|
+
//#endregion
|
|
1544
|
+
export {};
|
|
1545
|
+
|
|
1546
|
+
//# sourceMappingURL=cli.mjs.map
|