exa-js 2.5.1-beta.1 → 2.5.1-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -33,16 +33,16 @@ __export(index_exports, {
33
33
  CreateEnrichmentParametersFormat: () => CreateEnrichmentParametersFormat,
34
34
  CreateImportParametersFormat: () => CreateImportParametersFormat,
35
35
  EventType: () => EventType,
36
- EventsClient: () => EventsClient,
36
+ EventsClient: () => EventsClient2,
37
37
  Exa: () => Exa3,
38
38
  ExaError: () => ExaError,
39
- ExaNova: () => Exa2,
39
+ ExaNova: () => Exa,
40
40
  HttpStatusCode: () => HttpStatusCode,
41
41
  ImportFailedReason: () => ImportFailedReason,
42
42
  ImportFormat: () => ImportFormat,
43
43
  ImportObject: () => ImportObject,
44
44
  ImportStatus: () => ImportStatus,
45
- ImportsClient: () => ImportsClient,
45
+ ImportsClient: () => ImportsClient2,
46
46
  MonitorObject: () => MonitorObject,
47
47
  MonitorRunObject: () => MonitorRunObject,
48
48
  MonitorRunStatus: () => MonitorRunStatus,
@@ -52,21 +52,21 @@ __export(index_exports, {
52
52
  WebhookStatus: () => WebhookStatus,
53
53
  WebsetEnrichmentFormat: () => WebsetEnrichmentFormat,
54
54
  WebsetEnrichmentStatus: () => WebsetEnrichmentStatus,
55
- WebsetEnrichmentsClient: () => WebsetEnrichmentsClient,
55
+ WebsetEnrichmentsClient: () => WebsetEnrichmentsClient2,
56
56
  WebsetExcludeSource: () => WebsetExcludeSource,
57
57
  WebsetImportSource: () => WebsetImportSource,
58
58
  WebsetItemEvaluationSatisfied: () => WebsetItemEvaluationSatisfied,
59
59
  WebsetItemSource: () => WebsetItemSource,
60
- WebsetItemsClient: () => WebsetItemsClient,
61
- WebsetMonitorsClient: () => WebsetMonitorsClient,
60
+ WebsetItemsClient: () => WebsetItemsClient2,
61
+ WebsetMonitorsClient: () => WebsetMonitorsClient2,
62
62
  WebsetSearchBehavior: () => WebsetSearchBehavior,
63
63
  WebsetSearchCanceledReason: () => WebsetSearchCanceledReason,
64
64
  WebsetSearchScopeSource: () => WebsetSearchScopeSource,
65
65
  WebsetSearchStatus: () => WebsetSearchStatus,
66
- WebsetSearchesClient: () => WebsetSearchesClient,
66
+ WebsetSearchesClient: () => WebsetSearchesClient2,
67
67
  WebsetStatus: () => WebsetStatus,
68
- WebsetWebhooksClient: () => WebsetWebhooksClient,
69
- WebsetsClient: () => WebsetsClient,
68
+ WebsetWebhooksClient: () => WebsetWebhooksClient2,
69
+ WebsetsClient: () => WebsetsClient2,
70
70
  default: () => index_default
71
71
  });
72
72
  module.exports = __toCommonJS(index_exports);
@@ -75,7 +75,7 @@ var import_cross_fetch = __toESM(require("cross-fetch"));
75
75
  // package.json
76
76
  var package_default = {
77
77
  name: "exa-js",
78
- version: "2.5.1-beta.1",
78
+ version: "2.5.1-beta.2",
79
79
  description: "Exa SDK for Node.js and the browser",
80
80
  publishConfig: {
81
81
  access: "public"
@@ -159,67 +159,14 @@ var package_default = {
159
159
  homepage: "https://github.com/exa-labs/exa-js#readme"
160
160
  };
161
161
 
162
- // src/errors.ts
163
- var HttpStatusCode = /* @__PURE__ */ ((HttpStatusCode2) => {
164
- HttpStatusCode2[HttpStatusCode2["BadRequest"] = 400] = "BadRequest";
165
- HttpStatusCode2[HttpStatusCode2["NotFound"] = 404] = "NotFound";
166
- HttpStatusCode2[HttpStatusCode2["Unauthorized"] = 401] = "Unauthorized";
167
- HttpStatusCode2[HttpStatusCode2["Forbidden"] = 403] = "Forbidden";
168
- HttpStatusCode2[HttpStatusCode2["TooManyRequests"] = 429] = "TooManyRequests";
169
- HttpStatusCode2[HttpStatusCode2["RequestTimeout"] = 408] = "RequestTimeout";
170
- HttpStatusCode2[HttpStatusCode2["InternalServerError"] = 500] = "InternalServerError";
171
- HttpStatusCode2[HttpStatusCode2["ServiceUnavailable"] = 503] = "ServiceUnavailable";
172
- return HttpStatusCode2;
173
- })(HttpStatusCode || {});
174
- var ExaError = class extends Error {
175
- /**
176
- * Create a new ExaError
177
- * @param message Error message
178
- * @param statusCode HTTP status code
179
- * @param timestamp ISO timestamp from API
180
- * @param path Path that caused the error
181
- */
182
- constructor(message, statusCode, timestamp, path) {
183
- super(message);
184
- this.name = "ExaError";
185
- this.statusCode = statusCode;
186
- this.timestamp = timestamp ?? (/* @__PURE__ */ new Date()).toISOString();
187
- this.path = path;
188
- }
189
- };
190
-
191
- // src/zod-utils.ts
192
- var import_zod = require("zod");
193
- var import_zod_to_json_schema = require("zod-to-json-schema");
194
- function isZodSchema(obj) {
195
- return obj instanceof import_zod.ZodType;
196
- }
197
- function zodToJsonSchema(schema) {
198
- return (0, import_zod_to_json_schema.zodToJsonSchema)(schema, {
199
- $refStrategy: "none"
200
- });
201
- }
202
-
203
- // src/research/base.ts
204
- var ResearchBaseClient = class {
162
+ // src/nova/websets-client.ts
163
+ var WebsetsBaseClient = class {
205
164
  constructor(client) {
206
165
  this.client = client;
207
166
  }
208
- async request(endpoint, method = "POST", data, params) {
209
- return this.client.request(
210
- `/research/v1${endpoint}`,
211
- method,
212
- data,
213
- params
214
- );
215
- }
216
- async rawRequest(endpoint, method = "POST", data, params) {
217
- return this.client.rawRequest(
218
- `/research/v1${endpoint}`,
219
- method,
220
- data,
221
- params
222
- );
167
+ /** Make a request to the API, prepending `/websets` to the path. */
168
+ async request(endpoint, method = "POST", data, params, headers) {
169
+ return this.client.request(`/websets${endpoint}`, method, data, params, headers);
223
170
  }
224
171
  buildPaginationParams(pagination) {
225
172
  const params = {};
@@ -229,288 +176,115 @@ var ResearchBaseClient = class {
229
176
  return params;
230
177
  }
231
178
  };
232
-
233
- // src/research/client.ts
234
- var ResearchClient = class extends ResearchBaseClient {
235
- constructor(client) {
236
- super(client);
237
- }
238
- async create(params) {
239
- const { instructions, model, outputSchema } = params;
240
- let schema = outputSchema;
241
- if (schema && isZodSchema(schema)) {
242
- schema = zodToJsonSchema(schema);
243
- }
244
- const payload = {
245
- instructions,
246
- model: model ?? "exa-research-fast"
247
- };
248
- if (schema) {
249
- payload.outputSchema = schema;
250
- }
251
- return this.request("", "POST", payload);
179
+ var WebsetItemsClient = class extends WebsetsBaseClient {
180
+ async get(websetId, id) {
181
+ return this.request(`/v0/websets/${websetId}/items/${id}`, "GET");
252
182
  }
253
- get(researchId, options) {
254
- if (options?.stream) {
255
- const promise = async () => {
256
- const params = { stream: "true" };
257
- if (options.events !== void 0) {
258
- params.events = options.events.toString();
259
- }
260
- const resp = await this.rawRequest(
261
- `/${researchId}`,
262
- "GET",
263
- void 0,
264
- params
265
- );
266
- if (!resp.body) {
267
- throw new Error("No response body for SSE stream");
268
- }
269
- const reader = resp.body.getReader();
270
- const decoder = new TextDecoder();
271
- let buffer = "";
272
- function processPart(part) {
273
- const lines = part.split("\n");
274
- let data = lines.slice(1).join("\n");
275
- if (data.startsWith("data:")) {
276
- data = data.slice(5).trimStart();
277
- }
278
- try {
279
- return JSON.parse(data);
280
- } catch (e) {
281
- return null;
282
- }
283
- }
284
- async function* streamEvents() {
285
- while (true) {
286
- const { done, value } = await reader.read();
287
- if (done) break;
288
- buffer += decoder.decode(value, { stream: true });
289
- let parts = buffer.split("\n\n");
290
- buffer = parts.pop() ?? "";
291
- for (const part of parts) {
292
- const processed = processPart(part);
293
- if (processed) {
294
- yield processed;
295
- }
296
- }
297
- }
298
- if (buffer.trim()) {
299
- const processed = processPart(buffer.trim());
300
- if (processed) {
301
- yield processed;
302
- }
303
- }
304
- }
305
- return streamEvents();
306
- };
307
- return promise();
308
- } else {
309
- const params = { stream: "false" };
310
- if (options?.events !== void 0) {
311
- params.events = options.events.toString();
312
- }
313
- return this.request(
314
- `/${researchId}`,
315
- "GET",
316
- void 0,
317
- params
318
- );
319
- }
183
+ async delete(websetId, id) {
184
+ return this.request(`/v0/websets/${websetId}/items/${id}`, "DELETE");
320
185
  }
321
- async list(options) {
322
- const params = this.buildPaginationParams(options);
323
- return this.request("", "GET", void 0, params);
186
+ async list(websetId, options) {
187
+ const queryParams = { ...this.buildPaginationParams(options), sourceId: options?.sourceId };
188
+ return this.request(`/v0/websets/${websetId}/items`, "GET", void 0, queryParams);
324
189
  }
325
- async pollUntilFinished(researchId, options) {
326
- const pollInterval = options?.pollInterval ?? 1e3;
327
- const timeoutMs = options?.timeoutMs ?? 10 * 60 * 1e3;
328
- const maxConsecutiveFailures = 5;
329
- const startTime = Date.now();
330
- let consecutiveFailures = 0;
190
+ /** Iterate through all items in a Webset, handling pagination automatically. */
191
+ async *listAll(websetId, options) {
192
+ let cursor = void 0;
193
+ const pageOptions = options ? { ...options } : {};
331
194
  while (true) {
332
- try {
333
- const research = await this.get(researchId, {
334
- events: options?.events
335
- });
336
- consecutiveFailures = 0;
337
- if (research.status === "completed" || research.status === "failed" || research.status === "canceled") {
338
- return research;
339
- }
340
- } catch (err) {
341
- consecutiveFailures += 1;
342
- if (consecutiveFailures >= maxConsecutiveFailures) {
343
- throw new Error(
344
- `Polling failed ${maxConsecutiveFailures} times in a row for research ${researchId}: ${err}`
345
- );
346
- }
195
+ const response = await this.list(websetId, { ...pageOptions, cursor });
196
+ for (const item of response.data) {
197
+ yield item;
347
198
  }
348
- if (Date.now() - startTime > timeoutMs) {
349
- throw new Error(
350
- `Polling timeout: Research ${researchId} did not complete within ${timeoutMs}ms`
351
- );
199
+ if (!response.hasMore || !response.nextCursor) {
200
+ break;
352
201
  }
353
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
202
+ cursor = response.nextCursor;
203
+ }
204
+ }
205
+ /** Collect all items from a Webset into an array. */
206
+ async getAll(websetId, options) {
207
+ const items = [];
208
+ for await (const item of this.listAll(websetId, options)) {
209
+ items.push(item);
354
210
  }
211
+ return items;
355
212
  }
356
213
  };
357
-
358
- // src/websets/base.ts
359
- var WebsetsBaseClient = class {
360
- /**
361
- * Initialize a new Websets base client
362
- * @param client The Exa client instance
363
- */
364
- constructor(client) {
365
- this.client = client;
214
+ var WebsetSearchesClient = class extends WebsetsBaseClient {
215
+ async create(websetId, params, options) {
216
+ return this.request(`/v0/websets/${websetId}/searches`, "POST", { ...params }, void 0, options?.headers);
366
217
  }
367
- /**
368
- * Make a request to the Websets API
369
- * @param endpoint The endpoint path
370
- * @param method The HTTP method
371
- * @param data Optional request body data
372
- * @param params Optional query parameters
373
- * @returns The response JSON
374
- * @throws ExaError with API error details if the request fails
375
- */
376
- async request(endpoint, method = "POST", data, params, headers) {
377
- return this.client.request(
378
- `/websets${endpoint}`,
379
- method,
380
- data,
381
- params,
382
- headers
383
- );
218
+ async get(websetId, id) {
219
+ return this.request(`/v0/websets/${websetId}/searches/${id}`, "GET");
384
220
  }
385
- /**
386
- * Helper to build pagination parameters
387
- * @param pagination The pagination parameters
388
- * @returns QueryParams object with pagination parameters
389
- */
390
- buildPaginationParams(pagination) {
391
- const params = {};
392
- if (!pagination) return params;
393
- if (pagination.cursor) params.cursor = pagination.cursor;
394
- if (pagination.limit) params.limit = pagination.limit;
395
- return params;
221
+ async cancel(websetId, id) {
222
+ return this.request(`/v0/websets/${websetId}/searches/${id}/cancel`, "POST");
396
223
  }
397
224
  };
398
-
399
- // src/websets/enrichments.ts
400
225
  var WebsetEnrichmentsClient = class extends WebsetsBaseClient {
401
- /**
402
- * Create an Enrichment for a Webset
403
- * @param websetId The ID of the Webset
404
- * @param params The enrichment parameters
405
- * @returns The created Webset Enrichment
406
- */
407
226
  async create(websetId, params) {
408
- return this.request(
409
- `/v0/websets/${websetId}/enrichments`,
410
- "POST",
411
- params
412
- );
227
+ return this.request(`/v0/websets/${websetId}/enrichments`, "POST", { ...params });
228
+ }
229
+ async update(websetId, id, params) {
230
+ return this.request(`/v0/websets/${websetId}/enrichments/${id}`, "PATCH", { ...params });
413
231
  }
414
- /**
415
- * Get an Enrichment by ID
416
- * @param websetId The ID of the Webset
417
- * @param id The ID of the Enrichment
418
- * @returns The Webset Enrichment
419
- */
420
232
  async get(websetId, id) {
421
- return this.request(
422
- `/v0/websets/${websetId}/enrichments/${id}`,
423
- "GET"
424
- );
233
+ return this.request(`/v0/websets/${websetId}/enrichments/${id}`, "GET");
425
234
  }
426
- /**
427
- * Delete an Enrichment
428
- * @param websetId The ID of the Webset
429
- * @param id The ID of the Enrichment
430
- * @returns The deleted Webset Enrichment
431
- */
432
235
  async delete(websetId, id) {
433
- return this.request(
434
- `/v0/websets/${websetId}/enrichments/${id}`,
435
- "DELETE"
436
- );
437
- }
438
- /**
439
- * Update an Enrichment
440
- * @param websetId The ID of the Webset
441
- * @param id The ID of the Enrichment
442
- * @param params The enrichment update parameters
443
- * @returns Promise that resolves when the update is complete
444
- */
445
- async update(websetId, id, params) {
446
- return this.request(
447
- `/v0/websets/${websetId}/enrichments/${id}`,
448
- "PATCH",
449
- params
450
- );
236
+ return this.request(`/v0/websets/${websetId}/enrichments/${id}`, "DELETE");
451
237
  }
452
- /**
453
- * Cancel a running Enrichment
454
- * @param websetId The ID of the Webset
455
- * @param id The ID of the Enrichment
456
- * @returns The canceled Webset Enrichment
457
- */
458
238
  async cancel(websetId, id) {
459
- return this.request(
460
- `/v0/websets/${websetId}/enrichments/${id}/cancel`,
461
- "POST"
462
- );
239
+ return this.request(`/v0/websets/${websetId}/enrichments/${id}/cancel`, "POST");
463
240
  }
464
241
  };
465
-
466
- // src/websets/events.ts
467
242
  var EventsClient = class extends WebsetsBaseClient {
468
- /**
469
- * Initialize a new Events client
470
- * @param client The Exa client instance
471
- */
243
+ async list(options) {
244
+ const queryParams = { ...this.buildPaginationParams(options), types: options?.types, createdBefore: options?.createdBefore, createdAfter: options?.createdAfter };
245
+ return this.request("/v0/events", "GET", void 0, queryParams);
246
+ }
247
+ async get(id) {
248
+ return this.request(`/v0/events/${id}`, "GET");
249
+ }
250
+ };
251
+ var WebsetMonitorRunsClient = class extends WebsetsBaseClient {
252
+ async list(monitorId) {
253
+ return this.request(`/v0/monitors/${monitorId}/runs`, "GET");
254
+ }
255
+ async get(monitorId, id) {
256
+ return this.request(`/v0/monitors/${monitorId}/runs/${id}`, "GET");
257
+ }
258
+ };
259
+ var WebsetMonitorsClient = class extends WebsetsBaseClient {
472
260
  constructor(client) {
473
261
  super(client);
262
+ this.runs = new WebsetMonitorRunsClient(client);
263
+ }
264
+ async create(params) {
265
+ return this.request("/v0/monitors", "POST", { ...params });
474
266
  }
475
- /**
476
- * List all Events
477
- * @param options Optional filtering and pagination options
478
- * @returns The list of Events
479
- */
480
267
  async list(options) {
481
- const params = {
482
- cursor: options?.cursor,
483
- limit: options?.limit,
484
- types: options?.types
485
- };
486
- return this.request(
487
- "/v0/events",
488
- "GET",
489
- void 0,
490
- params
491
- );
268
+ const queryParams = { ...this.buildPaginationParams(options), websetId: options?.websetId };
269
+ return this.request("/v0/monitors", "GET", void 0, queryParams);
492
270
  }
493
- /**
494
- * Get an Event by ID
495
- * @param id The ID of the Event
496
- * @returns The Event
497
- */
498
271
  async get(id) {
499
- return this.request(`/v0/events/${id}`, "GET");
272
+ return this.request(`/v0/monitors/${id}`, "GET");
500
273
  }
501
- /**
502
- * Iterate through all Events, handling pagination automatically
503
- * @param options Filtering and pagination options
504
- * @returns Async generator of Events
505
- */
274
+ async update(id, params) {
275
+ return this.request(`/v0/monitors/${id}`, "PATCH", { ...params });
276
+ }
277
+ async delete(id) {
278
+ return this.request(`/v0/monitors/${id}`, "DELETE");
279
+ }
280
+ /** Iterate through all monitors, handling pagination automatically. */
506
281
  async *listAll(options) {
507
282
  let cursor = void 0;
508
283
  const pageOptions = options ? { ...options } : {};
509
284
  while (true) {
510
- pageOptions.cursor = cursor;
511
- const response = await this.list(pageOptions);
512
- for (const event of response.data) {
513
- yield event;
285
+ const response = await this.list({ ...pageOptions, cursor });
286
+ for (const monitor of response.data) {
287
+ yield monitor;
514
288
  }
515
289
  if (!response.hasMore || !response.nextCursor) {
516
290
  break;
@@ -518,955 +292,1241 @@ var EventsClient = class extends WebsetsBaseClient {
518
292
  cursor = response.nextCursor;
519
293
  }
520
294
  }
521
- /**
522
- * Collect all Events into an array
523
- * @param options Filtering and pagination options
524
- * @returns Promise resolving to an array of all Events
525
- */
295
+ /** Collect all monitors into an array. */
526
296
  async getAll(options) {
527
- const events = [];
528
- for await (const event of this.listAll(options)) {
529
- events.push(event);
297
+ const monitors = [];
298
+ for await (const monitor of this.listAll(options)) {
299
+ monitors.push(monitor);
300
+ }
301
+ return monitors;
302
+ }
303
+ };
304
+ var WebsetWebhooksClient = class extends WebsetsBaseClient {
305
+ async create(params) {
306
+ return this.request("/v0/webhooks", "POST", { ...params });
307
+ }
308
+ async list(options) {
309
+ const queryParams = this.buildPaginationParams(options);
310
+ return this.request("/v0/webhooks", "GET", void 0, queryParams);
311
+ }
312
+ async get(id) {
313
+ return this.request(`/v0/webhooks/${id}`, "GET");
314
+ }
315
+ async update(id, params) {
316
+ return this.request(`/v0/webhooks/${id}`, "PATCH", { ...params });
317
+ }
318
+ async delete(id) {
319
+ return this.request(`/v0/webhooks/${id}`, "DELETE");
320
+ }
321
+ async listAttempts(id, options) {
322
+ const queryParams = { ...this.buildPaginationParams(options), eventType: options?.eventType, successful: options?.successful };
323
+ return this.request(`/v0/webhooks/${id}/attempts`, "GET", void 0, queryParams);
324
+ }
325
+ };
326
+ var ImportsClient = class extends WebsetsBaseClient {
327
+ async create(params) {
328
+ return this.request("/v0/imports", "POST", { ...params });
329
+ }
330
+ async list(options) {
331
+ const queryParams = this.buildPaginationParams(options);
332
+ return this.request("/v0/imports", "GET", void 0, queryParams);
333
+ }
334
+ async get(id) {
335
+ return this.request(`/v0/imports/${id}`, "GET");
336
+ }
337
+ async update(id, params) {
338
+ return this.request(`/v0/imports/${id}`, "PATCH", { ...params });
339
+ }
340
+ async delete(id) {
341
+ return this.request(`/v0/imports/${id}`, "DELETE");
342
+ }
343
+ };
344
+ var WebsetsClient = class extends WebsetsBaseClient {
345
+ constructor(client) {
346
+ super(client);
347
+ this.items = new WebsetItemsClient(client);
348
+ this.searches = new WebsetSearchesClient(client);
349
+ this.enrichments = new WebsetEnrichmentsClient(client);
350
+ this.events = new EventsClient(client);
351
+ this.monitors = new WebsetMonitorsClient(client);
352
+ this.webhooks = new WebsetWebhooksClient(client);
353
+ this.imports = new ImportsClient(client);
354
+ }
355
+ async create(params, options) {
356
+ return this.request("/v0/websets", "POST", { ...params }, void 0, options?.headers);
357
+ }
358
+ async list(options) {
359
+ const queryParams = { ...this.buildPaginationParams(options), search: options?.search };
360
+ return this.request("/v0/websets", "GET", void 0, queryParams);
361
+ }
362
+ async get(id, options) {
363
+ const queryParams = { expand: options?.expand };
364
+ return this.request(`/v0/websets/${id}`, "GET", void 0, queryParams);
365
+ }
366
+ async update(id, params) {
367
+ return this.request(`/v0/websets/${id}`, "POST", { ...params });
368
+ }
369
+ async delete(id) {
370
+ return this.request(`/v0/websets/${id}`, "DELETE");
371
+ }
372
+ async cancel(id) {
373
+ return this.request(`/v0/websets/${id}/cancel`, "POST");
374
+ }
375
+ async preview(params, options) {
376
+ const queryParams = { search: options?.search };
377
+ return this.request("/v0/websets/preview", "POST", { ...params }, queryParams);
378
+ }
379
+ /** Iterate through all Websets, handling pagination automatically. */
380
+ async *listAll(options) {
381
+ let cursor = void 0;
382
+ const pageOptions = options ? { ...options } : {};
383
+ while (true) {
384
+ const response = await this.list({ ...pageOptions, cursor });
385
+ for (const webset of response.data) {
386
+ yield webset;
387
+ }
388
+ if (!response.hasMore || !response.nextCursor) {
389
+ break;
390
+ }
391
+ cursor = response.nextCursor;
392
+ }
393
+ }
394
+ /** Collect all Websets into an array. */
395
+ async getAll(options) {
396
+ const websets = [];
397
+ for await (const webset of this.listAll(options)) {
398
+ websets.push(webset);
399
+ }
400
+ return websets;
401
+ }
402
+ /** Poll until a Webset reaches idle status. */
403
+ async waitUntilIdle(id, options) {
404
+ let timeout;
405
+ let pollInterval = 1e3;
406
+ let onPoll;
407
+ if (typeof options === "number") {
408
+ timeout = options;
409
+ } else if (options) {
410
+ timeout = options.timeout;
411
+ pollInterval = options.pollInterval || 1e3;
412
+ onPoll = options.onPoll;
413
+ }
414
+ const startTime = Date.now();
415
+ while (true) {
416
+ const webset = await this.get(id);
417
+ if (onPoll) onPoll(webset.status);
418
+ if (webset.status === "idle") return webset;
419
+ if (timeout && Date.now() - startTime > timeout) {
420
+ throw new Error(`Webset ${id} did not reach idle state within ${timeout}ms. Current status: ${webset.status}`);
421
+ }
422
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
530
423
  }
531
- return events;
532
424
  }
533
425
  };
534
426
 
535
- // src/websets/openapi.ts
536
- var CreateEnrichmentParametersFormat = /* @__PURE__ */ ((CreateEnrichmentParametersFormat2) => {
537
- CreateEnrichmentParametersFormat2["text"] = "text";
538
- CreateEnrichmentParametersFormat2["date"] = "date";
539
- CreateEnrichmentParametersFormat2["number"] = "number";
540
- CreateEnrichmentParametersFormat2["options"] = "options";
541
- CreateEnrichmentParametersFormat2["email"] = "email";
542
- CreateEnrichmentParametersFormat2["phone"] = "phone";
543
- CreateEnrichmentParametersFormat2["url"] = "url";
544
- return CreateEnrichmentParametersFormat2;
545
- })(CreateEnrichmentParametersFormat || {});
546
- var CreateImportParametersFormat = /* @__PURE__ */ ((CreateImportParametersFormat2) => {
547
- CreateImportParametersFormat2["csv"] = "csv";
548
- return CreateImportParametersFormat2;
549
- })(CreateImportParametersFormat || {});
550
- var WebsetImportSource = /* @__PURE__ */ ((WebsetImportSource2) => {
551
- WebsetImportSource2["import"] = "import";
552
- WebsetImportSource2["webset"] = "webset";
553
- return WebsetImportSource2;
554
- })(WebsetImportSource || {});
555
- var EventType = /* @__PURE__ */ ((EventType2) => {
556
- EventType2["webset_created"] = "webset.created";
557
- EventType2["webset_deleted"] = "webset.deleted";
558
- EventType2["webset_paused"] = "webset.paused";
559
- EventType2["webset_idle"] = "webset.idle";
560
- EventType2["webset_search_created"] = "webset.search.created";
561
- EventType2["webset_search_canceled"] = "webset.search.canceled";
562
- EventType2["webset_search_completed"] = "webset.search.completed";
563
- EventType2["webset_search_updated"] = "webset.search.updated";
564
- EventType2["import_created"] = "import.created";
565
- EventType2["import_completed"] = "import.completed";
566
- EventType2["webset_item_created"] = "webset.item.created";
567
- EventType2["webset_item_enriched"] = "webset.item.enriched";
568
- EventType2["monitor_created"] = "monitor.created";
569
- EventType2["monitor_updated"] = "monitor.updated";
570
- EventType2["monitor_deleted"] = "monitor.deleted";
571
- EventType2["monitor_run_created"] = "monitor.run.created";
572
- EventType2["monitor_run_completed"] = "monitor.run.completed";
573
- EventType2["webset_export_created"] = "webset.export.created";
574
- EventType2["webset_export_completed"] = "webset.export.completed";
575
- return EventType2;
576
- })(EventType || {});
577
- var ImportFailedReason = /* @__PURE__ */ ((ImportFailedReason2) => {
578
- ImportFailedReason2["invalid_format"] = "invalid_format";
579
- ImportFailedReason2["invalid_file_content"] = "invalid_file_content";
580
- ImportFailedReason2["missing_identifier"] = "missing_identifier";
581
- return ImportFailedReason2;
582
- })(ImportFailedReason || {});
583
- var ImportFormat = /* @__PURE__ */ ((ImportFormat2) => {
584
- ImportFormat2["csv"] = "csv";
585
- ImportFormat2["webset"] = "webset";
586
- return ImportFormat2;
587
- })(ImportFormat || {});
588
- var ImportObject = /* @__PURE__ */ ((ImportObject2) => {
589
- ImportObject2["import"] = "import";
590
- return ImportObject2;
591
- })(ImportObject || {});
592
- var ImportStatus = /* @__PURE__ */ ((ImportStatus2) => {
593
- ImportStatus2["pending"] = "pending";
594
- ImportStatus2["processing"] = "processing";
595
- ImportStatus2["completed"] = "completed";
596
- ImportStatus2["failed"] = "failed";
597
- return ImportStatus2;
598
- })(ImportStatus || {});
599
- var MonitorObject = /* @__PURE__ */ ((MonitorObject2) => {
600
- MonitorObject2["monitor"] = "monitor";
601
- return MonitorObject2;
602
- })(MonitorObject || {});
603
- var MonitorStatus = /* @__PURE__ */ ((MonitorStatus2) => {
604
- MonitorStatus2["enabled"] = "enabled";
605
- MonitorStatus2["disabled"] = "disabled";
606
- return MonitorStatus2;
607
- })(MonitorStatus || {});
608
- var MonitorRunObject = /* @__PURE__ */ ((MonitorRunObject2) => {
609
- MonitorRunObject2["monitor_run"] = "monitor_run";
610
- return MonitorRunObject2;
611
- })(MonitorRunObject || {});
612
- var MonitorRunStatus = /* @__PURE__ */ ((MonitorRunStatus2) => {
613
- MonitorRunStatus2["created"] = "created";
614
- MonitorRunStatus2["running"] = "running";
615
- MonitorRunStatus2["completed"] = "completed";
616
- MonitorRunStatus2["canceled"] = "canceled";
617
- MonitorRunStatus2["failed"] = "failed";
618
- return MonitorRunStatus2;
619
- })(MonitorRunStatus || {});
620
- var MonitorRunType = /* @__PURE__ */ ((MonitorRunType2) => {
621
- MonitorRunType2["search"] = "search";
622
- MonitorRunType2["refresh"] = "refresh";
623
- return MonitorRunType2;
624
- })(MonitorRunType || {});
625
- var UpdateMonitorStatus = /* @__PURE__ */ ((UpdateMonitorStatus2) => {
626
- UpdateMonitorStatus2["enabled"] = "enabled";
627
- UpdateMonitorStatus2["disabled"] = "disabled";
628
- return UpdateMonitorStatus2;
629
- })(UpdateMonitorStatus || {});
630
- var WebhookStatus = /* @__PURE__ */ ((WebhookStatus2) => {
631
- WebhookStatus2["active"] = "active";
632
- WebhookStatus2["inactive"] = "inactive";
633
- return WebhookStatus2;
634
- })(WebhookStatus || {});
635
- var WebsetStatus = /* @__PURE__ */ ((WebsetStatus2) => {
636
- WebsetStatus2["idle"] = "idle";
637
- WebsetStatus2["pending"] = "pending";
638
- WebsetStatus2["running"] = "running";
639
- WebsetStatus2["paused"] = "paused";
640
- return WebsetStatus2;
641
- })(WebsetStatus || {});
642
- var WebsetEnrichmentStatus = /* @__PURE__ */ ((WebsetEnrichmentStatus2) => {
643
- WebsetEnrichmentStatus2["pending"] = "pending";
644
- WebsetEnrichmentStatus2["canceled"] = "canceled";
645
- WebsetEnrichmentStatus2["completed"] = "completed";
646
- return WebsetEnrichmentStatus2;
647
- })(WebsetEnrichmentStatus || {});
648
- var WebsetEnrichmentFormat = /* @__PURE__ */ ((WebsetEnrichmentFormat2) => {
649
- WebsetEnrichmentFormat2["text"] = "text";
650
- WebsetEnrichmentFormat2["date"] = "date";
651
- WebsetEnrichmentFormat2["number"] = "number";
652
- WebsetEnrichmentFormat2["options"] = "options";
653
- WebsetEnrichmentFormat2["email"] = "email";
654
- WebsetEnrichmentFormat2["phone"] = "phone";
655
- WebsetEnrichmentFormat2["url"] = "url";
656
- return WebsetEnrichmentFormat2;
657
- })(WebsetEnrichmentFormat || {});
658
- var WebsetItemSource = /* @__PURE__ */ ((WebsetItemSource2) => {
659
- WebsetItemSource2["search"] = "search";
660
- WebsetItemSource2["import"] = "import";
661
- return WebsetItemSource2;
662
- })(WebsetItemSource || {});
663
- var WebsetItemEvaluationSatisfied = /* @__PURE__ */ ((WebsetItemEvaluationSatisfied2) => {
664
- WebsetItemEvaluationSatisfied2["yes"] = "yes";
665
- WebsetItemEvaluationSatisfied2["no"] = "no";
666
- WebsetItemEvaluationSatisfied2["unclear"] = "unclear";
667
- return WebsetItemEvaluationSatisfied2;
668
- })(WebsetItemEvaluationSatisfied || {});
669
- var WebsetExcludeSource = /* @__PURE__ */ ((WebsetExcludeSource2) => {
670
- WebsetExcludeSource2["import"] = "import";
671
- WebsetExcludeSource2["webset"] = "webset";
672
- return WebsetExcludeSource2;
673
- })(WebsetExcludeSource || {});
674
- var WebsetSearchScopeSource = /* @__PURE__ */ ((WebsetSearchScopeSource2) => {
675
- WebsetSearchScopeSource2["import"] = "import";
676
- WebsetSearchScopeSource2["webset"] = "webset";
677
- return WebsetSearchScopeSource2;
678
- })(WebsetSearchScopeSource || {});
679
- var WebsetSearchStatus = /* @__PURE__ */ ((WebsetSearchStatus2) => {
680
- WebsetSearchStatus2["created"] = "created";
681
- WebsetSearchStatus2["pending"] = "pending";
682
- WebsetSearchStatus2["running"] = "running";
683
- WebsetSearchStatus2["completed"] = "completed";
684
- WebsetSearchStatus2["canceled"] = "canceled";
685
- return WebsetSearchStatus2;
686
- })(WebsetSearchStatus || {});
687
- var WebsetSearchBehavior = /* @__PURE__ */ ((WebsetSearchBehavior2) => {
688
- WebsetSearchBehavior2["override"] = "override";
689
- WebsetSearchBehavior2["append"] = "append";
690
- return WebsetSearchBehavior2;
691
- })(WebsetSearchBehavior || {});
692
- var WebsetSearchCanceledReason = /* @__PURE__ */ ((WebsetSearchCanceledReason2) => {
693
- WebsetSearchCanceledReason2["webset_deleted"] = "webset_deleted";
694
- WebsetSearchCanceledReason2["webset_canceled"] = "webset_canceled";
695
- return WebsetSearchCanceledReason2;
696
- })(WebsetSearchCanceledReason || {});
427
+ // src/nova/research-client.ts
428
+ var import_zod = require("zod");
429
+ var import_zod_to_json_schema = require("zod-to-json-schema");
430
+ function zodToJsonSchema(schema) {
431
+ return (0, import_zod_to_json_schema.zodToJsonSchema)(schema, { $refStrategy: "none" });
432
+ }
433
+ var ResearchBaseClient = class {
434
+ constructor(client) {
435
+ this.client = client;
436
+ }
437
+ /** Make a request to the API, prepending `/research/v1` to the path. */
438
+ async request(endpoint, method = "POST", data, params) {
439
+ return this.client.request(`/research/v1${endpoint}`, method, data, params);
440
+ }
441
+ buildPaginationParams(pagination) {
442
+ const params = {};
443
+ if (!pagination) return params;
444
+ if (pagination.cursor) params.cursor = pagination.cursor;
445
+ if (pagination.limit) params.limit = pagination.limit;
446
+ return params;
447
+ }
448
+ };
449
+ var ResearchClient = class extends ResearchBaseClient {
450
+ /** List research requests. */
451
+ async list(options) {
452
+ const params = this.buildPaginationParams(options);
453
+ return this.client.request("/research/v1", "GET", void 0, params);
454
+ }
455
+ /** Create a new research request. Defaults model to "exa-research-fast" if not provided. */
456
+ async create(params) {
457
+ let schema = params.outputSchema;
458
+ if (schema instanceof import_zod.ZodType) {
459
+ schema = zodToJsonSchema(schema);
460
+ }
461
+ const payload = {
462
+ instructions: params.instructions,
463
+ model: params.model ?? "exa-research-fast"
464
+ };
465
+ if (schema) {
466
+ payload.outputSchema = schema;
467
+ }
468
+ return this.client.request("/research/v1", "POST", payload, void 0);
469
+ }
470
+ /** Get a research request by ID. */
471
+ async get(researchId, options) {
472
+ const params = {};
473
+ if (options?.events !== void 0) params.events = options.events.toString();
474
+ return this.client.request(`/research/v1/${researchId}`, "GET", void 0, params);
475
+ }
476
+ /** Poll a research request until it reaches a terminal state (completed, failed, or canceled). */
477
+ async pollUntilFinished(researchId, options) {
478
+ const pollInterval = options?.pollInterval ?? 1e3;
479
+ const timeoutMs = options?.timeoutMs ?? 10 * 60 * 1e3;
480
+ const maxConsecutiveFailures = 5;
481
+ const startTime = Date.now();
482
+ let consecutiveFailures = 0;
483
+ while (true) {
484
+ try {
485
+ const research = await this.get(researchId, { events: options?.events });
486
+ consecutiveFailures = 0;
487
+ if (research.status === "completed" || research.status === "failed" || research.status === "canceled") {
488
+ return research;
489
+ }
490
+ } catch (err) {
491
+ consecutiveFailures += 1;
492
+ if (consecutiveFailures >= maxConsecutiveFailures) {
493
+ throw new Error(`Polling failed ${maxConsecutiveFailures} times in a row for research ${researchId}: ${err}`);
494
+ }
495
+ }
496
+ if (Date.now() - startTime > timeoutMs) {
497
+ throw new Error(`Polling timeout: Research ${researchId} did not complete within ${timeoutMs}ms`);
498
+ }
499
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
500
+ }
501
+ }
502
+ };
697
503
 
698
- // src/websets/imports.ts
699
- var ImportsClient = class extends WebsetsBaseClient {
700
- async create(params, csv) {
701
- if (csv === void 0) {
702
- return this.request(
703
- "/v0/imports",
704
- "POST",
705
- params
706
- );
504
+ // src/nova/client.ts
505
+ function isRecord(value) {
506
+ return value != null && typeof value === "object" && !Array.isArray(value);
507
+ }
508
+ var ExaError = class extends Error {
509
+ constructor(message, statusCode, timestamp, path, details) {
510
+ super(message);
511
+ this.name = "ExaError";
512
+ this.statusCode = statusCode;
513
+ this.timestamp = timestamp ?? (/* @__PURE__ */ new Date()).toISOString();
514
+ this.path = path;
515
+ this.details = details;
516
+ }
517
+ };
518
+ var CONTENTS_FIELDS = /* @__PURE__ */ new Set(["text", "highlights", "summary", "subpages", "subpageTarget", "extras", "livecrawl", "livecrawlTimeout", "maxAgeHours", "filterEmptyResults", "context"]);
519
+ var DEFAULT_MAX_CHARACTERS = 1e4;
520
+ var Exa = class {
521
+ constructor(apiKey, baseURL = "https://api.exa.ai") {
522
+ this.baseURL = baseURL;
523
+ if (!apiKey) {
524
+ apiKey = typeof process !== "undefined" ? process.env?.EXA_API_KEY : void 0;
525
+ if (!apiKey) {
526
+ throw new ExaError(
527
+ "API key must be provided as an argument or as an environment variable (EXA_API_KEY)",
528
+ 401
529
+ );
530
+ }
707
531
  }
708
- let csvBuffer;
709
- if (typeof csv === "string") {
710
- csvBuffer = Buffer.from(csv, "utf8");
711
- } else if (Buffer.isBuffer(csv)) {
712
- csvBuffer = csv;
532
+ this.headers = {
533
+ "x-api-key": apiKey,
534
+ "Content-Type": "application/json"
535
+ };
536
+ this.websets = new WebsetsClient(this);
537
+ this.research = new ResearchClient(this);
538
+ }
539
+ /** Make a request to the Exa API. Used by sub-clients and available for direct use. */
540
+ async request(endpoint, method, body, params, headers) {
541
+ const url = this.buildRequestUrl(endpoint, params);
542
+ const normalizedBody = this.normalizeCategoryInBody(body);
543
+ const combinedHeaders = headers ? { ...this.headers, ...headers } : this.headers;
544
+ const response = await fetch(url, {
545
+ method,
546
+ headers: combinedHeaders,
547
+ body: normalizedBody ? JSON.stringify(normalizedBody) : void 0
548
+ });
549
+ if (!response.ok) {
550
+ throw await this.toExaError(response, endpoint);
551
+ }
552
+ return await response.json();
553
+ }
554
+ /** Make a raw request returning the Response object directly. */
555
+ async rawRequest(endpoint, method = "POST", body, params) {
556
+ const url = this.buildRequestUrl(endpoint, params);
557
+ const normalizedBody = this.normalizeCategoryInBody(body);
558
+ return fetch(url, {
559
+ method,
560
+ headers: this.headers,
561
+ body: normalizedBody ? JSON.stringify(normalizedBody) : void 0
562
+ });
563
+ }
564
+ /** Normalize category values to underscore form. */
565
+ normalizeCategoryInBody(body) {
566
+ if (body == null || typeof body.category !== "string") {
567
+ return body;
568
+ }
569
+ return { ...body, category: body.category.replace(/ /g, "_") };
570
+ }
571
+ buildRequestUrl(endpoint, params) {
572
+ let url = `${this.baseURL}${endpoint}`;
573
+ if (params == null || Object.keys(params).length === 0) {
574
+ return url;
575
+ }
576
+ const searchParams = new URLSearchParams();
577
+ for (const [key, value] of Object.entries(params)) {
578
+ if (Array.isArray(value)) {
579
+ for (const item of value) {
580
+ searchParams.append(key, item);
581
+ }
582
+ } else if (value !== void 0) {
583
+ searchParams.append(key, String(value));
584
+ }
585
+ }
586
+ url += `?${searchParams.toString()}`;
587
+ return url;
588
+ }
589
+ tryParseJsonRecord(text) {
590
+ if (text.length === 0) {
591
+ return null;
592
+ }
593
+ try {
594
+ const parsed = JSON.parse(text);
595
+ return isRecord(parsed) ? parsed : null;
596
+ } catch {
597
+ return null;
598
+ }
599
+ }
600
+ async toExaError(response, endpoint) {
601
+ const text = await response.text();
602
+ const parsed = this.tryParseJsonRecord(text);
603
+ const statusCode = parsed != null && typeof parsed.statusCode === "number" ? parsed.statusCode : response.status;
604
+ const timestamp = parsed != null && typeof parsed.timestamp === "string" ? parsed.timestamp : void 0;
605
+ const path = parsed != null && typeof parsed.path === "string" ? parsed.path : endpoint;
606
+ const errorMessage = parsed != null && typeof parsed.error === "string" ? parsed.error : void 0;
607
+ const detailMessage = parsed != null && typeof parsed.message === "string" ? parsed.message : void 0;
608
+ let message;
609
+ if (errorMessage != null && detailMessage != null) {
610
+ message = `${errorMessage}. ${detailMessage}`;
611
+ } else if (errorMessage != null) {
612
+ message = errorMessage;
613
+ } else if (detailMessage != null) {
614
+ message = detailMessage;
615
+ } else if (text.length > 0) {
616
+ message = text;
713
617
  } else {
714
- throw new ExaError(
715
- "Invalid CSV data input. Must be string or Buffer",
716
- 400 /* BadRequest */
717
- );
618
+ message = `Exa API error ${response.status}`;
718
619
  }
719
- const sizeInBytes = csvBuffer.length;
720
- const sizeInMB = Math.max(1, Math.ceil(sizeInBytes / (1024 * 1024)));
721
- const csvText = csvBuffer.toString("utf8");
722
- const lines = csvText.split("\n").filter((line) => line.trim().length > 0);
723
- const recordCount = Math.max(0, lines.length - 1);
724
- if (sizeInMB > 50) {
725
- throw new ExaError(
726
- `CSV file too large: ${sizeInMB}MB. Maximum size is 50MB.`,
727
- 400 /* BadRequest */
728
- );
620
+ return new ExaError(message, statusCode, timestamp, path, parsed ?? text);
621
+ }
622
+ parseAnswerStreamLine(line) {
623
+ if (!line.startsWith("data:")) {
624
+ return null;
729
625
  }
730
- if (recordCount === 0) {
731
- throw new ExaError(
732
- "CSV file appears to have no data records (only header or empty)",
733
- 400 /* BadRequest */
734
- );
626
+ const jsonStr = line.replace(/^data:\s*/, "").trim();
627
+ if (jsonStr.length === 0 || jsonStr === "[DONE]") {
628
+ return null;
735
629
  }
736
- const createParams = {
737
- title: params.title,
738
- format: "csv" /* csv */,
739
- entity: params.entity,
740
- size: sizeInBytes,
741
- count: recordCount,
742
- metadata: params.metadata,
743
- csv: params.csv
744
- };
745
- const importResponse = await this.request(
746
- "/v0/imports",
747
- "POST",
748
- createParams
749
- );
630
+ let parsedChunk;
750
631
  try {
751
- const uploadResponse = await fetch(importResponse.uploadUrl, {
752
- method: "PUT",
753
- body: csvBuffer
754
- });
755
- if (!uploadResponse.ok) {
756
- const errorText = await uploadResponse.text();
757
- throw new ExaError(
758
- `Upload failed: ${uploadResponse.status} ${uploadResponse.statusText}. ${errorText}`,
759
- 400 /* BadRequest */
760
- );
632
+ parsedChunk = JSON.parse(jsonStr);
633
+ } catch {
634
+ return null;
635
+ }
636
+ if (!isRecord(parsedChunk)) {
637
+ return null;
638
+ }
639
+ let content;
640
+ const choices = parsedChunk.choices;
641
+ if (Array.isArray(choices) && choices.length > 0 && isRecord(choices[0])) {
642
+ const delta = choices[0].delta;
643
+ if (isRecord(delta) && typeof delta.content === "string") {
644
+ content = delta.content;
761
645
  }
762
- } catch (error) {
763
- if (error instanceof ExaError) {
764
- throw error;
646
+ }
647
+ let citations;
648
+ if (Array.isArray(parsedChunk.citations)) {
649
+ const normalized = [];
650
+ for (const citation of parsedChunk.citations) {
651
+ if (!isRecord(citation)) {
652
+ continue;
653
+ }
654
+ const id = typeof citation.id === "string" ? citation.id : void 0;
655
+ const url = typeof citation.url === "string" ? citation.url : void 0;
656
+ const title = typeof citation.title === "string" ? citation.title : void 0;
657
+ const publishedDate = typeof citation.publishedDate === "string" ? citation.publishedDate : void 0;
658
+ const author = typeof citation.author === "string" ? citation.author : void 0;
659
+ const text = typeof citation.text === "string" ? citation.text : void 0;
660
+ normalized.push({
661
+ ...id != null ? { id } : {},
662
+ ...url != null ? { url } : {},
663
+ ...title != null ? { title } : {},
664
+ ...publishedDate != null ? { publishedDate } : {},
665
+ ...author != null ? { author } : {},
666
+ ...text != null ? { text } : {}
667
+ });
668
+ }
669
+ if (normalized.length > 0) {
670
+ citations = normalized;
765
671
  }
766
- throw new ExaError(
767
- `Failed to upload CSV data: ${error.message}`,
768
- 400 /* BadRequest */
769
- );
770
672
  }
771
- return importResponse;
673
+ if (content == null && (citations == null || citations.length === 0)) {
674
+ return null;
675
+ }
676
+ return {
677
+ ...content != null ? { content } : {},
678
+ ...citations != null ? { citations } : {}
679
+ };
772
680
  }
773
- /**
774
- * Get an Import by ID
775
- * @param id The ID of the Import
776
- * @returns The Import
777
- */
778
- async get(id) {
779
- return this.request(`/v0/imports/${id}`, "GET");
681
+ /** Separate content-specific options from search/filter options. */
682
+ extractContentsOptions(options) {
683
+ const contentsOptions = {};
684
+ const restOptions = {};
685
+ let hasContentField = false;
686
+ for (const [key, value] of Object.entries(options)) {
687
+ if (CONTENTS_FIELDS.has(key)) {
688
+ contentsOptions[key] = value;
689
+ hasContentField = true;
690
+ } else {
691
+ restOptions[key] = value;
692
+ }
693
+ }
694
+ if (!hasContentField) {
695
+ contentsOptions.text = { maxCharacters: DEFAULT_MAX_CHARACTERS };
696
+ }
697
+ return { contentsOptions, restOptions };
780
698
  }
781
- /**
782
- * List all Imports
783
- * @param options Pagination options
784
- * @returns The list of Imports
785
- */
786
- async list(options) {
787
- const params = this.buildPaginationParams(options);
788
- return this.request(
789
- "/v0/imports",
790
- "GET",
791
- void 0,
792
- params
793
- );
699
+ search(query, options) {
700
+ let body;
701
+ if (options === void 0 || !("contents" in options)) {
702
+ body = { query, ...options, contents: { text: { maxCharacters: DEFAULT_MAX_CHARACTERS } } };
703
+ } else if (options.contents === false || options.contents === null || options.contents === void 0) {
704
+ const { contents, ...restOptions } = options;
705
+ body = { query, ...restOptions };
706
+ } else {
707
+ body = { query, ...options };
708
+ }
709
+ return this.request("/search", "POST", body);
794
710
  }
795
- /**
796
- * Update an Import
797
- * @param id The ID of the Import
798
- * @param params The import update parameters
799
- * @returns The updated Import
800
- */
801
- async update(id, params) {
802
- return this.request(`/v0/imports/${id}`, "PATCH", params);
711
+ findSimilar(url, options) {
712
+ let body;
713
+ if (options === void 0 || !("contents" in options)) {
714
+ body = { url, ...options, contents: { text: { maxCharacters: DEFAULT_MAX_CHARACTERS } } };
715
+ } else if (options.contents === false || options.contents === null || options.contents === void 0) {
716
+ const { contents, ...restOptions } = options;
717
+ body = { url, ...restOptions };
718
+ } else {
719
+ body = { url, ...options };
720
+ }
721
+ return this.request("/findSimilar", "POST", body);
803
722
  }
804
- /**
805
- * Delete an Import
806
- * @param id The ID of the Import
807
- * @returns The deleted Import
808
- */
809
- async delete(id) {
810
- return this.request(`/v0/imports/${id}`, "DELETE");
723
+ getContents(urls, options) {
724
+ return this.request("/contents", "POST", { urls, ...options });
811
725
  }
812
- /**
813
- * Wait until an Import is completed or failed
814
- * @param id The ID of the Import
815
- * @param options Configuration options for timeout and polling
816
- * @returns The Import once it reaches a final state (completed or failed)
817
- * @throws Error if the Import does not complete within the timeout or fails
818
- */
819
- async waitUntilCompleted(id, options) {
820
- const timeout = options?.timeout ?? 30 * 60 * 1e3;
821
- const pollInterval = options?.pollInterval ?? 2e3;
822
- const onPoll = options?.onPoll;
823
- const startTime = Date.now();
824
- while (true) {
825
- const importItem = await this.get(id);
826
- if (onPoll) {
827
- onPoll(importItem.status);
828
- }
829
- if (importItem.status === "completed" /* completed */) {
830
- return importItem;
831
- }
832
- if (importItem.status === "failed" /* failed */) {
833
- throw new ExaError(
834
- `Import ${id} failed: ${importItem.failedMessage || "Unknown error"}`,
835
- 400 /* BadRequest */
836
- );
837
- }
838
- if (Date.now() - startTime > timeout) {
839
- throw new ExaError(
840
- `Import ${id} did not complete within ${timeout}ms. Current status: ${importItem.status}`,
841
- 408 /* RequestTimeout */
842
- );
843
- }
844
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
726
+ answer(query, options) {
727
+ if (options?.stream) {
728
+ throw new ExaError("For streaming responses, please use streamAnswer() instead:\n\nfor await (const chunk of exa.streamAnswer(query)) {\n // Handle chunks\n}", 400);
845
729
  }
730
+ return this.request("/answer", "POST", { query, model: "exa", stream: false, text: false, ...options });
846
731
  }
847
- /**
848
- * Iterate through all Imports, handling pagination automatically
849
- * @param options Pagination options
850
- * @returns Async generator of Imports
851
- */
852
- async *listAll(options) {
853
- let cursor = void 0;
854
- const pageOptions = options ? { ...options } : {};
855
- while (true) {
856
- pageOptions.cursor = cursor;
857
- const response = await this.list(pageOptions);
858
- for (const importItem of response.data) {
859
- yield importItem;
732
+ async *streamAnswer(query, options) {
733
+ const response = await this.rawRequest("/answer", "POST", { query, model: "exa", text: false, ...options, stream: true });
734
+ if (!response.ok) {
735
+ throw await this.toExaError(response, "/answer");
736
+ }
737
+ const reader = response.body?.getReader();
738
+ if (!reader) {
739
+ throw new ExaError("No response body available for streaming.", 500, (/* @__PURE__ */ new Date()).toISOString(), "/answer");
740
+ }
741
+ const decoder = new TextDecoder();
742
+ let buffer = "";
743
+ try {
744
+ while (true) {
745
+ const { done, value } = await reader.read();
746
+ if (done) break;
747
+ buffer += decoder.decode(value, { stream: true });
748
+ const lines = buffer.split("\n");
749
+ buffer = lines.pop() ?? "";
750
+ for (const line of lines) {
751
+ const chunk = this.parseAnswerStreamLine(line);
752
+ if (chunk != null) {
753
+ yield chunk;
754
+ }
755
+ }
860
756
  }
861
- if (!response.hasMore || !response.nextCursor) {
862
- break;
757
+ const trailingChunk = this.parseAnswerStreamLine(buffer);
758
+ if (trailingChunk != null) {
759
+ yield trailingChunk;
863
760
  }
864
- cursor = response.nextCursor;
761
+ } finally {
762
+ reader.releaseLock();
865
763
  }
866
764
  }
867
765
  /**
868
- * Collect all Imports into an array
869
- * @param options Pagination options
870
- * @returns Promise resolving to an array of all Imports
766
+ * @deprecated Use `search()` instead. The search method now returns text contents by default.
767
+ * Search with contents. Extracts content fields (text, highlights, summary, etc.) into a `contents` wrapper.
871
768
  */
872
- async getAll(options) {
873
- const imports = [];
874
- for await (const importItem of this.listAll(options)) {
875
- imports.push(importItem);
769
+ async searchAndContents(query, options) {
770
+ if (options === void 0) {
771
+ return this.request("/search", "POST", {
772
+ query,
773
+ contents: { text: { maxCharacters: DEFAULT_MAX_CHARACTERS } }
774
+ });
876
775
  }
877
- return imports;
776
+ const { contentsOptions, restOptions } = this.extractContentsOptions(options);
777
+ return this.request("/search", "POST", { query, contents: contentsOptions, ...restOptions });
878
778
  }
879
- };
880
-
881
- // src/websets/items.ts
882
- var WebsetItemsClient = class extends WebsetsBaseClient {
883
779
  /**
884
- * List all Items for a Webset
885
- * @param websetId The ID of the Webset
886
- * @param params - Optional pagination and filtering parameters
887
- * @returns A promise that resolves with the list of Items
780
+ * @deprecated Use `findSimilar()` instead. The findSimilar method now returns text contents by default.
781
+ * Find similar with contents. Extracts content fields into a `contents` wrapper.
888
782
  */
889
- list(websetId, params) {
890
- const queryParams = {
891
- ...this.buildPaginationParams(params),
892
- sourceId: params?.sourceId
893
- };
894
- return this.request(
895
- `/v0/websets/${websetId}/items`,
896
- "GET",
897
- void 0,
898
- queryParams
783
+ async findSimilarAndContents(url, options) {
784
+ if (options === void 0) {
785
+ return this.request("/findSimilar", "POST", {
786
+ url,
787
+ contents: { text: { maxCharacters: DEFAULT_MAX_CHARACTERS } }
788
+ });
789
+ }
790
+ const { contentsOptions, restOptions } = this.extractContentsOptions(options);
791
+ return this.request("/findSimilar", "POST", { url, contents: contentsOptions, ...restOptions });
792
+ }
793
+ };
794
+
795
+ // src/errors.ts
796
+ var HttpStatusCode = /* @__PURE__ */ ((HttpStatusCode2) => {
797
+ HttpStatusCode2[HttpStatusCode2["BadRequest"] = 400] = "BadRequest";
798
+ HttpStatusCode2[HttpStatusCode2["NotFound"] = 404] = "NotFound";
799
+ HttpStatusCode2[HttpStatusCode2["Unauthorized"] = 401] = "Unauthorized";
800
+ HttpStatusCode2[HttpStatusCode2["Forbidden"] = 403] = "Forbidden";
801
+ HttpStatusCode2[HttpStatusCode2["TooManyRequests"] = 429] = "TooManyRequests";
802
+ HttpStatusCode2[HttpStatusCode2["RequestTimeout"] = 408] = "RequestTimeout";
803
+ HttpStatusCode2[HttpStatusCode2["InternalServerError"] = 500] = "InternalServerError";
804
+ HttpStatusCode2[HttpStatusCode2["ServiceUnavailable"] = 503] = "ServiceUnavailable";
805
+ return HttpStatusCode2;
806
+ })(HttpStatusCode || {});
807
+
808
+ // src/zod-utils.ts
809
+ var import_zod2 = require("zod");
810
+ var import_zod_to_json_schema2 = require("zod-to-json-schema");
811
+ function isZodSchema(obj) {
812
+ return obj instanceof import_zod2.ZodType;
813
+ }
814
+ function zodToJsonSchema2(schema) {
815
+ return (0, import_zod_to_json_schema2.zodToJsonSchema)(schema, {
816
+ $refStrategy: "none"
817
+ });
818
+ }
819
+
820
+ // src/research/base.ts
821
+ var ResearchBaseClient2 = class {
822
+ constructor(client) {
823
+ this.client = client;
824
+ }
825
+ async request(endpoint, method = "POST", data, params) {
826
+ return this.client.request(
827
+ `/research/v1${endpoint}`,
828
+ method,
829
+ data,
830
+ params
899
831
  );
900
832
  }
901
- /**
902
- * Iterate through all Items in a Webset, handling pagination automatically
903
- * @param websetId The ID of the Webset
904
- * @param options Pagination options
905
- * @returns Async generator of Webset Items
906
- */
907
- async *listAll(websetId, options) {
908
- let cursor = void 0;
909
- const pageOptions = options ? { ...options } : {};
910
- while (true) {
911
- pageOptions.cursor = cursor;
912
- const response = await this.list(websetId, pageOptions);
913
- for (const item of response.data) {
914
- yield item;
915
- }
916
- if (!response.hasMore || !response.nextCursor) {
917
- break;
918
- }
919
- cursor = response.nextCursor;
833
+ async rawRequest(endpoint, method = "POST", data, params) {
834
+ return this.client.rawRequest(
835
+ `/research/v1${endpoint}`,
836
+ method,
837
+ data,
838
+ params
839
+ );
840
+ }
841
+ buildPaginationParams(pagination) {
842
+ const params = {};
843
+ if (!pagination) return params;
844
+ if (pagination.cursor) params.cursor = pagination.cursor;
845
+ if (pagination.limit) params.limit = pagination.limit;
846
+ return params;
847
+ }
848
+ };
849
+
850
+ // src/research/client.ts
851
+ var ResearchClient2 = class extends ResearchBaseClient2 {
852
+ constructor(client) {
853
+ super(client);
854
+ }
855
+ async create(params) {
856
+ const { instructions, model, outputSchema } = params;
857
+ let schema = outputSchema;
858
+ if (schema && isZodSchema(schema)) {
859
+ schema = zodToJsonSchema2(schema);
860
+ }
861
+ const payload = {
862
+ instructions,
863
+ model: model ?? "exa-research-fast"
864
+ };
865
+ if (schema) {
866
+ payload.outputSchema = schema;
920
867
  }
868
+ return this.request("", "POST", payload);
921
869
  }
922
- /**
923
- * Collect all items from a Webset into an array
924
- * @param websetId The ID of the Webset
925
- * @param options Pagination options
926
- * @returns Promise resolving to an array of all Webset Items
927
- */
928
- async getAll(websetId, options) {
929
- const items = [];
930
- for await (const item of this.listAll(websetId, options)) {
931
- items.push(item);
870
+ get(researchId, options) {
871
+ if (options?.stream) {
872
+ const promise = async () => {
873
+ const params = { stream: "true" };
874
+ if (options.events !== void 0) {
875
+ params.events = options.events.toString();
876
+ }
877
+ const resp = await this.rawRequest(
878
+ `/${researchId}`,
879
+ "GET",
880
+ void 0,
881
+ params
882
+ );
883
+ if (!resp.body) {
884
+ throw new Error("No response body for SSE stream");
885
+ }
886
+ const reader = resp.body.getReader();
887
+ const decoder = new TextDecoder();
888
+ let buffer = "";
889
+ function processPart(part) {
890
+ const lines = part.split("\n");
891
+ let data = lines.slice(1).join("\n");
892
+ if (data.startsWith("data:")) {
893
+ data = data.slice(5).trimStart();
894
+ }
895
+ try {
896
+ return JSON.parse(data);
897
+ } catch (e) {
898
+ return null;
899
+ }
900
+ }
901
+ async function* streamEvents() {
902
+ while (true) {
903
+ const { done, value } = await reader.read();
904
+ if (done) break;
905
+ buffer += decoder.decode(value, { stream: true });
906
+ let parts = buffer.split("\n\n");
907
+ buffer = parts.pop() ?? "";
908
+ for (const part of parts) {
909
+ const processed = processPart(part);
910
+ if (processed) {
911
+ yield processed;
912
+ }
913
+ }
914
+ }
915
+ if (buffer.trim()) {
916
+ const processed = processPart(buffer.trim());
917
+ if (processed) {
918
+ yield processed;
919
+ }
920
+ }
921
+ }
922
+ return streamEvents();
923
+ };
924
+ return promise();
925
+ } else {
926
+ const params = { stream: "false" };
927
+ if (options?.events !== void 0) {
928
+ params.events = options.events.toString();
929
+ }
930
+ return this.request(
931
+ `/${researchId}`,
932
+ "GET",
933
+ void 0,
934
+ params
935
+ );
932
936
  }
933
- return items;
934
937
  }
935
- /**
936
- * Get an Item by ID
937
- * @param websetId The ID of the Webset
938
- * @param id The ID of the Item
939
- * @returns The Webset Item
940
- */
941
- async get(websetId, id) {
942
- return this.request(
943
- `/v0/websets/${websetId}/items/${id}`,
944
- "GET"
945
- );
938
+ async list(options) {
939
+ const params = this.buildPaginationParams(options);
940
+ return this.request("", "GET", void 0, params);
946
941
  }
947
- /**
948
- * Delete an Item
949
- * @param websetId The ID of the Webset
950
- * @param id The ID of the Item
951
- * @returns The deleted Webset Item
952
- */
953
- async delete(websetId, id) {
954
- return this.request(
955
- `/v0/websets/${websetId}/items/${id}`,
956
- "DELETE"
957
- );
942
+ async pollUntilFinished(researchId, options) {
943
+ const pollInterval = options?.pollInterval ?? 1e3;
944
+ const timeoutMs = options?.timeoutMs ?? 10 * 60 * 1e3;
945
+ const maxConsecutiveFailures = 5;
946
+ const startTime = Date.now();
947
+ let consecutiveFailures = 0;
948
+ while (true) {
949
+ try {
950
+ const research = await this.get(researchId, {
951
+ events: options?.events
952
+ });
953
+ consecutiveFailures = 0;
954
+ if (research.status === "completed" || research.status === "failed" || research.status === "canceled") {
955
+ return research;
956
+ }
957
+ } catch (err) {
958
+ consecutiveFailures += 1;
959
+ if (consecutiveFailures >= maxConsecutiveFailures) {
960
+ throw new Error(
961
+ `Polling failed ${maxConsecutiveFailures} times in a row for research ${researchId}: ${err}`
962
+ );
963
+ }
964
+ }
965
+ if (Date.now() - startTime > timeoutMs) {
966
+ throw new Error(
967
+ `Polling timeout: Research ${researchId} did not complete within ${timeoutMs}ms`
968
+ );
969
+ }
970
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
971
+ }
958
972
  }
959
973
  };
960
974
 
961
- // src/websets/monitors.ts
962
- var WebsetMonitorRunsClient = class extends WebsetsBaseClient {
963
- /**
964
- * List all runs for a Monitor
965
- * @param monitorId The ID of the Monitor
966
- * @param options Pagination options
967
- * @returns The list of Monitor runs
968
- */
969
- async list(monitorId, options) {
970
- const params = this.buildPaginationParams(options);
971
- return this.request(
972
- `/v0/monitors/${monitorId}/runs`,
973
- "GET",
974
- void 0,
975
- params
976
- );
977
- }
975
+ // src/websets/base.ts
976
+ var WebsetsBaseClient2 = class {
978
977
  /**
979
- * Get a specific Monitor run
980
- * @param monitorId The ID of the Monitor
981
- * @param runId The ID of the Monitor run
982
- * @returns The Monitor run
978
+ * Initialize a new Websets base client
979
+ * @param client The Exa client instance
983
980
  */
984
- async get(monitorId, runId) {
985
- return this.request(
986
- `/v0/monitors/${monitorId}/runs/${runId}`,
987
- "GET"
988
- );
989
- }
990
- };
991
- var WebsetMonitorsClient = class extends WebsetsBaseClient {
992
981
  constructor(client) {
993
- super(client);
994
- this.runs = new WebsetMonitorRunsClient(client);
995
- }
996
- /**
997
- * Create a Monitor
998
- * @param params The monitor parameters
999
- * @returns The created Monitor
1000
- */
1001
- async create(params) {
1002
- return this.request("/v0/monitors", "POST", params);
1003
- }
1004
- /**
1005
- * Get a Monitor by ID
1006
- * @param id The ID of the Monitor
1007
- * @returns The Monitor
1008
- */
1009
- async get(id) {
1010
- return this.request(`/v0/monitors/${id}`, "GET");
982
+ this.client = client;
1011
983
  }
1012
984
  /**
1013
- * List all Monitors
1014
- * @param options Pagination and filtering options
1015
- * @returns The list of Monitors
985
+ * Make a request to the Websets API
986
+ * @param endpoint The endpoint path
987
+ * @param method The HTTP method
988
+ * @param data Optional request body data
989
+ * @param params Optional query parameters
990
+ * @returns The response JSON
991
+ * @throws ExaError with API error details if the request fails
1016
992
  */
1017
- async list(options) {
1018
- const params = {
1019
- cursor: options?.cursor,
1020
- limit: options?.limit,
1021
- websetId: options?.websetId
1022
- };
1023
- return this.request(
1024
- "/v0/monitors",
1025
- "GET",
1026
- void 0,
1027
- params
993
+ async request(endpoint, method = "POST", data, params, headers) {
994
+ return this.client.request(
995
+ `/websets${endpoint}`,
996
+ method,
997
+ data,
998
+ params,
999
+ headers
1028
1000
  );
1029
1001
  }
1030
1002
  /**
1031
- * Update a Monitor
1032
- * @param id The ID of the Monitor
1033
- * @param params The monitor update parameters (status, metadata)
1034
- * @returns The updated Monitor
1035
- */
1036
- async update(id, params) {
1037
- return this.request(`/v0/monitors/${id}`, "PATCH", params);
1038
- }
1039
- /**
1040
- * Delete a Monitor
1041
- * @param id The ID of the Monitor
1042
- * @returns The deleted Monitor
1043
- */
1044
- async delete(id) {
1045
- return this.request(`/v0/monitors/${id}`, "DELETE");
1046
- }
1047
- /**
1048
- * Iterate through all Monitors, handling pagination automatically
1049
- * @param options Pagination and filtering options
1050
- * @returns Async generator of Monitors
1051
- */
1052
- async *listAll(options) {
1053
- let cursor = void 0;
1054
- const pageOptions = options ? { ...options } : {};
1055
- while (true) {
1056
- pageOptions.cursor = cursor;
1057
- const response = await this.list(pageOptions);
1058
- for (const monitor of response.data) {
1059
- yield monitor;
1060
- }
1061
- if (!response.hasMore || !response.nextCursor) {
1062
- break;
1063
- }
1064
- cursor = response.nextCursor;
1065
- }
1066
- }
1067
- /**
1068
- * Collect all Monitors into an array
1069
- * @param options Pagination and filtering options
1070
- * @returns Promise resolving to an array of all Monitors
1003
+ * Helper to build pagination parameters
1004
+ * @param pagination The pagination parameters
1005
+ * @returns QueryParams object with pagination parameters
1071
1006
  */
1072
- async getAll(options) {
1073
- const monitors = [];
1074
- for await (const monitor of this.listAll(options)) {
1075
- monitors.push(monitor);
1076
- }
1077
- return monitors;
1007
+ buildPaginationParams(pagination) {
1008
+ const params = {};
1009
+ if (!pagination) return params;
1010
+ if (pagination.cursor) params.cursor = pagination.cursor;
1011
+ if (pagination.limit) params.limit = pagination.limit;
1012
+ return params;
1078
1013
  }
1079
1014
  };
1080
1015
 
1081
- // src/websets/searches.ts
1082
- var WebsetSearchesClient = class extends WebsetsBaseClient {
1016
+ // src/websets/enrichments.ts
1017
+ var WebsetEnrichmentsClient2 = class extends WebsetsBaseClient2 {
1083
1018
  /**
1084
- * Create a new Search for the Webset
1019
+ * Create an Enrichment for a Webset
1085
1020
  * @param websetId The ID of the Webset
1086
- * @param params The search parameters
1087
- * @returns The created Webset Search
1021
+ * @param params The enrichment parameters
1022
+ * @returns The created Webset Enrichment
1088
1023
  */
1089
- async create(websetId, params, options) {
1024
+ async create(websetId, params) {
1090
1025
  return this.request(
1091
- `/v0/websets/${websetId}/searches`,
1026
+ `/v0/websets/${websetId}/enrichments`,
1092
1027
  "POST",
1093
- params,
1094
- void 0,
1095
- options?.headers
1028
+ params
1096
1029
  );
1097
1030
  }
1098
1031
  /**
1099
- * Get a Search by ID
1032
+ * Get an Enrichment by ID
1100
1033
  * @param websetId The ID of the Webset
1101
- * @param id The ID of the Search
1102
- * @returns The Webset Search
1034
+ * @param id The ID of the Enrichment
1035
+ * @returns The Webset Enrichment
1103
1036
  */
1104
1037
  async get(websetId, id) {
1105
1038
  return this.request(
1106
- `/v0/websets/${websetId}/searches/${id}`,
1039
+ `/v0/websets/${websetId}/enrichments/${id}`,
1107
1040
  "GET"
1108
1041
  );
1109
1042
  }
1110
1043
  /**
1111
- * Cancel a running Search
1044
+ * Delete an Enrichment
1112
1045
  * @param websetId The ID of the Webset
1113
- * @param id The ID of the Search
1114
- * @returns The canceled Webset Search
1046
+ * @param id The ID of the Enrichment
1047
+ * @returns The deleted Webset Enrichment
1115
1048
  */
1116
- async cancel(websetId, id) {
1049
+ async delete(websetId, id) {
1117
1050
  return this.request(
1118
- `/v0/websets/${websetId}/searches/${id}/cancel`,
1119
- "POST"
1051
+ `/v0/websets/${websetId}/enrichments/${id}`,
1052
+ "DELETE"
1120
1053
  );
1121
1054
  }
1122
- };
1123
-
1124
- // src/websets/webhooks.ts
1125
- var WebsetWebhooksClient = class extends WebsetsBaseClient {
1126
- /**
1127
- * Create a Webhook
1128
- * @param params The webhook parameters
1129
- * @returns The created Webhook
1130
- */
1131
- async create(params) {
1132
- return this.request("/v0/webhooks", "POST", params);
1133
- }
1134
- /**
1135
- * Get a Webhook by ID
1136
- * @param id The ID of the Webhook
1137
- * @returns The Webhook
1138
- */
1139
- async get(id) {
1140
- return this.request(`/v0/webhooks/${id}`, "GET");
1141
- }
1142
1055
  /**
1143
- * List all Webhooks
1144
- * @param options Pagination options
1145
- * @returns The list of Webhooks
1056
+ * Update an Enrichment
1057
+ * @param websetId The ID of the Webset
1058
+ * @param id The ID of the Enrichment
1059
+ * @param params The enrichment update parameters
1060
+ * @returns Promise that resolves when the update is complete
1146
1061
  */
1147
- async list(options) {
1148
- const params = this.buildPaginationParams(options);
1062
+ async update(websetId, id, params) {
1149
1063
  return this.request(
1150
- "/v0/webhooks",
1151
- "GET",
1152
- void 0,
1064
+ `/v0/websets/${websetId}/enrichments/${id}`,
1065
+ "PATCH",
1153
1066
  params
1154
1067
  );
1155
1068
  }
1156
1069
  /**
1157
- * Iterate through all Webhooks, handling pagination automatically
1158
- * @param options Pagination options
1159
- * @returns Async generator of Webhooks
1160
- */
1161
- async *listAll(options) {
1162
- let cursor = void 0;
1163
- const pageOptions = options ? { ...options } : {};
1164
- while (true) {
1165
- pageOptions.cursor = cursor;
1166
- const response = await this.list(pageOptions);
1167
- for (const webhook of response.data) {
1168
- yield webhook;
1169
- }
1170
- if (!response.hasMore || !response.nextCursor) {
1171
- break;
1172
- }
1173
- cursor = response.nextCursor;
1174
- }
1175
- }
1176
- /**
1177
- * Collect all Webhooks into an array
1178
- * @param options Pagination options
1179
- * @returns Promise resolving to an array of all Webhooks
1180
- */
1181
- async getAll(options) {
1182
- const webhooks = [];
1183
- for await (const webhook of this.listAll(options)) {
1184
- webhooks.push(webhook);
1185
- }
1186
- return webhooks;
1187
- }
1188
- /**
1189
- * Update a Webhook
1190
- * @param id The ID of the Webhook
1191
- * @param params The webhook update parameters (events, metadata, url)
1192
- * @returns The updated Webhook
1070
+ * Cancel a running Enrichment
1071
+ * @param websetId The ID of the Webset
1072
+ * @param id The ID of the Enrichment
1073
+ * @returns The canceled Webset Enrichment
1193
1074
  */
1194
- async update(id, params) {
1195
- return this.request(`/v0/webhooks/${id}`, "PATCH", params);
1075
+ async cancel(websetId, id) {
1076
+ return this.request(
1077
+ `/v0/websets/${websetId}/enrichments/${id}/cancel`,
1078
+ "POST"
1079
+ );
1196
1080
  }
1081
+ };
1082
+
1083
+ // src/websets/events.ts
1084
+ var EventsClient2 = class extends WebsetsBaseClient2 {
1197
1085
  /**
1198
- * Delete a Webhook
1199
- * @param id The ID of the Webhook
1200
- * @returns The deleted Webhook
1086
+ * Initialize a new Events client
1087
+ * @param client The Exa client instance
1201
1088
  */
1202
- async delete(id) {
1203
- return this.request(`/v0/webhooks/${id}`, "DELETE");
1089
+ constructor(client) {
1090
+ super(client);
1204
1091
  }
1205
1092
  /**
1206
- * List all attempts for a Webhook
1207
- * @param id The ID of the Webhook
1208
- * @param options Pagination and filtering options
1209
- * @returns The list of Webhook attempts
1093
+ * List all Events
1094
+ * @param options Optional filtering and pagination options
1095
+ * @returns The list of Events
1210
1096
  */
1211
- async listAttempts(id, options) {
1097
+ async list(options) {
1212
1098
  const params = {
1213
1099
  cursor: options?.cursor,
1214
1100
  limit: options?.limit,
1215
- eventType: options?.eventType,
1216
- successful: options?.successful
1101
+ types: options?.types
1217
1102
  };
1218
1103
  return this.request(
1219
- `/v0/webhooks/${id}/attempts`,
1104
+ "/v0/events",
1220
1105
  "GET",
1221
1106
  void 0,
1222
1107
  params
1223
1108
  );
1224
1109
  }
1225
1110
  /**
1226
- * Iterate through all attempts for a Webhook, handling pagination automatically
1227
- * @param id The ID of the Webhook
1228
- * @param options Pagination and filtering options
1229
- * @returns Async generator of Webhook attempts
1111
+ * Get an Event by ID
1112
+ * @param id The ID of the Event
1113
+ * @returns The Event
1230
1114
  */
1231
- async *listAllAttempts(id, options) {
1115
+ async get(id) {
1116
+ return this.request(`/v0/events/${id}`, "GET");
1117
+ }
1118
+ /**
1119
+ * Iterate through all Events, handling pagination automatically
1120
+ * @param options Filtering and pagination options
1121
+ * @returns Async generator of Events
1122
+ */
1123
+ async *listAll(options) {
1232
1124
  let cursor = void 0;
1233
1125
  const pageOptions = options ? { ...options } : {};
1234
1126
  while (true) {
1235
1127
  pageOptions.cursor = cursor;
1236
- const response = await this.listAttempts(id, pageOptions);
1237
- for (const attempt of response.data) {
1238
- yield attempt;
1128
+ const response = await this.list(pageOptions);
1129
+ for (const event of response.data) {
1130
+ yield event;
1239
1131
  }
1240
1132
  if (!response.hasMore || !response.nextCursor) {
1241
1133
  break;
1242
1134
  }
1243
1135
  cursor = response.nextCursor;
1244
1136
  }
1245
- }
1246
- /**
1247
- * Collect all attempts for a Webhook into an array
1248
- * @param id The ID of the Webhook
1249
- * @param options Pagination and filtering options
1250
- * @returns Promise resolving to an array of all Webhook attempts
1251
- */
1252
- async getAllAttempts(id, options) {
1253
- const attempts = [];
1254
- for await (const attempt of this.listAllAttempts(id, options)) {
1255
- attempts.push(attempt);
1137
+ }
1138
+ /**
1139
+ * Collect all Events into an array
1140
+ * @param options Filtering and pagination options
1141
+ * @returns Promise resolving to an array of all Events
1142
+ */
1143
+ async getAll(options) {
1144
+ const events = [];
1145
+ for await (const event of this.listAll(options)) {
1146
+ events.push(event);
1147
+ }
1148
+ return events;
1149
+ }
1150
+ };
1151
+
1152
+ // src/websets/openapi.ts
1153
+ var CreateEnrichmentParametersFormat = /* @__PURE__ */ ((CreateEnrichmentParametersFormat2) => {
1154
+ CreateEnrichmentParametersFormat2["text"] = "text";
1155
+ CreateEnrichmentParametersFormat2["date"] = "date";
1156
+ CreateEnrichmentParametersFormat2["number"] = "number";
1157
+ CreateEnrichmentParametersFormat2["options"] = "options";
1158
+ CreateEnrichmentParametersFormat2["email"] = "email";
1159
+ CreateEnrichmentParametersFormat2["phone"] = "phone";
1160
+ CreateEnrichmentParametersFormat2["url"] = "url";
1161
+ return CreateEnrichmentParametersFormat2;
1162
+ })(CreateEnrichmentParametersFormat || {});
1163
+ var CreateImportParametersFormat = /* @__PURE__ */ ((CreateImportParametersFormat2) => {
1164
+ CreateImportParametersFormat2["csv"] = "csv";
1165
+ return CreateImportParametersFormat2;
1166
+ })(CreateImportParametersFormat || {});
1167
+ var WebsetImportSource = /* @__PURE__ */ ((WebsetImportSource2) => {
1168
+ WebsetImportSource2["import"] = "import";
1169
+ WebsetImportSource2["webset"] = "webset";
1170
+ return WebsetImportSource2;
1171
+ })(WebsetImportSource || {});
1172
+ var EventType = /* @__PURE__ */ ((EventType2) => {
1173
+ EventType2["webset_created"] = "webset.created";
1174
+ EventType2["webset_deleted"] = "webset.deleted";
1175
+ EventType2["webset_paused"] = "webset.paused";
1176
+ EventType2["webset_idle"] = "webset.idle";
1177
+ EventType2["webset_search_created"] = "webset.search.created";
1178
+ EventType2["webset_search_canceled"] = "webset.search.canceled";
1179
+ EventType2["webset_search_completed"] = "webset.search.completed";
1180
+ EventType2["webset_search_updated"] = "webset.search.updated";
1181
+ EventType2["import_created"] = "import.created";
1182
+ EventType2["import_completed"] = "import.completed";
1183
+ EventType2["webset_item_created"] = "webset.item.created";
1184
+ EventType2["webset_item_enriched"] = "webset.item.enriched";
1185
+ EventType2["monitor_created"] = "monitor.created";
1186
+ EventType2["monitor_updated"] = "monitor.updated";
1187
+ EventType2["monitor_deleted"] = "monitor.deleted";
1188
+ EventType2["monitor_run_created"] = "monitor.run.created";
1189
+ EventType2["monitor_run_completed"] = "monitor.run.completed";
1190
+ EventType2["webset_export_created"] = "webset.export.created";
1191
+ EventType2["webset_export_completed"] = "webset.export.completed";
1192
+ return EventType2;
1193
+ })(EventType || {});
1194
+ var ImportFailedReason = /* @__PURE__ */ ((ImportFailedReason2) => {
1195
+ ImportFailedReason2["invalid_format"] = "invalid_format";
1196
+ ImportFailedReason2["invalid_file_content"] = "invalid_file_content";
1197
+ ImportFailedReason2["missing_identifier"] = "missing_identifier";
1198
+ return ImportFailedReason2;
1199
+ })(ImportFailedReason || {});
1200
+ var ImportFormat = /* @__PURE__ */ ((ImportFormat2) => {
1201
+ ImportFormat2["csv"] = "csv";
1202
+ ImportFormat2["webset"] = "webset";
1203
+ return ImportFormat2;
1204
+ })(ImportFormat || {});
1205
+ var ImportObject = /* @__PURE__ */ ((ImportObject2) => {
1206
+ ImportObject2["import"] = "import";
1207
+ return ImportObject2;
1208
+ })(ImportObject || {});
1209
+ var ImportStatus = /* @__PURE__ */ ((ImportStatus2) => {
1210
+ ImportStatus2["pending"] = "pending";
1211
+ ImportStatus2["processing"] = "processing";
1212
+ ImportStatus2["completed"] = "completed";
1213
+ ImportStatus2["failed"] = "failed";
1214
+ return ImportStatus2;
1215
+ })(ImportStatus || {});
1216
+ var MonitorObject = /* @__PURE__ */ ((MonitorObject2) => {
1217
+ MonitorObject2["monitor"] = "monitor";
1218
+ return MonitorObject2;
1219
+ })(MonitorObject || {});
1220
+ var MonitorStatus = /* @__PURE__ */ ((MonitorStatus2) => {
1221
+ MonitorStatus2["enabled"] = "enabled";
1222
+ MonitorStatus2["disabled"] = "disabled";
1223
+ return MonitorStatus2;
1224
+ })(MonitorStatus || {});
1225
+ var MonitorRunObject = /* @__PURE__ */ ((MonitorRunObject2) => {
1226
+ MonitorRunObject2["monitor_run"] = "monitor_run";
1227
+ return MonitorRunObject2;
1228
+ })(MonitorRunObject || {});
1229
+ var MonitorRunStatus = /* @__PURE__ */ ((MonitorRunStatus2) => {
1230
+ MonitorRunStatus2["created"] = "created";
1231
+ MonitorRunStatus2["running"] = "running";
1232
+ MonitorRunStatus2["completed"] = "completed";
1233
+ MonitorRunStatus2["canceled"] = "canceled";
1234
+ MonitorRunStatus2["failed"] = "failed";
1235
+ return MonitorRunStatus2;
1236
+ })(MonitorRunStatus || {});
1237
+ var MonitorRunType = /* @__PURE__ */ ((MonitorRunType2) => {
1238
+ MonitorRunType2["search"] = "search";
1239
+ MonitorRunType2["refresh"] = "refresh";
1240
+ return MonitorRunType2;
1241
+ })(MonitorRunType || {});
1242
+ var UpdateMonitorStatus = /* @__PURE__ */ ((UpdateMonitorStatus2) => {
1243
+ UpdateMonitorStatus2["enabled"] = "enabled";
1244
+ UpdateMonitorStatus2["disabled"] = "disabled";
1245
+ return UpdateMonitorStatus2;
1246
+ })(UpdateMonitorStatus || {});
1247
+ var WebhookStatus = /* @__PURE__ */ ((WebhookStatus2) => {
1248
+ WebhookStatus2["active"] = "active";
1249
+ WebhookStatus2["inactive"] = "inactive";
1250
+ return WebhookStatus2;
1251
+ })(WebhookStatus || {});
1252
+ var WebsetStatus = /* @__PURE__ */ ((WebsetStatus2) => {
1253
+ WebsetStatus2["idle"] = "idle";
1254
+ WebsetStatus2["pending"] = "pending";
1255
+ WebsetStatus2["running"] = "running";
1256
+ WebsetStatus2["paused"] = "paused";
1257
+ return WebsetStatus2;
1258
+ })(WebsetStatus || {});
1259
+ var WebsetEnrichmentStatus = /* @__PURE__ */ ((WebsetEnrichmentStatus2) => {
1260
+ WebsetEnrichmentStatus2["pending"] = "pending";
1261
+ WebsetEnrichmentStatus2["canceled"] = "canceled";
1262
+ WebsetEnrichmentStatus2["completed"] = "completed";
1263
+ return WebsetEnrichmentStatus2;
1264
+ })(WebsetEnrichmentStatus || {});
1265
+ var WebsetEnrichmentFormat = /* @__PURE__ */ ((WebsetEnrichmentFormat2) => {
1266
+ WebsetEnrichmentFormat2["text"] = "text";
1267
+ WebsetEnrichmentFormat2["date"] = "date";
1268
+ WebsetEnrichmentFormat2["number"] = "number";
1269
+ WebsetEnrichmentFormat2["options"] = "options";
1270
+ WebsetEnrichmentFormat2["email"] = "email";
1271
+ WebsetEnrichmentFormat2["phone"] = "phone";
1272
+ WebsetEnrichmentFormat2["url"] = "url";
1273
+ return WebsetEnrichmentFormat2;
1274
+ })(WebsetEnrichmentFormat || {});
1275
+ var WebsetItemSource = /* @__PURE__ */ ((WebsetItemSource2) => {
1276
+ WebsetItemSource2["search"] = "search";
1277
+ WebsetItemSource2["import"] = "import";
1278
+ return WebsetItemSource2;
1279
+ })(WebsetItemSource || {});
1280
+ var WebsetItemEvaluationSatisfied = /* @__PURE__ */ ((WebsetItemEvaluationSatisfied2) => {
1281
+ WebsetItemEvaluationSatisfied2["yes"] = "yes";
1282
+ WebsetItemEvaluationSatisfied2["no"] = "no";
1283
+ WebsetItemEvaluationSatisfied2["unclear"] = "unclear";
1284
+ return WebsetItemEvaluationSatisfied2;
1285
+ })(WebsetItemEvaluationSatisfied || {});
1286
+ var WebsetExcludeSource = /* @__PURE__ */ ((WebsetExcludeSource2) => {
1287
+ WebsetExcludeSource2["import"] = "import";
1288
+ WebsetExcludeSource2["webset"] = "webset";
1289
+ return WebsetExcludeSource2;
1290
+ })(WebsetExcludeSource || {});
1291
+ var WebsetSearchScopeSource = /* @__PURE__ */ ((WebsetSearchScopeSource2) => {
1292
+ WebsetSearchScopeSource2["import"] = "import";
1293
+ WebsetSearchScopeSource2["webset"] = "webset";
1294
+ return WebsetSearchScopeSource2;
1295
+ })(WebsetSearchScopeSource || {});
1296
+ var WebsetSearchStatus = /* @__PURE__ */ ((WebsetSearchStatus2) => {
1297
+ WebsetSearchStatus2["created"] = "created";
1298
+ WebsetSearchStatus2["pending"] = "pending";
1299
+ WebsetSearchStatus2["running"] = "running";
1300
+ WebsetSearchStatus2["completed"] = "completed";
1301
+ WebsetSearchStatus2["canceled"] = "canceled";
1302
+ return WebsetSearchStatus2;
1303
+ })(WebsetSearchStatus || {});
1304
+ var WebsetSearchBehavior = /* @__PURE__ */ ((WebsetSearchBehavior2) => {
1305
+ WebsetSearchBehavior2["override"] = "override";
1306
+ WebsetSearchBehavior2["append"] = "append";
1307
+ return WebsetSearchBehavior2;
1308
+ })(WebsetSearchBehavior || {});
1309
+ var WebsetSearchCanceledReason = /* @__PURE__ */ ((WebsetSearchCanceledReason2) => {
1310
+ WebsetSearchCanceledReason2["webset_deleted"] = "webset_deleted";
1311
+ WebsetSearchCanceledReason2["webset_canceled"] = "webset_canceled";
1312
+ return WebsetSearchCanceledReason2;
1313
+ })(WebsetSearchCanceledReason || {});
1314
+
1315
+ // src/websets/imports.ts
1316
+ var ImportsClient2 = class extends WebsetsBaseClient2 {
1317
+ async create(params, csv) {
1318
+ if (csv === void 0) {
1319
+ return this.request(
1320
+ "/v0/imports",
1321
+ "POST",
1322
+ params
1323
+ );
1324
+ }
1325
+ let csvBuffer;
1326
+ if (typeof csv === "string") {
1327
+ csvBuffer = Buffer.from(csv, "utf8");
1328
+ } else if (Buffer.isBuffer(csv)) {
1329
+ csvBuffer = csv;
1330
+ } else {
1331
+ throw new ExaError(
1332
+ "Invalid CSV data input. Must be string or Buffer",
1333
+ 400 /* BadRequest */
1334
+ );
1335
+ }
1336
+ const sizeInBytes = csvBuffer.length;
1337
+ const sizeInMB = Math.max(1, Math.ceil(sizeInBytes / (1024 * 1024)));
1338
+ const csvText = csvBuffer.toString("utf8");
1339
+ const lines = csvText.split("\n").filter((line) => line.trim().length > 0);
1340
+ const recordCount = Math.max(0, lines.length - 1);
1341
+ if (sizeInMB > 50) {
1342
+ throw new ExaError(
1343
+ `CSV file too large: ${sizeInMB}MB. Maximum size is 50MB.`,
1344
+ 400 /* BadRequest */
1345
+ );
1256
1346
  }
1257
- return attempts;
1258
- }
1259
- };
1260
-
1261
- // src/websets/client.ts
1262
- var WebsetsClient = class extends WebsetsBaseClient {
1263
- /**
1264
- * Initialize a new Websets client
1265
- * @param client The Exa client instance
1266
- */
1267
- constructor(client) {
1268
- super(client);
1269
- this.events = new EventsClient(client);
1270
- this.imports = new ImportsClient(client);
1271
- this.items = new WebsetItemsClient(client);
1272
- this.searches = new WebsetSearchesClient(client);
1273
- this.enrichments = new WebsetEnrichmentsClient(client);
1274
- this.monitors = new WebsetMonitorsClient(client);
1275
- this.webhooks = new WebsetWebhooksClient(client);
1276
- }
1277
- /**
1278
- * Create a new Webset
1279
- * @param params The Webset creation parameters
1280
- * @returns The created Webset
1281
- */
1282
- async create(params, options) {
1283
- return this.request(
1284
- "/v0/websets",
1285
- "POST",
1286
- params,
1287
- void 0,
1288
- options?.headers
1289
- );
1290
- }
1291
- /**
1292
- * Preview a webset
1293
- * @param params The preview parameters
1294
- * @param options Optional parameters. Search = true allows you to retrieve a preview set of items that could be returned by the webset.
1295
- * @returns The preview response showing how the query will be decomposed
1296
- */
1297
- async preview(params, options) {
1298
- const queryParams = {};
1299
- if (options?.search !== void 0) {
1300
- queryParams.search = options.search;
1347
+ if (recordCount === 0) {
1348
+ throw new ExaError(
1349
+ "CSV file appears to have no data records (only header or empty)",
1350
+ 400 /* BadRequest */
1351
+ );
1301
1352
  }
1302
- return this.request(
1303
- "/v0/websets/preview",
1353
+ const createParams = {
1354
+ title: params.title,
1355
+ format: "csv" /* csv */,
1356
+ entity: params.entity,
1357
+ size: sizeInBytes,
1358
+ count: recordCount,
1359
+ metadata: params.metadata,
1360
+ csv: params.csv
1361
+ };
1362
+ const importResponse = await this.request(
1363
+ "/v0/imports",
1304
1364
  "POST",
1305
- params,
1306
- queryParams
1365
+ createParams
1307
1366
  );
1367
+ try {
1368
+ const uploadResponse = await fetch(importResponse.uploadUrl, {
1369
+ method: "PUT",
1370
+ body: csvBuffer
1371
+ });
1372
+ if (!uploadResponse.ok) {
1373
+ const errorText = await uploadResponse.text();
1374
+ throw new ExaError(
1375
+ `Upload failed: ${uploadResponse.status} ${uploadResponse.statusText}. ${errorText}`,
1376
+ 400 /* BadRequest */
1377
+ );
1378
+ }
1379
+ } catch (error) {
1380
+ if (error instanceof ExaError) {
1381
+ throw error;
1382
+ }
1383
+ throw new ExaError(
1384
+ `Failed to upload CSV data: ${error.message}`,
1385
+ 400 /* BadRequest */
1386
+ );
1387
+ }
1388
+ return importResponse;
1308
1389
  }
1309
1390
  /**
1310
- * Get a Webset by ID
1311
- * @param id The ID of the Webset
1312
- * @param expand Optional array of relations to expand
1313
- * @returns The Webset
1391
+ * Get an Import by ID
1392
+ * @param id The ID of the Import
1393
+ * @returns The Import
1314
1394
  */
1315
- async get(id, expand) {
1316
- const params = {};
1317
- if (expand) {
1318
- params.expand = expand;
1319
- }
1320
- return this.request(
1321
- `/v0/websets/${id}`,
1322
- "GET",
1323
- void 0,
1324
- params
1325
- );
1395
+ async get(id) {
1396
+ return this.request(`/v0/imports/${id}`, "GET");
1326
1397
  }
1327
1398
  /**
1328
- * List all Websets
1329
- * @param options Pagination options (filtering by status is not supported by API)
1330
- * @returns The list of Websets
1399
+ * List all Imports
1400
+ * @param options Pagination options
1401
+ * @returns The list of Imports
1331
1402
  */
1332
1403
  async list(options) {
1333
1404
  const params = this.buildPaginationParams(options);
1334
1405
  return this.request(
1335
- "/v0/websets",
1406
+ "/v0/imports",
1336
1407
  "GET",
1337
1408
  void 0,
1338
1409
  params
1339
1410
  );
1340
1411
  }
1341
1412
  /**
1342
- * Iterate through all Websets, handling pagination automatically
1343
- * @param options Pagination options
1344
- * @returns Async generator of Websets
1345
- */
1346
- async *listAll(options) {
1347
- let cursor = void 0;
1348
- const pageOptions = options ? { ...options } : {};
1349
- while (true) {
1350
- pageOptions.cursor = cursor;
1351
- const response = await this.list(pageOptions);
1352
- for (const webset of response.data) {
1353
- yield webset;
1354
- }
1355
- if (!response.hasMore || !response.nextCursor) {
1356
- break;
1357
- }
1358
- cursor = response.nextCursor;
1359
- }
1360
- }
1361
- /**
1362
- * Collect all Websets into an array
1363
- * @param options Pagination options
1364
- * @returns Promise resolving to an array of all Websets
1365
- */
1366
- async getAll(options) {
1367
- const websets = [];
1368
- for await (const webset of this.listAll(options)) {
1369
- websets.push(webset);
1370
- }
1371
- return websets;
1372
- }
1373
- /**
1374
- * Update a Webset
1375
- * @param id The ID of the Webset
1376
- * @param params The Webset update parameters
1377
- * @returns The updated Webset
1413
+ * Update an Import
1414
+ * @param id The ID of the Import
1415
+ * @param params The import update parameters
1416
+ * @returns The updated Import
1378
1417
  */
1379
1418
  async update(id, params) {
1380
- return this.request(`/v0/websets/${id}`, "POST", params);
1419
+ return this.request(`/v0/imports/${id}`, "PATCH", params);
1381
1420
  }
1382
1421
  /**
1383
- * Delete a Webset
1384
- * @param id The ID of the Webset
1385
- * @returns The deleted Webset
1422
+ * Delete an Import
1423
+ * @param id The ID of the Import
1424
+ * @returns The deleted Import
1386
1425
  */
1387
1426
  async delete(id) {
1388
- return this.request(`/v0/websets/${id}`, "DELETE");
1389
- }
1390
- /**
1391
- * Cancel a running Webset
1392
- * @param id The ID or external ID of the Webset
1393
- * @returns The canceled Webset (as returned by the API)
1394
- */
1395
- async cancel(id) {
1396
- return this.request(`/v0/websets/${id}/cancel`, "POST");
1427
+ return this.request(`/v0/imports/${id}`, "DELETE");
1397
1428
  }
1398
1429
  /**
1399
- * Wait until a Webset is idle
1400
- * @param id The ID of the Webset
1430
+ * Wait until an Import is completed or failed
1431
+ * @param id The ID of the Import
1401
1432
  * @param options Configuration options for timeout and polling
1402
- * @returns The Webset once it becomes idle
1403
- * @throws Error if the Webset does not become idle within the timeout
1433
+ * @returns The Import once it reaches a final state (completed or failed)
1434
+ * @throws Error if the Import does not complete within the timeout or fails
1404
1435
  */
1405
- async waitUntilIdle(id, options) {
1406
- let timeout;
1407
- let pollInterval = 1e3;
1408
- let onPoll;
1409
- if (typeof options === "number") {
1410
- timeout = options;
1411
- } else if (options) {
1412
- timeout = options.timeout;
1413
- pollInterval = options.pollInterval || 1e3;
1414
- onPoll = options.onPoll;
1415
- }
1436
+ async waitUntilCompleted(id, options) {
1437
+ const timeout = options?.timeout ?? 30 * 60 * 1e3;
1438
+ const pollInterval = options?.pollInterval ?? 2e3;
1439
+ const onPoll = options?.onPoll;
1416
1440
  const startTime = Date.now();
1417
1441
  while (true) {
1418
- const webset = await this.get(id);
1442
+ const importItem = await this.get(id);
1419
1443
  if (onPoll) {
1420
- onPoll(webset.status);
1444
+ onPoll(importItem.status);
1421
1445
  }
1422
- if (webset.status === "idle" /* idle */) {
1423
- return webset;
1446
+ if (importItem.status === "completed" /* completed */) {
1447
+ return importItem;
1448
+ }
1449
+ if (importItem.status === "failed" /* failed */) {
1450
+ throw new ExaError(
1451
+ `Import ${id} failed: ${importItem.failedMessage || "Unknown error"}`,
1452
+ 400 /* BadRequest */
1453
+ );
1454
+ }
1455
+ if (Date.now() - startTime > timeout) {
1456
+ throw new ExaError(
1457
+ `Import ${id} did not complete within ${timeout}ms. Current status: ${importItem.status}`,
1458
+ 408 /* RequestTimeout */
1459
+ );
1460
+ }
1461
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
1462
+ }
1463
+ }
1464
+ /**
1465
+ * Iterate through all Imports, handling pagination automatically
1466
+ * @param options Pagination options
1467
+ * @returns Async generator of Imports
1468
+ */
1469
+ async *listAll(options) {
1470
+ let cursor = void 0;
1471
+ const pageOptions = options ? { ...options } : {};
1472
+ while (true) {
1473
+ pageOptions.cursor = cursor;
1474
+ const response = await this.list(pageOptions);
1475
+ for (const importItem of response.data) {
1476
+ yield importItem;
1424
1477
  }
1425
- if (timeout && Date.now() - startTime > timeout) {
1426
- throw new ExaError(
1427
- `Webset ${id} did not reach idle state within ${timeout}ms. Current status: ${webset.status}`,
1428
- 408 /* RequestTimeout */
1429
- );
1478
+ if (!response.hasMore || !response.nextCursor) {
1479
+ break;
1430
1480
  }
1431
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
1481
+ cursor = response.nextCursor;
1432
1482
  }
1433
1483
  }
1434
- };
1435
-
1436
- // src/nova/websets-client.ts
1437
- var WebsetsBaseClient2 = class {
1438
- constructor(client) {
1439
- this.client = client;
1440
- }
1441
- /** Make a request to the API, prepending `/websets` to the path. */
1442
- async request(endpoint, method = "POST", data, params, headers) {
1443
- return this.client.request(`/websets${endpoint}`, method, data, params, headers);
1444
- }
1445
- buildPaginationParams(pagination) {
1446
- const params = {};
1447
- if (!pagination) return params;
1448
- if (pagination.cursor) params.cursor = pagination.cursor;
1449
- if (pagination.limit) params.limit = pagination.limit;
1450
- return params;
1484
+ /**
1485
+ * Collect all Imports into an array
1486
+ * @param options Pagination options
1487
+ * @returns Promise resolving to an array of all Imports
1488
+ */
1489
+ async getAll(options) {
1490
+ const imports = [];
1491
+ for await (const importItem of this.listAll(options)) {
1492
+ imports.push(importItem);
1493
+ }
1494
+ return imports;
1451
1495
  }
1452
1496
  };
1497
+
1498
+ // src/websets/items.ts
1453
1499
  var WebsetItemsClient2 = class extends WebsetsBaseClient2 {
1454
- async get(websetId, id) {
1455
- return this.request(`/v0/websets/${websetId}/items/${id}`, "GET");
1456
- }
1457
- async delete(websetId, id) {
1458
- return this.request(`/v0/websets/${websetId}/items/${id}`, "DELETE");
1459
- }
1460
- async list(websetId, options) {
1461
- const queryParams = { ...this.buildPaginationParams(options), sourceId: options?.sourceId };
1462
- return this.request(`/v0/websets/${websetId}/items`, "GET", void 0, queryParams);
1500
+ /**
1501
+ * List all Items for a Webset
1502
+ * @param websetId The ID of the Webset
1503
+ * @param params - Optional pagination and filtering parameters
1504
+ * @returns A promise that resolves with the list of Items
1505
+ */
1506
+ list(websetId, params) {
1507
+ const queryParams = {
1508
+ ...this.buildPaginationParams(params),
1509
+ sourceId: params?.sourceId
1510
+ };
1511
+ return this.request(
1512
+ `/v0/websets/${websetId}/items`,
1513
+ "GET",
1514
+ void 0,
1515
+ queryParams
1516
+ );
1463
1517
  }
1464
- /** Iterate through all items in a Webset, handling pagination automatically. */
1518
+ /**
1519
+ * Iterate through all Items in a Webset, handling pagination automatically
1520
+ * @param websetId The ID of the Webset
1521
+ * @param options Pagination options
1522
+ * @returns Async generator of Webset Items
1523
+ */
1465
1524
  async *listAll(websetId, options) {
1466
1525
  let cursor = void 0;
1467
1526
  const pageOptions = options ? { ...options } : {};
1468
1527
  while (true) {
1469
- const response = await this.list(websetId, { ...pageOptions, cursor });
1528
+ pageOptions.cursor = cursor;
1529
+ const response = await this.list(websetId, pageOptions);
1470
1530
  for (const item of response.data) {
1471
1531
  yield item;
1472
1532
  }
@@ -1476,7 +1536,12 @@ var WebsetItemsClient2 = class extends WebsetsBaseClient2 {
1476
1536
  cursor = response.nextCursor;
1477
1537
  }
1478
1538
  }
1479
- /** Collect all items from a Webset into an array. */
1539
+ /**
1540
+ * Collect all items from a Webset into an array
1541
+ * @param websetId The ID of the Webset
1542
+ * @param options Pagination options
1543
+ * @returns Promise resolving to an array of all Webset Items
1544
+ */
1480
1545
  async getAll(websetId, options) {
1481
1546
  const items = [];
1482
1547
  for await (const item of this.listAll(websetId, options)) {
@@ -1484,180 +1549,131 @@ var WebsetItemsClient2 = class extends WebsetsBaseClient2 {
1484
1549
  }
1485
1550
  return items;
1486
1551
  }
1487
- };
1488
- var WebsetSearchesClient2 = class extends WebsetsBaseClient2 {
1489
- async create(websetId, params, options) {
1490
- return this.request(`/v0/websets/${websetId}/searches`, "POST", { ...params }, void 0, options?.headers);
1491
- }
1492
- async get(websetId, id) {
1493
- return this.request(`/v0/websets/${websetId}/searches/${id}`, "GET");
1494
- }
1495
- async cancel(websetId, id) {
1496
- return this.request(`/v0/websets/${websetId}/searches/${id}/cancel`, "POST");
1497
- }
1498
- };
1499
- var WebsetEnrichmentsClient2 = class extends WebsetsBaseClient2 {
1500
- async create(websetId, params) {
1501
- return this.request(`/v0/websets/${websetId}/enrichments`, "POST", { ...params });
1502
- }
1503
- async update(websetId, id, params) {
1504
- return this.request(`/v0/websets/${websetId}/enrichments/${id}`, "PATCH", { ...params });
1505
- }
1552
+ /**
1553
+ * Get an Item by ID
1554
+ * @param websetId The ID of the Webset
1555
+ * @param id The ID of the Item
1556
+ * @returns The Webset Item
1557
+ */
1506
1558
  async get(websetId, id) {
1507
- return this.request(`/v0/websets/${websetId}/enrichments/${id}`, "GET");
1559
+ return this.request(
1560
+ `/v0/websets/${websetId}/items/${id}`,
1561
+ "GET"
1562
+ );
1508
1563
  }
1564
+ /**
1565
+ * Delete an Item
1566
+ * @param websetId The ID of the Webset
1567
+ * @param id The ID of the Item
1568
+ * @returns The deleted Webset Item
1569
+ */
1509
1570
  async delete(websetId, id) {
1510
- return this.request(`/v0/websets/${websetId}/enrichments/${id}`, "DELETE");
1511
- }
1512
- async cancel(websetId, id) {
1513
- return this.request(`/v0/websets/${websetId}/enrichments/${id}/cancel`, "POST");
1514
- }
1515
- };
1516
- var EventsClient2 = class extends WebsetsBaseClient2 {
1517
- async list(options) {
1518
- const queryParams = { ...this.buildPaginationParams(options), types: options?.types, createdBefore: options?.createdBefore, createdAfter: options?.createdAfter };
1519
- return this.request("/v0/events", "GET", void 0, queryParams);
1520
- }
1521
- async get(id) {
1522
- return this.request(`/v0/events/${id}`, "GET");
1571
+ return this.request(
1572
+ `/v0/websets/${websetId}/items/${id}`,
1573
+ "DELETE"
1574
+ );
1523
1575
  }
1524
1576
  };
1577
+
1578
+ // src/websets/monitors.ts
1525
1579
  var WebsetMonitorRunsClient2 = class extends WebsetsBaseClient2 {
1526
- async list(monitorId) {
1527
- return this.request(`/v0/monitors/${monitorId}/runs`, "GET");
1528
- }
1529
- async get(monitorId, id) {
1530
- return this.request(`/v0/monitors/${monitorId}/runs/${id}`, "GET");
1531
- }
1532
- };
1533
- var WebsetMonitorsClient2 = class extends WebsetsBaseClient2 {
1534
- constructor(client) {
1535
- super(client);
1536
- this.runs = new WebsetMonitorRunsClient2(client);
1537
- }
1538
- async create(params) {
1539
- return this.request("/v0/monitors", "POST", { ...params });
1540
- }
1541
- async list(options) {
1542
- const queryParams = { ...this.buildPaginationParams(options), websetId: options?.websetId };
1543
- return this.request("/v0/monitors", "GET", void 0, queryParams);
1544
- }
1545
- async get(id) {
1546
- return this.request(`/v0/monitors/${id}`, "GET");
1547
- }
1548
- async update(id, params) {
1549
- return this.request(`/v0/monitors/${id}`, "PATCH", { ...params });
1550
- }
1551
- async delete(id) {
1552
- return this.request(`/v0/monitors/${id}`, "DELETE");
1553
- }
1554
- /** Iterate through all monitors, handling pagination automatically. */
1555
- async *listAll(options) {
1556
- let cursor = void 0;
1557
- const pageOptions = options ? { ...options } : {};
1558
- while (true) {
1559
- const response = await this.list({ ...pageOptions, cursor });
1560
- for (const monitor of response.data) {
1561
- yield monitor;
1562
- }
1563
- if (!response.hasMore || !response.nextCursor) {
1564
- break;
1565
- }
1566
- cursor = response.nextCursor;
1567
- }
1568
- }
1569
- /** Collect all monitors into an array. */
1570
- async getAll(options) {
1571
- const monitors = [];
1572
- for await (const monitor of this.listAll(options)) {
1573
- monitors.push(monitor);
1574
- }
1575
- return monitors;
1576
- }
1577
- };
1578
- var WebsetWebhooksClient2 = class extends WebsetsBaseClient2 {
1579
- async create(params) {
1580
- return this.request("/v0/webhooks", "POST", { ...params });
1581
- }
1582
- async list(options) {
1583
- const queryParams = this.buildPaginationParams(options);
1584
- return this.request("/v0/webhooks", "GET", void 0, queryParams);
1585
- }
1586
- async get(id) {
1587
- return this.request(`/v0/webhooks/${id}`, "GET");
1588
- }
1589
- async update(id, params) {
1590
- return this.request(`/v0/webhooks/${id}`, "PATCH", { ...params });
1591
- }
1592
- async delete(id) {
1593
- return this.request(`/v0/webhooks/${id}`, "DELETE");
1594
- }
1595
- async listAttempts(id, options) {
1596
- const queryParams = { ...this.buildPaginationParams(options), eventType: options?.eventType, successful: options?.successful };
1597
- return this.request(`/v0/webhooks/${id}/attempts`, "GET", void 0, queryParams);
1598
- }
1599
- };
1600
- var ImportsClient2 = class extends WebsetsBaseClient2 {
1601
- async create(params) {
1602
- return this.request("/v0/imports", "POST", { ...params });
1603
- }
1604
- async list(options) {
1605
- const queryParams = this.buildPaginationParams(options);
1606
- return this.request("/v0/imports", "GET", void 0, queryParams);
1607
- }
1608
- async get(id) {
1609
- return this.request(`/v0/imports/${id}`, "GET");
1610
- }
1611
- async update(id, params) {
1612
- return this.request(`/v0/imports/${id}`, "PATCH", { ...params });
1580
+ /**
1581
+ * List all runs for a Monitor
1582
+ * @param monitorId The ID of the Monitor
1583
+ * @param options Pagination options
1584
+ * @returns The list of Monitor runs
1585
+ */
1586
+ async list(monitorId, options) {
1587
+ const params = this.buildPaginationParams(options);
1588
+ return this.request(
1589
+ `/v0/monitors/${monitorId}/runs`,
1590
+ "GET",
1591
+ void 0,
1592
+ params
1593
+ );
1613
1594
  }
1614
- async delete(id) {
1615
- return this.request(`/v0/imports/${id}`, "DELETE");
1595
+ /**
1596
+ * Get a specific Monitor run
1597
+ * @param monitorId The ID of the Monitor
1598
+ * @param runId The ID of the Monitor run
1599
+ * @returns The Monitor run
1600
+ */
1601
+ async get(monitorId, runId) {
1602
+ return this.request(
1603
+ `/v0/monitors/${monitorId}/runs/${runId}`,
1604
+ "GET"
1605
+ );
1616
1606
  }
1617
1607
  };
1618
- var WebsetsClient2 = class extends WebsetsBaseClient2 {
1608
+ var WebsetMonitorsClient2 = class extends WebsetsBaseClient2 {
1619
1609
  constructor(client) {
1620
1610
  super(client);
1621
- this.items = new WebsetItemsClient2(client);
1622
- this.searches = new WebsetSearchesClient2(client);
1623
- this.enrichments = new WebsetEnrichmentsClient2(client);
1624
- this.events = new EventsClient2(client);
1625
- this.monitors = new WebsetMonitorsClient2(client);
1626
- this.webhooks = new WebsetWebhooksClient2(client);
1627
- this.imports = new ImportsClient2(client);
1611
+ this.runs = new WebsetMonitorRunsClient2(client);
1628
1612
  }
1629
- async create(params, options) {
1630
- return this.request("/v0/websets", "POST", { ...params }, void 0, options?.headers);
1613
+ /**
1614
+ * Create a Monitor
1615
+ * @param params The monitor parameters
1616
+ * @returns The created Monitor
1617
+ */
1618
+ async create(params) {
1619
+ return this.request("/v0/monitors", "POST", params);
1631
1620
  }
1632
- async list(options) {
1633
- const queryParams = { ...this.buildPaginationParams(options), search: options?.search };
1634
- return this.request("/v0/websets", "GET", void 0, queryParams);
1621
+ /**
1622
+ * Get a Monitor by ID
1623
+ * @param id The ID of the Monitor
1624
+ * @returns The Monitor
1625
+ */
1626
+ async get(id) {
1627
+ return this.request(`/v0/monitors/${id}`, "GET");
1635
1628
  }
1636
- async get(id, options) {
1637
- const queryParams = { expand: options?.expand };
1638
- return this.request(`/v0/websets/${id}`, "GET", void 0, queryParams);
1629
+ /**
1630
+ * List all Monitors
1631
+ * @param options Pagination and filtering options
1632
+ * @returns The list of Monitors
1633
+ */
1634
+ async list(options) {
1635
+ const params = {
1636
+ cursor: options?.cursor,
1637
+ limit: options?.limit,
1638
+ websetId: options?.websetId
1639
+ };
1640
+ return this.request(
1641
+ "/v0/monitors",
1642
+ "GET",
1643
+ void 0,
1644
+ params
1645
+ );
1639
1646
  }
1647
+ /**
1648
+ * Update a Monitor
1649
+ * @param id The ID of the Monitor
1650
+ * @param params The monitor update parameters (status, metadata)
1651
+ * @returns The updated Monitor
1652
+ */
1640
1653
  async update(id, params) {
1641
- return this.request(`/v0/websets/${id}`, "POST", { ...params });
1654
+ return this.request(`/v0/monitors/${id}`, "PATCH", params);
1642
1655
  }
1656
+ /**
1657
+ * Delete a Monitor
1658
+ * @param id The ID of the Monitor
1659
+ * @returns The deleted Monitor
1660
+ */
1643
1661
  async delete(id) {
1644
- return this.request(`/v0/websets/${id}`, "DELETE");
1645
- }
1646
- async cancel(id) {
1647
- return this.request(`/v0/websets/${id}/cancel`, "POST");
1648
- }
1649
- async preview(params, options) {
1650
- const queryParams = { search: options?.search };
1651
- return this.request("/v0/websets/preview", "POST", { ...params }, queryParams);
1662
+ return this.request(`/v0/monitors/${id}`, "DELETE");
1652
1663
  }
1653
- /** Iterate through all Websets, handling pagination automatically. */
1664
+ /**
1665
+ * Iterate through all Monitors, handling pagination automatically
1666
+ * @param options Pagination and filtering options
1667
+ * @returns Async generator of Monitors
1668
+ */
1654
1669
  async *listAll(options) {
1655
1670
  let cursor = void 0;
1656
1671
  const pageOptions = options ? { ...options } : {};
1657
1672
  while (true) {
1658
- const response = await this.list({ ...pageOptions, cursor });
1659
- for (const webset of response.data) {
1660
- yield webset;
1673
+ pageOptions.cursor = cursor;
1674
+ const response = await this.list(pageOptions);
1675
+ for (const monitor of response.data) {
1676
+ yield monitor;
1661
1677
  }
1662
1678
  if (!response.hasMore || !response.nextCursor) {
1663
1679
  break;
@@ -1665,404 +1681,372 @@ var WebsetsClient2 = class extends WebsetsBaseClient2 {
1665
1681
  cursor = response.nextCursor;
1666
1682
  }
1667
1683
  }
1668
- /** Collect all Websets into an array. */
1684
+ /**
1685
+ * Collect all Monitors into an array
1686
+ * @param options Pagination and filtering options
1687
+ * @returns Promise resolving to an array of all Monitors
1688
+ */
1669
1689
  async getAll(options) {
1670
- const websets = [];
1671
- for await (const webset of this.listAll(options)) {
1672
- websets.push(webset);
1673
- }
1674
- return websets;
1675
- }
1676
- /** Poll until a Webset reaches idle status. */
1677
- async waitUntilIdle(id, options) {
1678
- let timeout;
1679
- let pollInterval = 1e3;
1680
- let onPoll;
1681
- if (typeof options === "number") {
1682
- timeout = options;
1683
- } else if (options) {
1684
- timeout = options.timeout;
1685
- pollInterval = options.pollInterval || 1e3;
1686
- onPoll = options.onPoll;
1687
- }
1688
- const startTime = Date.now();
1689
- while (true) {
1690
- const webset = await this.get(id);
1691
- if (onPoll) onPoll(webset.status);
1692
- if (webset.status === "idle") return webset;
1693
- if (timeout && Date.now() - startTime > timeout) {
1694
- throw new Error(`Webset ${id} did not reach idle state within ${timeout}ms. Current status: ${webset.status}`);
1695
- }
1696
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
1697
- }
1698
- }
1699
- };
1700
-
1701
- // src/nova/research-client.ts
1702
- var import_zod2 = require("zod");
1703
- var import_zod_to_json_schema2 = require("zod-to-json-schema");
1704
- function zodToJsonSchema2(schema) {
1705
- return (0, import_zod_to_json_schema2.zodToJsonSchema)(schema, { $refStrategy: "none" });
1706
- }
1707
- var ResearchBaseClient2 = class {
1708
- constructor(client) {
1709
- this.client = client;
1710
- }
1711
- /** Make a request to the API, prepending `/research/v1` to the path. */
1712
- async request(endpoint, method = "POST", data, params) {
1713
- return this.client.request(`/research/v1${endpoint}`, method, data, params);
1714
- }
1715
- buildPaginationParams(pagination) {
1716
- const params = {};
1717
- if (!pagination) return params;
1718
- if (pagination.cursor) params.cursor = pagination.cursor;
1719
- if (pagination.limit) params.limit = pagination.limit;
1720
- return params;
1721
- }
1722
- };
1723
- var ResearchClient2 = class extends ResearchBaseClient2 {
1724
- /** List research requests. */
1725
- async list(options) {
1726
- const params = this.buildPaginationParams(options);
1727
- return this.client.request("/research/v1", "GET", void 0, params);
1728
- }
1729
- /** Create a new research request. Defaults model to "exa-research-fast" if not provided. */
1730
- async create(params) {
1731
- let schema = params.outputSchema;
1732
- if (schema instanceof import_zod2.ZodType) {
1733
- schema = zodToJsonSchema2(schema);
1734
- }
1735
- const payload = {
1736
- instructions: params.instructions,
1737
- model: params.model ?? "exa-research-fast"
1738
- };
1739
- if (schema) {
1740
- payload.outputSchema = schema;
1741
- }
1742
- return this.client.request("/research/v1", "POST", payload, void 0);
1743
- }
1744
- /** Get a research request by ID. */
1745
- async get(researchId, options) {
1746
- const params = {};
1747
- if (options?.events !== void 0) params.events = options.events.toString();
1748
- return this.client.request(`/research/v1/${researchId}`, "GET", void 0, params);
1749
- }
1750
- /** Poll a research request until it reaches a terminal state (completed, failed, or canceled). */
1751
- async pollUntilFinished(researchId, options) {
1752
- const pollInterval = options?.pollInterval ?? 1e3;
1753
- const timeoutMs = options?.timeoutMs ?? 10 * 60 * 1e3;
1754
- const maxConsecutiveFailures = 5;
1755
- const startTime = Date.now();
1756
- let consecutiveFailures = 0;
1757
- while (true) {
1758
- try {
1759
- const research = await this.get(researchId, { events: options?.events });
1760
- consecutiveFailures = 0;
1761
- if (research.status === "completed" || research.status === "failed" || research.status === "canceled") {
1762
- return research;
1763
- }
1764
- } catch (err) {
1765
- consecutiveFailures += 1;
1766
- if (consecutiveFailures >= maxConsecutiveFailures) {
1767
- throw new Error(`Polling failed ${maxConsecutiveFailures} times in a row for research ${researchId}: ${err}`);
1768
- }
1769
- }
1770
- if (Date.now() - startTime > timeoutMs) {
1771
- throw new Error(`Polling timeout: Research ${researchId} did not complete within ${timeoutMs}ms`);
1772
- }
1773
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
1690
+ const monitors = [];
1691
+ for await (const monitor of this.listAll(options)) {
1692
+ monitors.push(monitor);
1774
1693
  }
1694
+ return monitors;
1775
1695
  }
1776
1696
  };
1777
1697
 
1778
- // src/nova/client.ts
1779
- function isRecord(value) {
1780
- return value != null && typeof value === "object" && !Array.isArray(value);
1781
- }
1782
- var ExaError2 = class extends Error {
1783
- constructor(message, statusCode, timestamp, path, details) {
1784
- super(message);
1785
- this.name = "ExaError";
1786
- this.statusCode = statusCode;
1787
- this.timestamp = timestamp;
1788
- this.path = path;
1789
- this.details = details;
1790
- }
1791
- };
1792
- var CONTENTS_FIELDS = /* @__PURE__ */ new Set(["text", "highlights", "summary", "subpages", "subpageTarget", "extras", "livecrawl", "livecrawlTimeout", "maxAgeHours", "filterEmptyResults", "context"]);
1793
- var DEFAULT_MAX_CHARACTERS = 1e4;
1794
- var Exa2 = class {
1795
- constructor(apiKey, baseURL = "https://api.exa.ai") {
1796
- this.baseURL = baseURL;
1797
- if (!apiKey) {
1798
- apiKey = typeof process !== "undefined" ? process.env?.EXA_API_KEY : void 0;
1799
- if (!apiKey) {
1800
- throw new ExaError2(
1801
- "API key must be provided as an argument or as an environment variable (EXA_API_KEY)",
1802
- 401
1803
- );
1804
- }
1805
- }
1806
- this.headers = {
1807
- "x-api-key": apiKey,
1808
- "Content-Type": "application/json"
1809
- };
1810
- this.websets = new WebsetsClient2(this);
1811
- this.research = new ResearchClient2(this);
1812
- }
1813
- /** Make a request to the Exa API. Used by sub-clients and available for direct use. */
1814
- async request(endpoint, method, body, params, headers) {
1815
- const url = this.buildRequestUrl(endpoint, params);
1816
- const normalizedBody = this.normalizeCategoryInBody(body);
1817
- const combinedHeaders = headers ? { ...this.headers, ...headers } : this.headers;
1818
- const response = await fetch(url, {
1819
- method,
1820
- headers: combinedHeaders,
1821
- body: normalizedBody ? JSON.stringify(normalizedBody) : void 0
1822
- });
1823
- if (!response.ok) {
1824
- throw await this.toExaError(response, endpoint);
1825
- }
1826
- return await response.json();
1698
+ // src/websets/searches.ts
1699
+ var WebsetSearchesClient2 = class extends WebsetsBaseClient2 {
1700
+ /**
1701
+ * Create a new Search for the Webset
1702
+ * @param websetId The ID of the Webset
1703
+ * @param params The search parameters
1704
+ * @returns The created Webset Search
1705
+ */
1706
+ async create(websetId, params, options) {
1707
+ return this.request(
1708
+ `/v0/websets/${websetId}/searches`,
1709
+ "POST",
1710
+ params,
1711
+ void 0,
1712
+ options?.headers
1713
+ );
1827
1714
  }
1828
- /** Make a raw request returning the Response object directly. */
1829
- async rawRequest(endpoint, method = "POST", body, params) {
1830
- const url = this.buildRequestUrl(endpoint, params);
1831
- const normalizedBody = this.normalizeCategoryInBody(body);
1832
- return fetch(url, {
1833
- method,
1834
- headers: this.headers,
1835
- body: normalizedBody ? JSON.stringify(normalizedBody) : void 0
1836
- });
1715
+ /**
1716
+ * Get a Search by ID
1717
+ * @param websetId The ID of the Webset
1718
+ * @param id The ID of the Search
1719
+ * @returns The Webset Search
1720
+ */
1721
+ async get(websetId, id) {
1722
+ return this.request(
1723
+ `/v0/websets/${websetId}/searches/${id}`,
1724
+ "GET"
1725
+ );
1837
1726
  }
1838
- /** Normalize category values to underscore form. */
1839
- normalizeCategoryInBody(body) {
1840
- if (body == null || typeof body.category !== "string") {
1841
- return body;
1842
- }
1843
- return { ...body, category: body.category.replace(/ /g, "_") };
1727
+ /**
1728
+ * Cancel a running Search
1729
+ * @param websetId The ID of the Webset
1730
+ * @param id The ID of the Search
1731
+ * @returns The canceled Webset Search
1732
+ */
1733
+ async cancel(websetId, id) {
1734
+ return this.request(
1735
+ `/v0/websets/${websetId}/searches/${id}/cancel`,
1736
+ "POST"
1737
+ );
1844
1738
  }
1845
- buildRequestUrl(endpoint, params) {
1846
- let url = `${this.baseURL}${endpoint}`;
1847
- if (params == null || Object.keys(params).length === 0) {
1848
- return url;
1849
- }
1850
- const searchParams = new URLSearchParams();
1851
- for (const [key, value] of Object.entries(params)) {
1852
- if (Array.isArray(value)) {
1853
- for (const item of value) {
1854
- searchParams.append(key, item);
1855
- }
1856
- } else if (value !== void 0) {
1857
- searchParams.append(key, String(value));
1858
- }
1859
- }
1860
- url += `?${searchParams.toString()}`;
1861
- return url;
1739
+ };
1740
+
1741
+ // src/websets/webhooks.ts
1742
+ var WebsetWebhooksClient2 = class extends WebsetsBaseClient2 {
1743
+ /**
1744
+ * Create a Webhook
1745
+ * @param params The webhook parameters
1746
+ * @returns The created Webhook
1747
+ */
1748
+ async create(params) {
1749
+ return this.request("/v0/webhooks", "POST", params);
1862
1750
  }
1863
- tryParseJsonRecord(text) {
1864
- if (text.length === 0) {
1865
- return null;
1866
- }
1867
- try {
1868
- const parsed = JSON.parse(text);
1869
- return isRecord(parsed) ? parsed : null;
1870
- } catch {
1871
- return null;
1872
- }
1751
+ /**
1752
+ * Get a Webhook by ID
1753
+ * @param id The ID of the Webhook
1754
+ * @returns The Webhook
1755
+ */
1756
+ async get(id) {
1757
+ return this.request(`/v0/webhooks/${id}`, "GET");
1873
1758
  }
1874
- async toExaError(response, endpoint) {
1875
- const text = await response.text();
1876
- const parsed = this.tryParseJsonRecord(text);
1877
- const statusCode = parsed != null && typeof parsed.statusCode === "number" ? parsed.statusCode : response.status;
1878
- const timestamp = parsed != null && typeof parsed.timestamp === "string" ? parsed.timestamp : void 0;
1879
- const path = parsed != null && typeof parsed.path === "string" ? parsed.path : endpoint;
1880
- const errorMessage = parsed != null && typeof parsed.error === "string" ? parsed.error : void 0;
1881
- const detailMessage = parsed != null && typeof parsed.message === "string" ? parsed.message : void 0;
1882
- let message;
1883
- if (errorMessage != null && detailMessage != null) {
1884
- message = `${errorMessage}. ${detailMessage}`;
1885
- } else if (errorMessage != null) {
1886
- message = errorMessage;
1887
- } else if (detailMessage != null) {
1888
- message = detailMessage;
1889
- } else if (text.length > 0) {
1890
- message = text;
1891
- } else {
1892
- message = `Exa API error ${response.status}`;
1893
- }
1894
- return new ExaError2(message, statusCode, timestamp, path, parsed ?? text);
1759
+ /**
1760
+ * List all Webhooks
1761
+ * @param options Pagination options
1762
+ * @returns The list of Webhooks
1763
+ */
1764
+ async list(options) {
1765
+ const params = this.buildPaginationParams(options);
1766
+ return this.request(
1767
+ "/v0/webhooks",
1768
+ "GET",
1769
+ void 0,
1770
+ params
1771
+ );
1895
1772
  }
1896
- parseAnswerStreamLine(line) {
1897
- if (!line.startsWith("data:")) {
1898
- return null;
1899
- }
1900
- const jsonStr = line.replace(/^data:\s*/, "").trim();
1901
- if (jsonStr.length === 0 || jsonStr === "[DONE]") {
1902
- return null;
1903
- }
1904
- let parsedChunk;
1905
- try {
1906
- parsedChunk = JSON.parse(jsonStr);
1907
- } catch {
1908
- return null;
1909
- }
1910
- if (!isRecord(parsedChunk)) {
1911
- return null;
1912
- }
1913
- let content;
1914
- const choices = parsedChunk.choices;
1915
- if (Array.isArray(choices) && choices.length > 0 && isRecord(choices[0])) {
1916
- const delta = choices[0].delta;
1917
- if (isRecord(delta) && typeof delta.content === "string") {
1918
- content = delta.content;
1919
- }
1920
- }
1921
- let citations;
1922
- if (Array.isArray(parsedChunk.citations)) {
1923
- const normalized = [];
1924
- for (const citation of parsedChunk.citations) {
1925
- if (!isRecord(citation)) {
1926
- continue;
1927
- }
1928
- const id = typeof citation.id === "string" ? citation.id : void 0;
1929
- const url = typeof citation.url === "string" ? citation.url : void 0;
1930
- const title = typeof citation.title === "string" ? citation.title : void 0;
1931
- const publishedDate = typeof citation.publishedDate === "string" ? citation.publishedDate : void 0;
1932
- const author = typeof citation.author === "string" ? citation.author : void 0;
1933
- const text = typeof citation.text === "string" ? citation.text : void 0;
1934
- normalized.push({
1935
- ...id != null ? { id } : {},
1936
- ...url != null ? { url } : {},
1937
- ...title != null ? { title } : {},
1938
- ...publishedDate != null ? { publishedDate } : {},
1939
- ...author != null ? { author } : {},
1940
- ...text != null ? { text } : {}
1941
- });
1773
+ /**
1774
+ * Iterate through all Webhooks, handling pagination automatically
1775
+ * @param options Pagination options
1776
+ * @returns Async generator of Webhooks
1777
+ */
1778
+ async *listAll(options) {
1779
+ let cursor = void 0;
1780
+ const pageOptions = options ? { ...options } : {};
1781
+ while (true) {
1782
+ pageOptions.cursor = cursor;
1783
+ const response = await this.list(pageOptions);
1784
+ for (const webhook of response.data) {
1785
+ yield webhook;
1942
1786
  }
1943
- if (normalized.length > 0) {
1944
- citations = normalized;
1787
+ if (!response.hasMore || !response.nextCursor) {
1788
+ break;
1945
1789
  }
1790
+ cursor = response.nextCursor;
1946
1791
  }
1947
- if (content == null && (citations == null || citations.length === 0)) {
1948
- return null;
1792
+ }
1793
+ /**
1794
+ * Collect all Webhooks into an array
1795
+ * @param options Pagination options
1796
+ * @returns Promise resolving to an array of all Webhooks
1797
+ */
1798
+ async getAll(options) {
1799
+ const webhooks = [];
1800
+ for await (const webhook of this.listAll(options)) {
1801
+ webhooks.push(webhook);
1949
1802
  }
1950
- return {
1951
- ...content != null ? { content } : {},
1952
- ...citations != null ? { citations } : {}
1803
+ return webhooks;
1804
+ }
1805
+ /**
1806
+ * Update a Webhook
1807
+ * @param id The ID of the Webhook
1808
+ * @param params The webhook update parameters (events, metadata, url)
1809
+ * @returns The updated Webhook
1810
+ */
1811
+ async update(id, params) {
1812
+ return this.request(`/v0/webhooks/${id}`, "PATCH", params);
1813
+ }
1814
+ /**
1815
+ * Delete a Webhook
1816
+ * @param id The ID of the Webhook
1817
+ * @returns The deleted Webhook
1818
+ */
1819
+ async delete(id) {
1820
+ return this.request(`/v0/webhooks/${id}`, "DELETE");
1821
+ }
1822
+ /**
1823
+ * List all attempts for a Webhook
1824
+ * @param id The ID of the Webhook
1825
+ * @param options Pagination and filtering options
1826
+ * @returns The list of Webhook attempts
1827
+ */
1828
+ async listAttempts(id, options) {
1829
+ const params = {
1830
+ cursor: options?.cursor,
1831
+ limit: options?.limit,
1832
+ eventType: options?.eventType,
1833
+ successful: options?.successful
1953
1834
  };
1835
+ return this.request(
1836
+ `/v0/webhooks/${id}/attempts`,
1837
+ "GET",
1838
+ void 0,
1839
+ params
1840
+ );
1954
1841
  }
1955
- /** Separate content-specific options from search/filter options. */
1956
- extractContentsOptions(options) {
1957
- const contentsOptions = {};
1958
- const restOptions = {};
1959
- let hasContentField = false;
1960
- for (const [key, value] of Object.entries(options)) {
1961
- if (CONTENTS_FIELDS.has(key)) {
1962
- contentsOptions[key] = value;
1963
- hasContentField = true;
1964
- } else {
1965
- restOptions[key] = value;
1842
+ /**
1843
+ * Iterate through all attempts for a Webhook, handling pagination automatically
1844
+ * @param id The ID of the Webhook
1845
+ * @param options Pagination and filtering options
1846
+ * @returns Async generator of Webhook attempts
1847
+ */
1848
+ async *listAllAttempts(id, options) {
1849
+ let cursor = void 0;
1850
+ const pageOptions = options ? { ...options } : {};
1851
+ while (true) {
1852
+ pageOptions.cursor = cursor;
1853
+ const response = await this.listAttempts(id, pageOptions);
1854
+ for (const attempt of response.data) {
1855
+ yield attempt;
1966
1856
  }
1857
+ if (!response.hasMore || !response.nextCursor) {
1858
+ break;
1859
+ }
1860
+ cursor = response.nextCursor;
1967
1861
  }
1968
- if (!hasContentField) {
1969
- contentsOptions.text = { maxCharacters: DEFAULT_MAX_CHARACTERS };
1970
- }
1971
- return { contentsOptions, restOptions };
1972
1862
  }
1973
- search(query, options) {
1974
- let body;
1975
- if (options === void 0 || !("contents" in options)) {
1976
- body = { query, ...options, contents: { text: { maxCharacters: DEFAULT_MAX_CHARACTERS } } };
1977
- } else if (options.contents === false || options.contents === null || options.contents === void 0) {
1978
- const { contents, ...restOptions } = options;
1979
- body = { query, ...restOptions };
1980
- } else {
1981
- body = { query, ...options };
1863
+ /**
1864
+ * Collect all attempts for a Webhook into an array
1865
+ * @param id The ID of the Webhook
1866
+ * @param options Pagination and filtering options
1867
+ * @returns Promise resolving to an array of all Webhook attempts
1868
+ */
1869
+ async getAllAttempts(id, options) {
1870
+ const attempts = [];
1871
+ for await (const attempt of this.listAllAttempts(id, options)) {
1872
+ attempts.push(attempt);
1982
1873
  }
1983
- return this.request("/search", "POST", body);
1874
+ return attempts;
1984
1875
  }
1985
- findSimilar(url, options) {
1986
- let body;
1987
- if (options === void 0 || !("contents" in options)) {
1988
- body = { url, ...options, contents: { text: { maxCharacters: DEFAULT_MAX_CHARACTERS } } };
1989
- } else if (options.contents === false || options.contents === null || options.contents === void 0) {
1990
- const { contents, ...restOptions } = options;
1991
- body = { url, ...restOptions };
1992
- } else {
1993
- body = { url, ...options };
1994
- }
1995
- return this.request("/findSimilar", "POST", body);
1876
+ };
1877
+
1878
+ // src/websets/client.ts
1879
+ var WebsetsClient2 = class extends WebsetsBaseClient2 {
1880
+ /**
1881
+ * Initialize a new Websets client
1882
+ * @param client The Exa client instance
1883
+ */
1884
+ constructor(client) {
1885
+ super(client);
1886
+ this.events = new EventsClient2(client);
1887
+ this.imports = new ImportsClient2(client);
1888
+ this.items = new WebsetItemsClient2(client);
1889
+ this.searches = new WebsetSearchesClient2(client);
1890
+ this.enrichments = new WebsetEnrichmentsClient2(client);
1891
+ this.monitors = new WebsetMonitorsClient2(client);
1892
+ this.webhooks = new WebsetWebhooksClient2(client);
1996
1893
  }
1997
- getContents(urls, options) {
1998
- return this.request("/contents", "POST", { urls, ...options });
1894
+ /**
1895
+ * Create a new Webset
1896
+ * @param params The Webset creation parameters
1897
+ * @returns The created Webset
1898
+ */
1899
+ async create(params, options) {
1900
+ return this.request(
1901
+ "/v0/websets",
1902
+ "POST",
1903
+ params,
1904
+ void 0,
1905
+ options?.headers
1906
+ );
1999
1907
  }
2000
- answer(query, options) {
2001
- if (options?.stream) {
2002
- throw new ExaError2("For streaming responses, please use streamAnswer() instead:\n\nfor await (const chunk of exa.streamAnswer(query)) {\n // Handle chunks\n}", 400);
1908
+ /**
1909
+ * Preview a webset
1910
+ * @param params The preview parameters
1911
+ * @param options Optional parameters. Search = true allows you to retrieve a preview set of items that could be returned by the webset.
1912
+ * @returns The preview response showing how the query will be decomposed
1913
+ */
1914
+ async preview(params, options) {
1915
+ const queryParams = {};
1916
+ if (options?.search !== void 0) {
1917
+ queryParams.search = options.search;
2003
1918
  }
2004
- return this.request("/answer", "POST", { query, model: "exa", stream: false, text: false, ...options });
1919
+ return this.request(
1920
+ "/v0/websets/preview",
1921
+ "POST",
1922
+ params,
1923
+ queryParams
1924
+ );
2005
1925
  }
2006
- async *streamAnswer(query, options) {
2007
- const response = await this.rawRequest("/answer", "POST", { query, model: "exa", text: false, ...options, stream: true });
2008
- if (!response.ok) {
2009
- throw await this.toExaError(response, "/answer");
2010
- }
2011
- const reader = response.body?.getReader();
2012
- if (!reader) {
2013
- throw new ExaError2("No response body available for streaming.", 500, (/* @__PURE__ */ new Date()).toISOString(), "/answer");
1926
+ /**
1927
+ * Get a Webset by ID
1928
+ * @param id The ID of the Webset
1929
+ * @param expand Optional array of relations to expand
1930
+ * @returns The Webset
1931
+ */
1932
+ async get(id, expand) {
1933
+ const params = {};
1934
+ if (expand) {
1935
+ params.expand = expand;
2014
1936
  }
2015
- const decoder = new TextDecoder();
2016
- let buffer = "";
2017
- try {
2018
- while (true) {
2019
- const { done, value } = await reader.read();
2020
- if (done) break;
2021
- buffer += decoder.decode(value, { stream: true });
2022
- const lines = buffer.split("\n");
2023
- buffer = lines.pop() ?? "";
2024
- for (const line of lines) {
2025
- const chunk = this.parseAnswerStreamLine(line);
2026
- if (chunk != null) {
2027
- yield chunk;
2028
- }
2029
- }
1937
+ return this.request(
1938
+ `/v0/websets/${id}`,
1939
+ "GET",
1940
+ void 0,
1941
+ params
1942
+ );
1943
+ }
1944
+ /**
1945
+ * List all Websets
1946
+ * @param options Pagination options (filtering by status is not supported by API)
1947
+ * @returns The list of Websets
1948
+ */
1949
+ async list(options) {
1950
+ const params = this.buildPaginationParams(options);
1951
+ return this.request(
1952
+ "/v0/websets",
1953
+ "GET",
1954
+ void 0,
1955
+ params
1956
+ );
1957
+ }
1958
+ /**
1959
+ * Iterate through all Websets, handling pagination automatically
1960
+ * @param options Pagination options
1961
+ * @returns Async generator of Websets
1962
+ */
1963
+ async *listAll(options) {
1964
+ let cursor = void 0;
1965
+ const pageOptions = options ? { ...options } : {};
1966
+ while (true) {
1967
+ pageOptions.cursor = cursor;
1968
+ const response = await this.list(pageOptions);
1969
+ for (const webset of response.data) {
1970
+ yield webset;
2030
1971
  }
2031
- const trailingChunk = this.parseAnswerStreamLine(buffer);
2032
- if (trailingChunk != null) {
2033
- yield trailingChunk;
1972
+ if (!response.hasMore || !response.nextCursor) {
1973
+ break;
2034
1974
  }
2035
- } finally {
2036
- reader.releaseLock();
1975
+ cursor = response.nextCursor;
2037
1976
  }
2038
1977
  }
2039
1978
  /**
2040
- * @deprecated Use `search()` instead. The search method now returns text contents by default.
2041
- * Search with contents. Extracts content fields (text, highlights, summary, etc.) into a `contents` wrapper.
1979
+ * Collect all Websets into an array
1980
+ * @param options Pagination options
1981
+ * @returns Promise resolving to an array of all Websets
2042
1982
  */
2043
- async searchAndContents(query, options) {
2044
- if (options === void 0) {
2045
- return this.request("/search", "POST", {
2046
- query,
2047
- contents: { text: { maxCharacters: DEFAULT_MAX_CHARACTERS } }
2048
- });
1983
+ async getAll(options) {
1984
+ const websets = [];
1985
+ for await (const webset of this.listAll(options)) {
1986
+ websets.push(webset);
2049
1987
  }
2050
- const { contentsOptions, restOptions } = this.extractContentsOptions(options);
2051
- return this.request("/search", "POST", { query, contents: contentsOptions, ...restOptions });
1988
+ return websets;
2052
1989
  }
2053
1990
  /**
2054
- * @deprecated Use `findSimilar()` instead. The findSimilar method now returns text contents by default.
2055
- * Find similar with contents. Extracts content fields into a `contents` wrapper.
1991
+ * Update a Webset
1992
+ * @param id The ID of the Webset
1993
+ * @param params The Webset update parameters
1994
+ * @returns The updated Webset
2056
1995
  */
2057
- async findSimilarAndContents(url, options) {
2058
- if (options === void 0) {
2059
- return this.request("/findSimilar", "POST", {
2060
- url,
2061
- contents: { text: { maxCharacters: DEFAULT_MAX_CHARACTERS } }
2062
- });
1996
+ async update(id, params) {
1997
+ return this.request(`/v0/websets/${id}`, "POST", params);
1998
+ }
1999
+ /**
2000
+ * Delete a Webset
2001
+ * @param id The ID of the Webset
2002
+ * @returns The deleted Webset
2003
+ */
2004
+ async delete(id) {
2005
+ return this.request(`/v0/websets/${id}`, "DELETE");
2006
+ }
2007
+ /**
2008
+ * Cancel a running Webset
2009
+ * @param id The ID or external ID of the Webset
2010
+ * @returns The canceled Webset (as returned by the API)
2011
+ */
2012
+ async cancel(id) {
2013
+ return this.request(`/v0/websets/${id}/cancel`, "POST");
2014
+ }
2015
+ /**
2016
+ * Wait until a Webset is idle
2017
+ * @param id The ID of the Webset
2018
+ * @param options Configuration options for timeout and polling
2019
+ * @returns The Webset once it becomes idle
2020
+ * @throws Error if the Webset does not become idle within the timeout
2021
+ */
2022
+ async waitUntilIdle(id, options) {
2023
+ let timeout;
2024
+ let pollInterval = 1e3;
2025
+ let onPoll;
2026
+ if (typeof options === "number") {
2027
+ timeout = options;
2028
+ } else if (options) {
2029
+ timeout = options.timeout;
2030
+ pollInterval = options.pollInterval || 1e3;
2031
+ onPoll = options.onPoll;
2032
+ }
2033
+ const startTime = Date.now();
2034
+ while (true) {
2035
+ const webset = await this.get(id);
2036
+ if (onPoll) {
2037
+ onPoll(webset.status);
2038
+ }
2039
+ if (webset.status === "idle" /* idle */) {
2040
+ return webset;
2041
+ }
2042
+ if (timeout && Date.now() - startTime > timeout) {
2043
+ throw new ExaError(
2044
+ `Webset ${id} did not reach idle state within ${timeout}ms. Current status: ${webset.status}`,
2045
+ 408 /* RequestTimeout */
2046
+ );
2047
+ }
2048
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
2063
2049
  }
2064
- const { contentsOptions, restOptions } = this.extractContentsOptions(options);
2065
- return this.request("/findSimilar", "POST", { url, contents: contentsOptions, ...restOptions });
2066
2050
  }
2067
2051
  };
2068
2052
 
@@ -2098,7 +2082,7 @@ var Exa3 = class {
2098
2082
  if (typeof summary === "object" && summary !== null && "schema" in summary && summary.schema && isZodSchema(summary.schema)) {
2099
2083
  contentsOptions.summary = {
2100
2084
  ...summary,
2101
- schema: zodToJsonSchema(summary.schema)
2085
+ schema: zodToJsonSchema2(summary.schema)
2102
2086
  };
2103
2087
  } else {
2104
2088
  contentsOptions.summary = summary;
@@ -2139,8 +2123,8 @@ var Exa3 = class {
2139
2123
  "Content-Type": "application/json",
2140
2124
  "User-Agent": `exa-node ${package_default.version}`
2141
2125
  });
2142
- this.websets = new WebsetsClient(this);
2143
- this.research = new ResearchClient(this);
2126
+ this.websets = new WebsetsClient2(this);
2127
+ this.research = new ResearchClient2(this);
2144
2128
  }
2145
2129
  /**
2146
2130
  * Makes a request to the Exa API.
@@ -2352,7 +2336,7 @@ var Exa3 = class {
2352
2336
  }
2353
2337
  let outputSchema = options?.outputSchema;
2354
2338
  if (outputSchema && isZodSchema(outputSchema)) {
2355
- outputSchema = zodToJsonSchema(outputSchema);
2339
+ outputSchema = zodToJsonSchema2(outputSchema);
2356
2340
  }
2357
2341
  const requestBody = {
2358
2342
  query,
@@ -2368,7 +2352,7 @@ var Exa3 = class {
2368
2352
  async *streamAnswer(query, options) {
2369
2353
  let outputSchema = options?.outputSchema;
2370
2354
  if (outputSchema && isZodSchema(outputSchema)) {
2371
- outputSchema = zodToJsonSchema(outputSchema);
2355
+ outputSchema = zodToJsonSchema2(outputSchema);
2372
2356
  }
2373
2357
  const body = {
2374
2358
  query,