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

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