exa-js 2.5.1-beta.0 → 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.0",
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;
354
203
  }
355
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);
210
+ }
211
+ return items;
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,645 +292,833 @@ 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 || {});
697
-
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
- );
707
- }
708
- let csvBuffer;
709
- if (typeof csv === "string") {
710
- csvBuffer = Buffer.from(csv, "utf8");
711
- } else if (Buffer.isBuffer(csv)) {
712
- csvBuffer = csv;
713
- } else {
714
- throw new ExaError(
715
- "Invalid CSV data input. Must be string or Buffer",
716
- 400 /* BadRequest */
717
- );
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);
718
460
  }
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
- );
461
+ const payload = {
462
+ instructions: params.instructions,
463
+ model: params.model ?? "exa-research-fast"
464
+ };
465
+ if (schema) {
466
+ payload.outputSchema = schema;
729
467
  }
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
- );
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));
735
500
  }
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
- );
750
- 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();
501
+ }
502
+ };
503
+
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) {
757
526
  throw new ExaError(
758
- `Upload failed: ${uploadResponse.status} ${uploadResponse.statusText}. ${errorText}`,
759
- 400 /* BadRequest */
527
+ "API key must be provided as an argument or as an environment variable (EXA_API_KEY)",
528
+ 401
760
529
  );
761
530
  }
762
- } catch (error) {
763
- if (error instanceof ExaError) {
764
- throw error;
765
- }
766
- throw new ExaError(
767
- `Failed to upload CSV data: ${error.message}`,
768
- 400 /* BadRequest */
769
- );
770
531
  }
771
- return importResponse;
772
- }
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");
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);
780
538
  }
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
- );
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();
794
553
  }
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);
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
+ });
803
563
  }
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");
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, "_") };
811
570
  }
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);
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));
828
584
  }
829
- if (importItem.status === "completed" /* completed */) {
830
- return importItem;
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;
617
+ } else {
618
+ message = `Exa API error ${response.status}`;
619
+ }
620
+ return new ExaError(message, statusCode, timestamp, path, parsed ?? text);
621
+ }
622
+ parseAnswerStreamLine(line) {
623
+ if (!line.startsWith("data:")) {
624
+ return null;
625
+ }
626
+ const jsonStr = line.replace(/^data:\s*/, "").trim();
627
+ if (jsonStr.length === 0 || jsonStr === "[DONE]") {
628
+ return null;
629
+ }
630
+ let parsedChunk;
631
+ try {
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;
831
645
  }
832
- if (importItem.status === "failed" /* failed */) {
833
- throw new ExaError(
834
- `Import ${id} failed: ${importItem.failedMessage || "Unknown error"}`,
835
- 400 /* BadRequest */
836
- );
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
+ });
837
668
  }
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
- );
669
+ if (normalized.length > 0) {
670
+ citations = normalized;
843
671
  }
844
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
845
672
  }
673
+ if (content == null && (citations == null || citations.length === 0)) {
674
+ return null;
675
+ }
676
+ return {
677
+ ...content != null ? { content } : {},
678
+ ...citations != null ? { citations } : {}
679
+ };
846
680
  }
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;
860
- }
861
- if (!response.hasMore || !response.nextCursor) {
862
- break;
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;
863
692
  }
864
- cursor = response.nextCursor;
865
693
  }
694
+ if (!hasContentField) {
695
+ contentsOptions.text = { maxCharacters: DEFAULT_MAX_CHARACTERS };
696
+ }
697
+ return { contentsOptions, restOptions };
866
698
  }
867
- /**
868
- * Collect all Imports into an array
869
- * @param options Pagination options
870
- * @returns Promise resolving to an array of all Imports
871
- */
872
- async getAll(options) {
873
- const imports = [];
874
- for await (const importItem of this.listAll(options)) {
875
- imports.push(importItem);
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 };
876
708
  }
877
- return imports;
709
+ return this.request("/search", "POST", body);
878
710
  }
879
- };
880
-
881
- // src/websets/items.ts
882
- var WebsetItemsClient = class extends WebsetsBaseClient {
883
- /**
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
888
- */
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
899
- );
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);
900
722
  }
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;
723
+ getContents(urls, options) {
724
+ return this.request("/contents", "POST", { urls, ...options });
725
+ }
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);
729
+ }
730
+ return this.request("/answer", "POST", { query, model: "exa", stream: false, text: false, ...options });
731
+ }
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
+ }
915
756
  }
916
- if (!response.hasMore || !response.nextCursor) {
917
- break;
757
+ const trailingChunk = this.parseAnswerStreamLine(buffer);
758
+ if (trailingChunk != null) {
759
+ yield trailingChunk;
918
760
  }
919
- cursor = response.nextCursor;
761
+ } finally {
762
+ reader.releaseLock();
920
763
  }
921
764
  }
922
765
  /**
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
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.
927
768
  */
928
- async getAll(websetId, options) {
929
- const items = [];
930
- for await (const item of this.listAll(websetId, options)) {
931
- items.push(item);
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
+ });
932
775
  }
933
- return items;
776
+ const { contentsOptions, restOptions } = this.extractContentsOptions(options);
777
+ return this.request("/search", "POST", { query, contents: contentsOptions, ...restOptions });
934
778
  }
935
779
  /**
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
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.
940
782
  */
941
- async get(websetId, id) {
942
- return this.request(
943
- `/v0/websets/${websetId}/items/${id}`,
944
- "GET"
945
- );
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;
946
824
  }
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"
825
+ async request(endpoint, method = "POST", data, params) {
826
+ return this.client.request(
827
+ `/research/v1${endpoint}`,
828
+ method,
829
+ data,
830
+ params
957
831
  );
958
832
  }
959
- };
960
-
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,
833
+ async rawRequest(endpoint, method = "POST", data, params) {
834
+ return this.client.rawRequest(
835
+ `/research/v1${endpoint}`,
836
+ method,
837
+ data,
975
838
  params
976
839
  );
977
840
  }
978
- /**
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
983
- */
984
- async get(monitorId, runId) {
985
- return this.request(
986
- `/v0/monitors/${monitorId}/runs/${runId}`,
987
- "GET"
988
- );
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;
989
847
  }
990
848
  };
991
- var WebsetMonitorsClient = class extends WebsetsBaseClient {
849
+
850
+ // src/research/client.ts
851
+ var ResearchClient2 = class extends ResearchBaseClient2 {
992
852
  constructor(client) {
993
853
  super(client);
994
- this.runs = new WebsetMonitorRunsClient(client);
995
854
  }
996
- /**
997
- * Create a Monitor
998
- * @param params The monitor parameters
999
- * @returns The created Monitor
1000
- */
1001
855
  async create(params) {
1002
- return this.request("/v0/monitors", "POST", 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;
867
+ }
868
+ return this.request("", "POST", payload);
1003
869
  }
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");
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
+ );
936
+ }
1011
937
  }
1012
- /**
1013
- * List all Monitors
1014
- * @param options Pagination and filtering options
1015
- * @returns The list of Monitors
1016
- */
1017
938
  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
1028
- );
939
+ const params = this.buildPaginationParams(options);
940
+ return this.request("", "GET", void 0, params);
1029
941
  }
1030
- /**
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);
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
+ }
1038
972
  }
973
+ };
974
+
975
+ // src/websets/base.ts
976
+ var WebsetsBaseClient2 = class {
1039
977
  /**
1040
- * Delete a Monitor
1041
- * @param id The ID of the Monitor
1042
- * @returns The deleted Monitor
978
+ * Initialize a new Websets base client
979
+ * @param client The Exa client instance
1043
980
  */
1044
- async delete(id) {
1045
- return this.request(`/v0/monitors/${id}`, "DELETE");
981
+ constructor(client) {
982
+ this.client = client;
1046
983
  }
1047
984
  /**
1048
- * Iterate through all Monitors, handling pagination automatically
1049
- * @param options Pagination and filtering options
1050
- * @returns Async generator 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
1051
992
  */
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
- }
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
1000
+ );
1066
1001
  }
1067
1002
  /**
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
1048
+ */
1049
+ async delete(websetId, id) {
1050
+ return this.request(
1051
+ `/v0/websets/${websetId}/enrichments/${id}`,
1052
+ "DELETE"
1053
+ );
1054
+ }
1055
+ /**
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
1061
+ */
1062
+ async update(websetId, id, params) {
1063
+ return this.request(
1064
+ `/v0/websets/${websetId}/enrichments/${id}`,
1065
+ "PATCH",
1066
+ params
1067
+ );
1068
+ }
1069
+ /**
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
1115
1074
  */
1116
1075
  async cancel(websetId, id) {
1117
1076
  return this.request(
1118
- `/v0/websets/${websetId}/searches/${id}/cancel`,
1077
+ `/v0/websets/${websetId}/enrichments/${id}/cancel`,
1119
1078
  "POST"
1120
1079
  );
1121
1080
  }
1122
1081
  };
1123
1082
 
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
- }
1083
+ // src/websets/events.ts
1084
+ var EventsClient2 = class extends WebsetsBaseClient2 {
1134
1085
  /**
1135
- * Get a Webhook by ID
1136
- * @param id The ID of the Webhook
1137
- * @returns The Webhook
1086
+ * Initialize a new Events client
1087
+ * @param client The Exa client instance
1138
1088
  */
1139
- async get(id) {
1140
- return this.request(`/v0/webhooks/${id}`, "GET");
1089
+ constructor(client) {
1090
+ super(client);
1141
1091
  }
1142
1092
  /**
1143
- * List all Webhooks
1144
- * @param options Pagination options
1145
- * @returns The list of Webhooks
1093
+ * List all Events
1094
+ * @param options Optional filtering and pagination options
1095
+ * @returns The list of Events
1146
1096
  */
1147
1097
  async list(options) {
1148
- const params = this.buildPaginationParams(options);
1098
+ const params = {
1099
+ cursor: options?.cursor,
1100
+ limit: options?.limit,
1101
+ types: options?.types
1102
+ };
1149
1103
  return this.request(
1150
- "/v0/webhooks",
1104
+ "/v0/events",
1151
1105
  "GET",
1152
1106
  void 0,
1153
1107
  params
1154
1108
  );
1155
1109
  }
1156
1110
  /**
1157
- * Iterate through all Webhooks, handling pagination automatically
1158
- * @param options Pagination options
1159
- * @returns Async generator of Webhooks
1111
+ * Get an Event by ID
1112
+ * @param id The ID of the Event
1113
+ * @returns The Event
1114
+ */
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
1160
1122
  */
1161
1123
  async *listAll(options) {
1162
1124
  let cursor = void 0;
@@ -1164,8 +1126,8 @@ var WebsetWebhooksClient = class extends WebsetsBaseClient {
1164
1126
  while (true) {
1165
1127
  pageOptions.cursor = cursor;
1166
1128
  const response = await this.list(pageOptions);
1167
- for (const webhook of response.data) {
1168
- yield webhook;
1129
+ for (const event of response.data) {
1130
+ yield event;
1169
1131
  }
1170
1132
  if (!response.hasMore || !response.nextCursor) {
1171
1133
  break;
@@ -1174,299 +1136,377 @@ var WebsetWebhooksClient = class extends WebsetsBaseClient {
1174
1136
  }
1175
1137
  }
1176
1138
  /**
1177
- * Collect all Webhooks into an array
1178
- * @param options Pagination options
1179
- * @returns Promise resolving to an array of all Webhooks
1139
+ * Collect all Events into an array
1140
+ * @param options Filtering and pagination options
1141
+ * @returns Promise resolving to an array of all Events
1180
1142
  */
1181
1143
  async getAll(options) {
1182
- const webhooks = [];
1183
- for await (const webhook of this.listAll(options)) {
1184
- webhooks.push(webhook);
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
+ );
1185
1324
  }
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
1193
- */
1194
- async update(id, params) {
1195
- return this.request(`/v0/webhooks/${id}`, "PATCH", params);
1196
- }
1197
- /**
1198
- * Delete a Webhook
1199
- * @param id The ID of the Webhook
1200
- * @returns The deleted Webhook
1201
- */
1202
- async delete(id) {
1203
- return this.request(`/v0/webhooks/${id}`, "DELETE");
1204
- }
1205
- /**
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
1210
- */
1211
- async listAttempts(id, options) {
1212
- const params = {
1213
- cursor: options?.cursor,
1214
- limit: options?.limit,
1215
- eventType: options?.eventType,
1216
- successful: options?.successful
1217
- };
1218
- return this.request(
1219
- `/v0/webhooks/${id}/attempts`,
1220
- "GET",
1221
- void 0,
1222
- params
1223
- );
1224
- }
1225
- /**
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
1230
- */
1231
- async *listAllAttempts(id, options) {
1232
- let cursor = void 0;
1233
- const pageOptions = options ? { ...options } : {};
1234
- while (true) {
1235
- pageOptions.cursor = cursor;
1236
- const response = await this.listAttempts(id, pageOptions);
1237
- for (const attempt of response.data) {
1238
- yield attempt;
1239
- }
1240
- if (!response.hasMore || !response.nextCursor) {
1241
- break;
1242
- }
1243
- cursor = response.nextCursor;
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
+ );
1244
1335
  }
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);
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
1307
- );
1308
- }
1309
- /**
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
1314
- */
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
1365
+ createParams
1325
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;
1326
1389
  }
1327
1390
  /**
1328
- * List all Websets
1329
- * @param options Pagination options (filtering by status is not supported by API)
1330
- * @returns The list of Websets
1391
+ * Get an Import by ID
1392
+ * @param id The ID of the Import
1393
+ * @returns The Import
1394
+ */
1395
+ async get(id) {
1396
+ return this.request(`/v0/imports/${id}`, "GET");
1397
+ }
1398
+ /**
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;
1424
1448
  }
1425
- if (timeout && Date.now() - startTime > timeout) {
1449
+ if (importItem.status === "failed" /* failed */) {
1426
1450
  throw new ExaError(
1427
- `Webset ${id} did not reach idle state within ${timeout}ms. Current status: ${webset.status}`,
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}`,
1428
1458
  408 /* RequestTimeout */
1429
1459
  );
1430
1460
  }
1431
1461
  await new Promise((resolve) => setTimeout(resolve, pollInterval));
1432
1462
  }
1433
1463
  }
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(
1444
- `/websets${endpoint}`,
1445
- method,
1446
- data,
1447
- params,
1448
- headers
1449
- );
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;
1477
+ }
1478
+ if (!response.hasMore || !response.nextCursor) {
1479
+ break;
1480
+ }
1481
+ cursor = response.nextCursor;
1482
+ }
1450
1483
  }
1451
- buildPaginationParams(pagination) {
1452
- const params = {};
1453
- if (!pagination) return params;
1454
- if (pagination.cursor) params.cursor = pagination.cursor;
1455
- if (pagination.limit) params.limit = pagination.limit;
1456
- 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;
1457
1495
  }
1458
1496
  };
1497
+
1498
+ // src/websets/items.ts
1459
1499
  var WebsetItemsClient2 = class extends WebsetsBaseClient2 {
1460
- async get(websetId, id) {
1461
- return this.request(`/v0/websets/${websetId}/items/${id}`, "GET");
1462
- }
1463
- async delete(websetId, id) {
1464
- return this.request(`/v0/websets/${websetId}/items/${id}`, "DELETE");
1465
- }
1466
- async list(websetId, options) {
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) {
1467
1507
  const queryParams = {
1468
- ...this.buildPaginationParams(options),
1469
- sourceId: options?.sourceId
1508
+ ...this.buildPaginationParams(params),
1509
+ sourceId: params?.sourceId
1470
1510
  };
1471
1511
  return this.request(
1472
1512
  `/v0/websets/${websetId}/items`,
@@ -1475,73 +1515,94 @@ var WebsetItemsClient2 = class extends WebsetsBaseClient2 {
1475
1515
  queryParams
1476
1516
  );
1477
1517
  }
1478
- };
1479
- var WebsetSearchesClient2 = class extends WebsetsBaseClient2 {
1480
- async create(websetId, params, options) {
1481
- return this.request(
1482
- `/v0/websets/${websetId}/searches`,
1483
- "POST",
1484
- { ...params },
1485
- void 0,
1486
- options?.headers
1487
- );
1488
- }
1489
- async get(websetId, id) {
1490
- return this.request(`/v0/websets/${websetId}/searches/${id}`, "GET");
1491
- }
1492
- async cancel(websetId, id) {
1493
- return this.request(
1494
- `/v0/websets/${websetId}/searches/${id}/cancel`,
1495
- "POST"
1496
- );
1497
- }
1498
- };
1499
- var WebsetEnrichmentsClient2 = class extends WebsetsBaseClient2 {
1500
- async create(websetId, params) {
1501
- return this.request(`/v0/websets/${websetId}/enrichments`, "POST", {
1502
- ...params
1503
- });
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
+ */
1524
+ async *listAll(websetId, options) {
1525
+ let cursor = void 0;
1526
+ const pageOptions = options ? { ...options } : {};
1527
+ while (true) {
1528
+ pageOptions.cursor = cursor;
1529
+ const response = await this.list(websetId, pageOptions);
1530
+ for (const item of response.data) {
1531
+ yield item;
1532
+ }
1533
+ if (!response.hasMore || !response.nextCursor) {
1534
+ break;
1535
+ }
1536
+ cursor = response.nextCursor;
1537
+ }
1504
1538
  }
1505
- async update(websetId, id, params) {
1506
- return this.request(
1507
- `/v0/websets/${websetId}/enrichments/${id}`,
1508
- "PATCH",
1509
- { ...params }
1510
- );
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
+ */
1545
+ async getAll(websetId, options) {
1546
+ const items = [];
1547
+ for await (const item of this.listAll(websetId, options)) {
1548
+ items.push(item);
1549
+ }
1550
+ return items;
1511
1551
  }
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
+ */
1512
1558
  async get(websetId, id) {
1513
- return this.request(`/v0/websets/${websetId}/enrichments/${id}`, "GET");
1559
+ return this.request(
1560
+ `/v0/websets/${websetId}/items/${id}`,
1561
+ "GET"
1562
+ );
1514
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
+ */
1515
1570
  async delete(websetId, id) {
1516
- return this.request(`/v0/websets/${websetId}/enrichments/${id}`, "DELETE");
1517
- }
1518
- async cancel(websetId, id) {
1519
1571
  return this.request(
1520
- `/v0/websets/${websetId}/enrichments/${id}/cancel`,
1521
- "POST"
1572
+ `/v0/websets/${websetId}/items/${id}`,
1573
+ "DELETE"
1522
1574
  );
1523
1575
  }
1524
1576
  };
1525
- var EventsClient2 = class extends WebsetsBaseClient2 {
1526
- async list(options) {
1527
- const queryParams = {
1528
- ...this.buildPaginationParams(options),
1529
- types: options?.types,
1530
- createdBefore: options?.createdBefore,
1531
- createdAfter: options?.createdAfter
1532
- };
1533
- return this.request("/v0/events", "GET", void 0, queryParams);
1534
- }
1535
- async get(id) {
1536
- return this.request(`/v0/events/${id}`, "GET");
1537
- }
1538
- };
1577
+
1578
+ // src/websets/monitors.ts
1539
1579
  var WebsetMonitorRunsClient2 = class extends WebsetsBaseClient2 {
1540
- async list(monitorId) {
1541
- return this.request(`/v0/monitors/${monitorId}/runs`, "GET");
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
+ );
1542
1594
  }
1543
- async get(monitorId, id) {
1544
- return this.request(`/v0/monitors/${monitorId}/runs/${id}`, "GET");
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
+ );
1545
1606
  }
1546
1607
  };
1547
1608
  var WebsetMonitorsClient2 = class extends WebsetsBaseClient2 {
@@ -1549,435 +1610,443 @@ var WebsetMonitorsClient2 = class extends WebsetsBaseClient2 {
1549
1610
  super(client);
1550
1611
  this.runs = new WebsetMonitorRunsClient2(client);
1551
1612
  }
1613
+ /**
1614
+ * Create a Monitor
1615
+ * @param params The monitor parameters
1616
+ * @returns The created Monitor
1617
+ */
1552
1618
  async create(params) {
1553
- return this.request("/v0/monitors", "POST", { ...params });
1554
- }
1555
- async list(options) {
1556
- const queryParams = {
1557
- ...this.buildPaginationParams(options),
1558
- websetId: options?.websetId
1559
- };
1560
- return this.request("/v0/monitors", "GET", void 0, queryParams);
1619
+ return this.request("/v0/monitors", "POST", params);
1561
1620
  }
1621
+ /**
1622
+ * Get a Monitor by ID
1623
+ * @param id The ID of the Monitor
1624
+ * @returns The Monitor
1625
+ */
1562
1626
  async get(id) {
1563
1627
  return this.request(`/v0/monitors/${id}`, "GET");
1564
1628
  }
1565
- async update(id, params) {
1566
- return this.request(`/v0/monitors/${id}`, "PATCH", { ...params });
1567
- }
1568
- async delete(id) {
1569
- return this.request(`/v0/monitors/${id}`, "DELETE");
1570
- }
1571
- };
1572
- var WebsetWebhooksClient2 = class extends WebsetsBaseClient2 {
1573
- async create(params) {
1574
- return this.request("/v0/webhooks", "POST", { ...params });
1575
- }
1629
+ /**
1630
+ * List all Monitors
1631
+ * @param options Pagination and filtering options
1632
+ * @returns The list of Monitors
1633
+ */
1576
1634
  async list(options) {
1577
- const queryParams = this.buildPaginationParams(options);
1578
- return this.request("/v0/webhooks", "GET", void 0, queryParams);
1579
- }
1580
- async get(id) {
1581
- return this.request(`/v0/webhooks/${id}`, "GET");
1582
- }
1583
- async update(id, params) {
1584
- return this.request(`/v0/webhooks/${id}`, "PATCH", { ...params });
1585
- }
1586
- async delete(id) {
1587
- return this.request(`/v0/webhooks/${id}`, "DELETE");
1588
- }
1589
- async listAttempts(id, options) {
1590
- const queryParams = {
1591
- ...this.buildPaginationParams(options),
1592
- eventType: options?.eventType,
1593
- successful: options?.successful
1635
+ const params = {
1636
+ cursor: options?.cursor,
1637
+ limit: options?.limit,
1638
+ websetId: options?.websetId
1594
1639
  };
1595
1640
  return this.request(
1596
- `/v0/webhooks/${id}/attempts`,
1641
+ "/v0/monitors",
1597
1642
  "GET",
1598
1643
  void 0,
1599
- queryParams
1600
- );
1601
- }
1602
- };
1603
- var ImportsClient2 = class extends WebsetsBaseClient2 {
1604
- async create(params) {
1605
- return this.request("/v0/imports", "POST", { ...params });
1606
- }
1607
- async list(options) {
1608
- const queryParams = this.buildPaginationParams(options);
1609
- return this.request("/v0/imports", "GET", void 0, queryParams);
1610
- }
1611
- async get(id) {
1612
- return this.request(`/v0/imports/${id}`, "GET");
1613
- }
1614
- async update(id, params) {
1615
- return this.request(`/v0/imports/${id}`, "PATCH", { ...params });
1616
- }
1617
- async delete(id) {
1618
- return this.request(`/v0/imports/${id}`, "DELETE");
1619
- }
1620
- };
1621
- var WebsetsClient2 = class extends WebsetsBaseClient2 {
1622
- constructor(client) {
1623
- super(client);
1624
- this.items = new WebsetItemsClient2(client);
1625
- this.searches = new WebsetSearchesClient2(client);
1626
- this.enrichments = new WebsetEnrichmentsClient2(client);
1627
- this.events = new EventsClient2(client);
1628
- this.monitors = new WebsetMonitorsClient2(client);
1629
- this.webhooks = new WebsetWebhooksClient2(client);
1630
- this.imports = new ImportsClient2(client);
1631
- }
1632
- async create(params, options) {
1633
- return this.request(
1634
- "/v0/websets",
1635
- "POST",
1636
- { ...params },
1637
- void 0,
1638
- options?.headers
1644
+ params
1639
1645
  );
1640
1646
  }
1641
- async list(options) {
1642
- const queryParams = {
1643
- ...this.buildPaginationParams(options),
1644
- search: options?.search
1645
- };
1646
- return this.request("/v0/websets", "GET", void 0, queryParams);
1647
- }
1648
- async get(id, options) {
1649
- const queryParams = { expand: options?.expand };
1650
- return this.request(`/v0/websets/${id}`, "GET", void 0, queryParams);
1651
- }
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
+ */
1652
1653
  async update(id, params) {
1653
- return this.request(`/v0/websets/${id}`, "POST", { ...params });
1654
+ return this.request(`/v0/monitors/${id}`, "PATCH", params);
1654
1655
  }
1656
+ /**
1657
+ * Delete a Monitor
1658
+ * @param id The ID of the Monitor
1659
+ * @returns The deleted Monitor
1660
+ */
1655
1661
  async delete(id) {
1656
- return this.request(`/v0/websets/${id}`, "DELETE");
1657
- }
1658
- async cancel(id) {
1659
- return this.request(`/v0/websets/${id}/cancel`, "POST");
1660
- }
1661
- async preview(params, options) {
1662
- const queryParams = { search: options?.search };
1663
- return this.request(
1664
- "/v0/websets/preview",
1665
- "POST",
1666
- { ...params },
1667
- queryParams
1668
- );
1662
+ return this.request(`/v0/monitors/${id}`, "DELETE");
1669
1663
  }
1670
- /** Poll until a Webset reaches idle status. */
1671
- async waitUntilIdle(id, options) {
1672
- let timeout;
1673
- let pollInterval = 1e3;
1674
- let onPoll;
1675
- if (typeof options === "number") {
1676
- timeout = options;
1677
- } else if (options) {
1678
- timeout = options.timeout;
1679
- pollInterval = options.pollInterval || 1e3;
1680
- onPoll = options.onPoll;
1681
- }
1682
- const startTime = Date.now();
1664
+ /**
1665
+ * Iterate through all Monitors, handling pagination automatically
1666
+ * @param options Pagination and filtering options
1667
+ * @returns Async generator of Monitors
1668
+ */
1669
+ async *listAll(options) {
1670
+ let cursor = void 0;
1671
+ const pageOptions = options ? { ...options } : {};
1683
1672
  while (true) {
1684
- const webset = await this.get(id);
1685
- if (onPoll) onPoll(webset.status);
1686
- if (webset.status === "idle") return webset;
1687
- if (timeout && Date.now() - startTime > timeout) {
1688
- throw new Error(
1689
- `Webset ${id} did not reach idle state within ${timeout}ms. Current status: ${webset.status}`
1690
- );
1673
+ pageOptions.cursor = cursor;
1674
+ const response = await this.list(pageOptions);
1675
+ for (const monitor of response.data) {
1676
+ yield monitor;
1691
1677
  }
1692
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
1678
+ if (!response.hasMore || !response.nextCursor) {
1679
+ break;
1680
+ }
1681
+ cursor = response.nextCursor;
1682
+ }
1683
+ }
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
+ */
1689
+ async getAll(options) {
1690
+ const monitors = [];
1691
+ for await (const monitor of this.listAll(options)) {
1692
+ monitors.push(monitor);
1693
1693
  }
1694
+ return monitors;
1694
1695
  }
1695
1696
  };
1696
1697
 
1697
- // src/nova/research-client.ts
1698
- var import_zod2 = require("zod");
1699
- var import_zod_to_json_schema2 = require("zod-to-json-schema");
1700
- function zodToJsonSchema2(schema) {
1701
- return (0, import_zod_to_json_schema2.zodToJsonSchema)(schema, { $refStrategy: "none" });
1702
- }
1703
- var ResearchBaseClient2 = class {
1704
- constructor(client) {
1705
- this.client = client;
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
+ );
1706
1714
  }
1707
- /** Make a request to the API, prepending `/research/v1` to the path. */
1708
- async request(endpoint, method = "POST", data, params) {
1709
- return this.client.request(
1710
- `/research/v1${endpoint}`,
1711
- method,
1712
- data,
1713
- params
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"
1714
1725
  );
1715
1726
  }
1716
- buildPaginationParams(pagination) {
1717
- const params = {};
1718
- if (!pagination) return params;
1719
- if (pagination.cursor) params.cursor = pagination.cursor;
1720
- if (pagination.limit) params.limit = pagination.limit;
1721
- return params;
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
+ );
1722
1738
  }
1723
1739
  };
1724
- var ResearchClient2 = class extends ResearchBaseClient2 {
1725
- /** List research requests. */
1726
- async list(options) {
1727
- const params = this.buildPaginationParams(options);
1728
- return this.client.request("/research/v1", "GET", void 0, params);
1729
- }
1730
- /** Create a new research request. Defaults model to "exa-research-fast" if not provided. */
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
+ */
1731
1748
  async create(params) {
1732
- let schema = params.outputSchema;
1733
- if (schema instanceof import_zod2.ZodType) {
1734
- schema = zodToJsonSchema2(schema);
1735
- }
1736
- const payload = {
1737
- instructions: params.instructions,
1738
- model: params.model ?? "exa-research-fast"
1739
- };
1740
- if (schema) {
1741
- payload.outputSchema = schema;
1742
- }
1743
- return this.client.request("/research/v1", "POST", payload, void 0);
1749
+ return this.request("/v0/webhooks", "POST", params);
1744
1750
  }
1745
- /** Get a research request by ID. */
1746
- async get(researchId, options) {
1747
- const params = {};
1748
- if (options?.events !== void 0)
1749
- params.events = options.events.toString();
1750
- return this.client.request(
1751
- `/research/v1/${researchId}`,
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");
1758
+ }
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",
1752
1768
  "GET",
1753
1769
  void 0,
1754
1770
  params
1755
1771
  );
1756
1772
  }
1757
- /** Poll a research request until it reaches a terminal state (completed, failed, or canceled). */
1758
- async pollUntilFinished(researchId, options) {
1759
- const pollInterval = options?.pollInterval ?? 1e3;
1760
- const timeoutMs = options?.timeoutMs ?? 10 * 60 * 1e3;
1761
- const maxConsecutiveFailures = 5;
1762
- const startTime = Date.now();
1763
- let consecutiveFailures = 0;
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 } : {};
1764
1781
  while (true) {
1765
- try {
1766
- const research = await this.get(researchId, {
1767
- events: options?.events
1768
- });
1769
- consecutiveFailures = 0;
1770
- if (research.status === "completed" || research.status === "failed" || research.status === "canceled") {
1771
- return research;
1772
- }
1773
- } catch (err) {
1774
- consecutiveFailures += 1;
1775
- if (consecutiveFailures >= maxConsecutiveFailures) {
1776
- throw new Error(
1777
- `Polling failed ${maxConsecutiveFailures} times in a row for research ${researchId}: ${err}`
1778
- );
1779
- }
1782
+ pageOptions.cursor = cursor;
1783
+ const response = await this.list(pageOptions);
1784
+ for (const webhook of response.data) {
1785
+ yield webhook;
1780
1786
  }
1781
- if (Date.now() - startTime > timeoutMs) {
1782
- throw new Error(
1783
- `Polling timeout: Research ${researchId} did not complete within ${timeoutMs}ms`
1784
- );
1787
+ if (!response.hasMore || !response.nextCursor) {
1788
+ break;
1785
1789
  }
1786
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
1790
+ cursor = response.nextCursor;
1787
1791
  }
1788
1792
  }
1789
- };
1790
-
1791
- // src/nova/client.ts
1792
- var CONTENTS_FIELDS = /* @__PURE__ */ new Set([
1793
- "text",
1794
- "highlights",
1795
- "summary",
1796
- "subpages",
1797
- "subpageTarget",
1798
- "extras",
1799
- "livecrawl",
1800
- "livecrawlTimeout",
1801
- "maxAgeHours",
1802
- "filterEmptyResults",
1803
- "context"
1804
- ]);
1805
- var DEFAULT_MAX_CHARACTERS = 1e4;
1806
- var Exa2 = class {
1807
- constructor(apiKey, baseURL = "https://api.exa.ai") {
1808
- this.baseURL = baseURL;
1809
- if (!apiKey) {
1810
- apiKey = typeof process !== "undefined" ? process.env?.EXA_API_KEY : void 0;
1811
- if (!apiKey) {
1812
- throw new Error(
1813
- "API key must be provided as an argument or as an environment variable (EXA_API_KEY)"
1814
- );
1815
- }
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);
1816
1802
  }
1817
- this.headers = {
1818
- "x-api-key": apiKey,
1819
- "Content-Type": "application/json"
1820
- };
1821
- this.websets = new WebsetsClient2(this);
1822
- this.research = new ResearchClient2(this);
1803
+ return webhooks;
1823
1804
  }
1824
- /** Make a request to the Exa API. Used by sub-clients and available for direct use. */
1825
- async request(endpoint, method, body, params, headers) {
1826
- let url = `${this.baseURL}${endpoint}`;
1827
- const normalizedBody = this.normalizeCategoryInBody(body);
1828
- if (params && Object.keys(params).length > 0) {
1829
- const searchParams = new URLSearchParams();
1830
- for (const [key, value] of Object.entries(params)) {
1831
- if (Array.isArray(value)) {
1832
- for (const item of value) {
1833
- searchParams.append(key, item);
1834
- }
1835
- } else if (value !== void 0) {
1836
- searchParams.append(key, String(value));
1837
- }
1838
- }
1839
- url += `?${searchParams.toString()}`;
1840
- }
1841
- const combinedHeaders = headers ? { ...this.headers, ...headers } : this.headers;
1842
- const response = await fetch(url, {
1843
- method,
1844
- headers: combinedHeaders,
1845
- body: normalizedBody ? JSON.stringify(normalizedBody) : void 0
1846
- });
1847
- if (!response.ok) {
1848
- const text = await response.text();
1849
- throw new Error(`Exa API error ${response.status}: ${text}`);
1850
- }
1851
- return await response.json();
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);
1852
1813
  }
1853
- /** Make a raw request returning the Response object directly. */
1854
- async rawRequest(endpoint, method = "POST", body, params) {
1855
- let url = `${this.baseURL}${endpoint}`;
1856
- const normalizedBody = this.normalizeCategoryInBody(body);
1857
- if (params && Object.keys(params).length > 0) {
1858
- const searchParams = new URLSearchParams();
1859
- for (const [key, value] of Object.entries(params)) {
1860
- if (Array.isArray(value)) {
1861
- for (const item of value) {
1862
- searchParams.append(key, item);
1863
- }
1864
- } else if (value !== void 0) {
1865
- searchParams.append(key, String(value));
1866
- }
1867
- }
1868
- url += `?${searchParams.toString()}`;
1869
- }
1870
- return fetch(url, {
1871
- method,
1872
- headers: this.headers,
1873
- body: normalizedBody ? JSON.stringify(normalizedBody) : void 0
1874
- });
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");
1875
1821
  }
1876
- /** Normalize category values to underscore form. */
1877
- normalizeCategoryInBody(body) {
1878
- if (body == null || typeof body.category !== "string") {
1879
- return body;
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
1834
+ };
1835
+ return this.request(
1836
+ `/v0/webhooks/${id}/attempts`,
1837
+ "GET",
1838
+ void 0,
1839
+ params
1840
+ );
1841
+ }
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;
1856
+ }
1857
+ if (!response.hasMore || !response.nextCursor) {
1858
+ break;
1859
+ }
1860
+ cursor = response.nextCursor;
1880
1861
  }
1881
- return { ...body, category: body.category.replace(/ /g, "_") };
1882
1862
  }
1883
- /** Separate content-specific options from search/filter options. */
1884
- extractContentsOptions(options) {
1885
- const contentsOptions = {};
1886
- const restOptions = {};
1887
- let hasContentField = false;
1888
- for (const [key, value] of Object.entries(options)) {
1889
- if (CONTENTS_FIELDS.has(key)) {
1890
- contentsOptions[key] = value;
1891
- hasContentField = true;
1892
- } else {
1893
- restOptions[key] = value;
1894
- }
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);
1895
1873
  }
1896
- if (!hasContentField) {
1897
- contentsOptions.text = { maxCharacters: DEFAULT_MAX_CHARACTERS };
1874
+ return attempts;
1875
+ }
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);
1893
+ }
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
+ );
1907
+ }
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;
1898
1918
  }
1899
- return { contentsOptions, restOptions };
1919
+ return this.request(
1920
+ "/v0/websets/preview",
1921
+ "POST",
1922
+ params,
1923
+ queryParams
1924
+ );
1900
1925
  }
1901
- search(query, options) {
1902
- let body;
1903
- if (options === void 0 || !("contents" in options)) {
1904
- body = {
1905
- query,
1906
- ...options,
1907
- contents: { text: { maxCharacters: DEFAULT_MAX_CHARACTERS } }
1908
- };
1909
- } else if (options.contents === false || options.contents === null || options.contents === void 0) {
1910
- const { contents, ...restOptions } = options;
1911
- body = { query, ...restOptions };
1912
- } else {
1913
- body = { query, ...options };
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;
1914
1936
  }
1915
- return this.request("/search", "POST", body);
1937
+ return this.request(
1938
+ `/v0/websets/${id}`,
1939
+ "GET",
1940
+ void 0,
1941
+ params
1942
+ );
1916
1943
  }
1917
- findSimilar(url, options) {
1918
- let body;
1919
- if (options === void 0 || !("contents" in options)) {
1920
- body = {
1921
- url,
1922
- ...options,
1923
- contents: { text: { maxCharacters: DEFAULT_MAX_CHARACTERS } }
1924
- };
1925
- } else if (options.contents === false || options.contents === null || options.contents === void 0) {
1926
- const { contents, ...restOptions } = options;
1927
- body = { url, ...restOptions };
1928
- } else {
1929
- body = { url, ...options };
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;
1971
+ }
1972
+ if (!response.hasMore || !response.nextCursor) {
1973
+ break;
1974
+ }
1975
+ cursor = response.nextCursor;
1930
1976
  }
1931
- return this.request("/findSimilar", "POST", body);
1932
1977
  }
1933
- getContents(urls, options) {
1934
- return this.request("/contents", "POST", { urls, ...options });
1978
+ /**
1979
+ * Collect all Websets into an array
1980
+ * @param options Pagination options
1981
+ * @returns Promise resolving to an array of all Websets
1982
+ */
1983
+ async getAll(options) {
1984
+ const websets = [];
1985
+ for await (const webset of this.listAll(options)) {
1986
+ websets.push(webset);
1987
+ }
1988
+ return websets;
1935
1989
  }
1936
- answer(query, options) {
1937
- return this.request("/answer", "POST", { query, ...options });
1990
+ /**
1991
+ * Update a Webset
1992
+ * @param id The ID of the Webset
1993
+ * @param params The Webset update parameters
1994
+ * @returns The updated Webset
1995
+ */
1996
+ async update(id, params) {
1997
+ return this.request(`/v0/websets/${id}`, "POST", params);
1938
1998
  }
1939
- streamAnswer(query, options) {
1940
- return this.rawRequest("/answer", "POST", {
1941
- query,
1942
- stream: true,
1943
- ...options
1944
- });
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");
1945
2006
  }
1946
2007
  /**
1947
- * @deprecated Use `search()` instead. The search method now returns text contents by default.
1948
- * Search with contents. Extracts content fields (text, highlights, summary, etc.) into a `contents` wrapper.
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)
1949
2011
  */
1950
- async searchAndContents(query, options) {
1951
- if (options === void 0) {
1952
- return this.request("/search", "POST", {
1953
- query,
1954
- contents: { text: { maxCharacters: DEFAULT_MAX_CHARACTERS } }
1955
- });
1956
- }
1957
- const { contentsOptions, restOptions } = this.extractContentsOptions(options);
1958
- return this.request("/search", "POST", {
1959
- query,
1960
- contents: contentsOptions,
1961
- ...restOptions
1962
- });
2012
+ async cancel(id) {
2013
+ return this.request(`/v0/websets/${id}/cancel`, "POST");
1963
2014
  }
1964
2015
  /**
1965
- * @deprecated Use `findSimilar()` instead. The findSimilar method now returns text contents by default.
1966
- * Find similar with contents. Extracts content fields into a `contents` wrapper.
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
1967
2021
  */
1968
- async findSimilarAndContents(url, options) {
1969
- if (options === void 0) {
1970
- return this.request("/findSimilar", "POST", {
1971
- url,
1972
- contents: { text: { maxCharacters: DEFAULT_MAX_CHARACTERS } }
1973
- });
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));
1974
2049
  }
1975
- const { contentsOptions, restOptions } = this.extractContentsOptions(options);
1976
- return this.request("/findSimilar", "POST", {
1977
- url,
1978
- contents: contentsOptions,
1979
- ...restOptions
1980
- });
1981
2050
  }
1982
2051
  };
1983
2052
 
@@ -2013,7 +2082,7 @@ var Exa3 = class {
2013
2082
  if (typeof summary === "object" && summary !== null && "schema" in summary && summary.schema && isZodSchema(summary.schema)) {
2014
2083
  contentsOptions.summary = {
2015
2084
  ...summary,
2016
- schema: zodToJsonSchema(summary.schema)
2085
+ schema: zodToJsonSchema2(summary.schema)
2017
2086
  };
2018
2087
  } else {
2019
2088
  contentsOptions.summary = summary;
@@ -2054,8 +2123,8 @@ var Exa3 = class {
2054
2123
  "Content-Type": "application/json",
2055
2124
  "User-Agent": `exa-node ${package_default.version}`
2056
2125
  });
2057
- this.websets = new WebsetsClient(this);
2058
- this.research = new ResearchClient(this);
2126
+ this.websets = new WebsetsClient2(this);
2127
+ this.research = new ResearchClient2(this);
2059
2128
  }
2060
2129
  /**
2061
2130
  * Makes a request to the Exa API.
@@ -2267,7 +2336,7 @@ var Exa3 = class {
2267
2336
  }
2268
2337
  let outputSchema = options?.outputSchema;
2269
2338
  if (outputSchema && isZodSchema(outputSchema)) {
2270
- outputSchema = zodToJsonSchema(outputSchema);
2339
+ outputSchema = zodToJsonSchema2(outputSchema);
2271
2340
  }
2272
2341
  const requestBody = {
2273
2342
  query,
@@ -2283,7 +2352,7 @@ var Exa3 = class {
2283
2352
  async *streamAnswer(query, options) {
2284
2353
  let outputSchema = options?.outputSchema;
2285
2354
  if (outputSchema && isZodSchema(outputSchema)) {
2286
- outputSchema = zodToJsonSchema(outputSchema);
2355
+ outputSchema = zodToJsonSchema2(outputSchema);
2287
2356
  }
2288
2357
  const body = {
2289
2358
  query,