exa-js 2.28.0 → 2.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -103,7 +103,7 @@ var import_cross_fetch = __toESM(require("cross-fetch"));
103
103
  // package.json
104
104
  var package_default = {
105
105
  name: "exa-js",
106
- version: "2.28.0",
106
+ version: "2.29.0",
107
107
  description: "Exa SDK for Node.js and the browser",
108
108
  publishConfig: {
109
109
  access: "public"
@@ -141,7 +141,6 @@ var package_default = {
141
141
  "generate:types:websets": "openapi-typescript https://raw.githubusercontent.com/exa-labs/openapi-spec/refs/heads/master/exa-websets-spec.yaml --enum --root-types --alphabetize --root-types-no-schema-prefix --output ./src/websets/openapi.ts && npm run format:websets",
142
142
  format: 'prettier --write "src/**/*.ts"',
143
143
  "format:websets": "prettier --write src/websets/openapi.ts",
144
- "generate-docs": "npx tsx scripts/generate-docs.ts",
145
144
  "build:beta": "cross-env NPM_CONFIG_TAG=beta npm run build",
146
145
  "version:beta": "npm version prerelease --preid=beta",
147
146
  "version:stable": "npm version patch",
@@ -157,10 +156,7 @@ var package_default = {
157
156
  openai: "^6.49.0",
158
157
  "openapi-typescript": "~7.6.1",
159
158
  prettier: "~3.5.3",
160
- "ts-morph": "^27.0.2",
161
- "ts-node": "~10.9.2",
162
159
  tsup: "~8.4.0",
163
- tsx: "^4.23.15",
164
160
  typescript: "~5.8.3",
165
161
  vitest: "~4.1.12"
166
162
  },
@@ -226,6 +222,7 @@ var ExaError = class extends Error {
226
222
  this.code = envelope.code;
227
223
  this.detail = envelope.detail;
228
224
  this.requestId = envelope.requestId;
225
+ this.tag = envelope.tag;
229
226
  }
230
227
  }
231
228
  };
@@ -325,6 +322,7 @@ async function exaErrorFromResponse(response, path) {
325
322
  message += (message.length > 0 ? ". " : "") + errorData.message;
326
323
  }
327
324
  }
325
+ const tag = typeof errorData.tag === "string" ? errorData.tag : void 0;
328
326
  return new ExaError(
329
327
  message,
330
328
  response.status,
@@ -334,8 +332,9 @@ async function exaErrorFromResponse(response, path) {
334
332
  type: envelope.type,
335
333
  code: envelope.code,
336
334
  detail: envelope.detail,
337
- requestId: errorData.requestId ?? envelope.requestId
338
- } : errorData.requestId ? { requestId: errorData.requestId } : void 0
335
+ requestId: errorData.requestId ?? envelope.requestId,
336
+ tag
337
+ } : errorData.requestId || tag ? { requestId: errorData.requestId, tag } : void 0
339
338
  );
340
339
  }
341
340
 
@@ -457,6 +456,12 @@ function mergeRequestHeaders(headers, extraHeaders) {
457
456
  }
458
457
  return merged;
459
458
  }
459
+ function setsHeader(headers, name) {
460
+ const lowerCaseName = name.toLowerCase();
461
+ return Object.entries(headers ?? {}).some(
462
+ ([key, value]) => key.toLowerCase() === lowerCaseName && value !== void 0
463
+ );
464
+ }
460
465
  var CLIENT_DEFAULTS = /* @__PURE__ */ new WeakMap();
461
466
  function setClientDefaults(client, defaults) {
462
467
  if (defaults === void 0) {
@@ -711,6 +716,26 @@ function sleep(ms, signal) {
711
716
  }, ms);
712
717
  });
713
718
  }
719
+ function untilAborted(promise, signal) {
720
+ return new Promise((resolve, reject) => {
721
+ const onAbort = () => reject(signal.reason);
722
+ if (signal.aborted) {
723
+ onAbort();
724
+ } else {
725
+ signal.addEventListener("abort", onAbort, { once: true });
726
+ }
727
+ promise.then(
728
+ (value) => {
729
+ signal.removeEventListener("abort", onAbort);
730
+ resolve(value);
731
+ },
732
+ (error) => {
733
+ signal.removeEventListener("abort", onAbort);
734
+ reject(error);
735
+ }
736
+ );
737
+ });
738
+ }
714
739
  var RequestScopedClient = class {
715
740
  /**
716
741
  * Returns a view of this client that sends `requestOptions` with every
@@ -744,7 +769,35 @@ var RequestScopedClient = class {
744
769
  view.requestOptions = { ...this.requestOptions, query: remaining };
745
770
  return view;
746
771
  }
772
+ /**
773
+ * Yields every item of a cursor-paginated listing. `fetchPage` fetches the
774
+ * page at `cursor` with the view it is given: this one for the first page,
775
+ * `forNextPage()` for the rest. Stops after a page without `hasMore` or
776
+ * without a `nextCursor`.
777
+ */
778
+ async *paginate(firstCursor, fetchPage) {
779
+ let view = this;
780
+ let cursor = firstCursor;
781
+ while (true) {
782
+ const page = await fetchPage(view, cursor);
783
+ for (const item of page.data) {
784
+ yield item;
785
+ }
786
+ if (!page.hasMore || !page.nextCursor) {
787
+ return;
788
+ }
789
+ cursor = page.nextCursor;
790
+ view = view.forNextPage();
791
+ }
792
+ }
747
793
  };
794
+ async function collectAll(items) {
795
+ const all = [];
796
+ for await (const item of items) {
797
+ all.push(item);
798
+ }
799
+ return all;
800
+ }
748
801
 
749
802
  // src/agent/base.ts
750
803
  var AgentBaseClient = class extends RequestScopedClient {
@@ -907,33 +960,19 @@ var AgentMonitorEntitiesClient = class extends AgentMonitorsBaseClient {
907
960
  * automatically.
908
961
  */
909
962
  async *listAll(monitorId, options, requestOptions) {
910
- let scoped = this.withRequestOptions(requestOptions);
911
- let cursor = options.cursor;
912
963
  const { betas, ...pagination } = options;
913
- const pageOptions = { ...pagination };
914
- while (true) {
915
- pageOptions.cursor = cursor;
916
- const response = await scoped.list(monitorId, { ...pageOptions, betas });
917
- for (const entityView of response.data) {
918
- yield entityView;
919
- }
920
- if (!response.hasMore || !response.nextCursor) {
921
- break;
922
- }
923
- cursor = response.nextCursor;
924
- scoped = scoped.forNextPage();
925
- }
964
+ yield* this.withRequestOptions(requestOptions).paginate(
965
+ options.cursor,
966
+ (view, cursor) => view.list(monitorId, { ...pagination, cursor, betas })
967
+ );
926
968
  }
927
969
  /**
928
970
  * Collect all of a monitor's entities into an array.
929
971
  */
930
972
  async getAll(monitorId, options, requestOptions) {
931
- const scoped = this.withRequestOptions(requestOptions);
932
- const entities = [];
933
- for await (const entityView of scoped.listAll(monitorId, options)) {
934
- entities.push(entityView);
935
- }
936
- return entities;
973
+ return collectAll(
974
+ this.withRequestOptions(requestOptions).listAll(monitorId, options)
975
+ );
937
976
  }
938
977
  };
939
978
  var AgentMonitorChangesClient = class extends AgentMonitorsBaseClient {
@@ -957,33 +996,19 @@ var AgentMonitorChangesClient = class extends AgentMonitorsBaseClient {
957
996
  * automatically.
958
997
  */
959
998
  async *listAll(monitorId, options, requestOptions) {
960
- let scoped = this.withRequestOptions(requestOptions);
961
- let cursor = options.cursor;
962
999
  const { betas, ...pagination } = options;
963
- const pageOptions = { ...pagination };
964
- while (true) {
965
- pageOptions.cursor = cursor;
966
- const response = await scoped.list(monitorId, { ...pageOptions, betas });
967
- for (const change of response.data) {
968
- yield change;
969
- }
970
- if (!response.hasMore || !response.nextCursor) {
971
- break;
972
- }
973
- cursor = response.nextCursor;
974
- scoped = scoped.forNextPage();
975
- }
1000
+ yield* this.withRequestOptions(requestOptions).paginate(
1001
+ options.cursor,
1002
+ (view, cursor) => view.list(monitorId, { ...pagination, cursor, betas })
1003
+ );
976
1004
  }
977
1005
  /**
978
1006
  * Collect a monitor's change feed into an array.
979
1007
  */
980
1008
  async getAll(monitorId, options, requestOptions) {
981
- const scoped = this.withRequestOptions(requestOptions);
982
- const changes = [];
983
- for await (const change of scoped.listAll(monitorId, options)) {
984
- changes.push(change);
985
- }
986
- return changes;
1009
+ return collectAll(
1010
+ this.withRequestOptions(requestOptions).listAll(monitorId, options)
1011
+ );
987
1012
  }
988
1013
  };
989
1014
  var AgentMonitorBacktestsClient = class extends AgentMonitorsBaseClient {
@@ -1103,33 +1128,19 @@ var AgentMonitorsClient = class extends AgentMonitorsBaseClient {
1103
1128
  * Iterate through all Agent Monitors, handling pagination automatically.
1104
1129
  */
1105
1130
  async *listAll(options, requestOptions) {
1106
- let scoped = this.withRequestOptions(requestOptions);
1107
- let cursor = options.cursor;
1108
1131
  const { betas, ...pagination } = options;
1109
- const pageOptions = { ...pagination };
1110
- while (true) {
1111
- pageOptions.cursor = cursor;
1112
- const response = await scoped.list({ ...pageOptions, betas });
1113
- for (const monitor of response.data) {
1114
- yield monitor;
1115
- }
1116
- if (!response.hasMore || !response.nextCursor) {
1117
- break;
1118
- }
1119
- cursor = response.nextCursor;
1120
- scoped = scoped.forNextPage();
1121
- }
1132
+ yield* this.withRequestOptions(requestOptions).paginate(
1133
+ options.cursor,
1134
+ (view, cursor) => view.list({ ...pagination, cursor, betas })
1135
+ );
1122
1136
  }
1123
1137
  /**
1124
1138
  * Collect all Agent Monitors into an array.
1125
1139
  */
1126
1140
  async getAll(options, requestOptions) {
1127
- const scoped = this.withRequestOptions(requestOptions);
1128
- const monitors = [];
1129
- for await (const monitor of scoped.listAll(options)) {
1130
- monitors.push(monitor);
1131
- }
1132
- return monitors;
1141
+ return collectAll(
1142
+ this.withRequestOptions(requestOptions).listAll(options)
1143
+ );
1133
1144
  }
1134
1145
  /**
1135
1146
  * Delete an Agent Monitor and stop its refreshes.
@@ -1307,32 +1318,18 @@ var AgentRunsClient = class extends AgentBaseClient {
1307
1318
  * Iterate through all Agent runs, handling pagination automatically.
1308
1319
  */
1309
1320
  async *listAll(options, requestOptions) {
1310
- let scoped = this.withRequestOptions(requestOptions);
1311
- let cursor = void 0;
1312
- const pageOptions = options ? { ...options } : {};
1313
- while (true) {
1314
- pageOptions.cursor = cursor;
1315
- const response = await scoped.list(pageOptions);
1316
- for (const run of response.data) {
1317
- yield run;
1318
- }
1319
- if (!response.hasMore || !response.nextCursor) {
1320
- break;
1321
- }
1322
- cursor = response.nextCursor;
1323
- scoped = scoped.forNextPage();
1324
- }
1321
+ yield* this.withRequestOptions(requestOptions).paginate(
1322
+ options?.cursor,
1323
+ (view, cursor) => view.list({ ...options, cursor })
1324
+ );
1325
1325
  }
1326
1326
  /**
1327
1327
  * Collect all Agent runs into an array.
1328
1328
  */
1329
1329
  async getAll(options, requestOptions) {
1330
- const scoped = this.withRequestOptions(requestOptions);
1331
- const runs = [];
1332
- for await (const run of scoped.listAll(options)) {
1333
- runs.push(run);
1334
- }
1335
- return runs;
1330
+ return collectAll(
1331
+ this.withRequestOptions(requestOptions).listAll(options)
1332
+ );
1336
1333
  }
1337
1334
  /**
1338
1335
  * Cancel a queued or running Agent run.
@@ -1469,30 +1466,16 @@ var AgentBetaRunsClient = class extends AgentRunsClient {
1469
1466
  );
1470
1467
  }
1471
1468
  async *listAll(options, requestOptions) {
1472
- let scoped = this.withRequestOptions(requestOptions);
1473
- let cursor = void 0;
1474
1469
  const { betas, ...pagination } = options ?? {};
1475
- const pageOptions = { ...pagination };
1476
- while (true) {
1477
- pageOptions.cursor = cursor;
1478
- const response = await scoped.list({ ...pageOptions, betas });
1479
- for (const run of response.data) {
1480
- yield run;
1481
- }
1482
- if (!response.hasMore || !response.nextCursor) {
1483
- break;
1484
- }
1485
- cursor = response.nextCursor;
1486
- scoped = scoped.forNextPage();
1487
- }
1470
+ yield* this.withRequestOptions(requestOptions).paginate(
1471
+ pagination?.cursor,
1472
+ (view, cursor) => view.list({ ...pagination, cursor, betas })
1473
+ );
1488
1474
  }
1489
1475
  async getAll(options, requestOptions) {
1490
- const scoped = this.withRequestOptions(requestOptions);
1491
- const runs = [];
1492
- for await (const run of scoped.listAll(options)) {
1493
- runs.push(run);
1494
- }
1495
- return runs;
1476
+ return collectAll(
1477
+ this.withRequestOptions(requestOptions).listAll(options)
1478
+ );
1496
1479
  }
1497
1480
  async cancel(runId, options) {
1498
1481
  const scoped = this.withRequestOptions(options);
@@ -1657,21 +1640,10 @@ var SearchMonitorRunsClient = class extends SearchMonitorsBaseClient {
1657
1640
  * @returns Async generator of Search Monitor runs
1658
1641
  */
1659
1642
  async *listAll(monitorId, options, requestOptions) {
1660
- let scoped = this.withRequestOptions(requestOptions);
1661
- let cursor = void 0;
1662
- const pageOptions = options ? { ...options } : {};
1663
- while (true) {
1664
- pageOptions.cursor = cursor;
1665
- const response = await scoped.list(monitorId, pageOptions);
1666
- for (const run of response.data) {
1667
- yield run;
1668
- }
1669
- if (!response.hasMore || !response.nextCursor) {
1670
- break;
1671
- }
1672
- cursor = response.nextCursor;
1673
- scoped = scoped.forNextPage();
1674
- }
1643
+ yield* this.withRequestOptions(requestOptions).paginate(
1644
+ options?.cursor,
1645
+ (view, cursor) => view.list(monitorId, { ...options, cursor })
1646
+ );
1675
1647
  }
1676
1648
  /**
1677
1649
  * Collect all runs for a Search Monitor into an array
@@ -1681,12 +1653,9 @@ var SearchMonitorRunsClient = class extends SearchMonitorsBaseClient {
1681
1653
  * @returns Promise resolving to an array of all Search Monitor runs
1682
1654
  */
1683
1655
  async getAll(monitorId, options, requestOptions) {
1684
- const scoped = this.withRequestOptions(requestOptions);
1685
- const runs = [];
1686
- for await (const run of scoped.listAll(monitorId, options)) {
1687
- runs.push(run);
1688
- }
1689
- return runs;
1656
+ return collectAll(
1657
+ this.withRequestOptions(requestOptions).listAll(monitorId, options)
1658
+ );
1690
1659
  }
1691
1660
  };
1692
1661
  var SearchMonitorsClient = class extends SearchMonitorsBaseClient {
@@ -1771,21 +1740,10 @@ var SearchMonitorsClient = class extends SearchMonitorsBaseClient {
1771
1740
  * @returns Async generator of Search Monitors
1772
1741
  */
1773
1742
  async *listAll(options, requestOptions) {
1774
- let scoped = this.withRequestOptions(requestOptions);
1775
- let cursor = void 0;
1776
- const pageOptions = options ? { ...options } : {};
1777
- while (true) {
1778
- pageOptions.cursor = cursor;
1779
- const response = await scoped.list(pageOptions);
1780
- for (const monitor of response.data) {
1781
- yield monitor;
1782
- }
1783
- if (!response.hasMore || !response.nextCursor) {
1784
- break;
1785
- }
1786
- cursor = response.nextCursor;
1787
- scoped = scoped.forNextPage();
1788
- }
1743
+ yield* this.withRequestOptions(requestOptions).paginate(
1744
+ options?.cursor,
1745
+ (view, cursor) => view.list({ ...options, cursor })
1746
+ );
1789
1747
  }
1790
1748
  /**
1791
1749
  * Collect all Search Monitors into an array
@@ -1794,12 +1752,9 @@ var SearchMonitorsClient = class extends SearchMonitorsBaseClient {
1794
1752
  * @returns Promise resolving to an array of all Search Monitors
1795
1753
  */
1796
1754
  async getAll(options, requestOptions) {
1797
- const scoped = this.withRequestOptions(requestOptions);
1798
- const monitors = [];
1799
- for await (const monitor of scoped.listAll(options)) {
1800
- monitors.push(monitor);
1801
- }
1802
- return monitors;
1755
+ return collectAll(
1756
+ this.withRequestOptions(requestOptions).listAll(options)
1757
+ );
1803
1758
  }
1804
1759
  };
1805
1760
 
@@ -1813,21 +1768,6 @@ var ResearchBaseClient = class extends RequestScopedClient {
1813
1768
  super();
1814
1769
  this.client = client;
1815
1770
  }
1816
- /** Rejects with `researchRetiredError()`: the Research API has been retired. */
1817
- async request(_endpoint, _method = "POST", _data, _params) {
1818
- throw researchRetiredError();
1819
- }
1820
- /** Rejects with `researchRetiredError()`: the Research API has been retired. */
1821
- async rawRequest(_endpoint, _method = "POST", _data, _params) {
1822
- throw researchRetiredError();
1823
- }
1824
- buildPaginationParams(pagination) {
1825
- const params = {};
1826
- if (!pagination) return params;
1827
- if (pagination.cursor) params.cursor = pagination.cursor;
1828
- if (pagination.limit) params.limit = pagination.limit;
1829
- return params;
1830
- }
1831
1771
  };
1832
1772
 
1833
1773
  // src/research/client.ts
@@ -1835,105 +1775,14 @@ var ResearchClient = class extends ResearchBaseClient {
1835
1775
  constructor(client) {
1836
1776
  super(client);
1837
1777
  }
1838
- async create(params, requestOptions) {
1839
- const scoped = this.withRequestOptions(requestOptions);
1840
- const { instructions, model, outputSchema } = params;
1841
- let schema = outputSchema;
1842
- if (schema && isZodSchema(schema)) {
1843
- schema = zodToJsonSchema(schema);
1844
- }
1845
- const payload = {
1846
- instructions,
1847
- model: model ?? "exa-research-fast"
1848
- };
1849
- if (schema) {
1850
- payload.outputSchema = schema;
1851
- }
1852
- return scoped.request("", "POST", payload);
1778
+ async create(_params, _requestOptions) {
1779
+ throw researchRetiredError();
1853
1780
  }
1854
- get(researchId, options, requestOptions) {
1855
- const scoped = this.withRequestOptions(requestOptions);
1856
- if (options?.stream) {
1857
- const promise = async () => {
1858
- const params = { stream: "true" };
1859
- if (options.events !== void 0) {
1860
- params.events = options.events.toString();
1861
- }
1862
- const resp = await scoped.rawRequest(
1863
- `/${researchId}`,
1864
- "GET",
1865
- void 0,
1866
- params
1867
- );
1868
- if (!resp.ok) {
1869
- throw await exaErrorFromResponse(resp, `/research/v1/${researchId}`);
1870
- }
1871
- if (!resp.body) {
1872
- throw new Error("No response body for SSE stream");
1873
- }
1874
- const reader = resp.body.getReader();
1875
- const decoder = new TextDecoder();
1876
- let buffer = "";
1877
- function processPart(part) {
1878
- const lines = part.split("\n");
1879
- let data = lines.slice(1).join("\n");
1880
- if (data.startsWith("data:")) {
1881
- data = data.slice(5).trimStart();
1882
- }
1883
- try {
1884
- return JSON.parse(data);
1885
- } catch (e) {
1886
- return null;
1887
- }
1888
- }
1889
- async function* streamEvents() {
1890
- try {
1891
- while (true) {
1892
- const { done, value } = await reader.read();
1893
- if (done) break;
1894
- buffer += decoder.decode(value, { stream: true });
1895
- let parts = buffer.split("\n\n");
1896
- buffer = parts.pop() ?? "";
1897
- for (const part of parts) {
1898
- const processed = processPart(part);
1899
- if (processed) {
1900
- yield processed;
1901
- }
1902
- }
1903
- }
1904
- if (buffer.trim()) {
1905
- const processed = processPart(buffer.trim());
1906
- if (processed) {
1907
- yield processed;
1908
- }
1909
- }
1910
- } finally {
1911
- try {
1912
- await reader.cancel();
1913
- } catch {
1914
- }
1915
- }
1916
- }
1917
- return streamEvents();
1918
- };
1919
- return promise();
1920
- } else {
1921
- const params = { stream: "false" };
1922
- if (options?.events !== void 0) {
1923
- params.events = options.events.toString();
1924
- }
1925
- return scoped.request(
1926
- `/${researchId}`,
1927
- "GET",
1928
- void 0,
1929
- params
1930
- );
1931
- }
1781
+ get(_researchId, _options, _requestOptions) {
1782
+ return Promise.reject(researchRetiredError());
1932
1783
  }
1933
- async list(options, requestOptions) {
1934
- const scoped = this.withRequestOptions(requestOptions);
1935
- const params = this.buildPaginationParams(options);
1936
- return scoped.request("", "GET", void 0, params);
1784
+ async list(_options, _requestOptions) {
1785
+ throw researchRetiredError();
1937
1786
  }
1938
1787
  async pollUntilFinished(_researchId, _options, _requestOptions) {
1939
1788
  throw researchRetiredError();
@@ -2115,21 +1964,10 @@ var EventsClient = class extends WebsetsBaseClient {
2115
1964
  * @returns Async generator of Events
2116
1965
  */
2117
1966
  async *listAll(options, requestOptions) {
2118
- let scoped = this.withRequestOptions(requestOptions);
2119
- let cursor = void 0;
2120
- const pageOptions = options ? { ...options } : {};
2121
- while (true) {
2122
- pageOptions.cursor = cursor;
2123
- const response = await scoped.list(pageOptions);
2124
- for (const event of response.data) {
2125
- yield event;
2126
- }
2127
- if (!response.hasMore || !response.nextCursor) {
2128
- break;
2129
- }
2130
- cursor = response.nextCursor;
2131
- scoped = scoped.forNextPage();
2132
- }
1967
+ yield* this.withRequestOptions(requestOptions).paginate(
1968
+ options?.cursor,
1969
+ (view, cursor) => view.list({ ...options, cursor })
1970
+ );
2133
1971
  }
2134
1972
  /**
2135
1973
  * Collect all Events into an array
@@ -2138,12 +1976,9 @@ var EventsClient = class extends WebsetsBaseClient {
2138
1976
  * @returns Promise resolving to an array of all Events
2139
1977
  */
2140
1978
  async getAll(options, requestOptions) {
2141
- const scoped = this.withRequestOptions(requestOptions);
2142
- const events = [];
2143
- for await (const event of scoped.listAll(options)) {
2144
- events.push(event);
2145
- }
2146
- return events;
1979
+ return collectAll(
1980
+ this.withRequestOptions(requestOptions).listAll(options)
1981
+ );
2147
1982
  }
2148
1983
  };
2149
1984
 
@@ -2488,21 +2323,10 @@ var ImportsClient = class extends WebsetsBaseClient {
2488
2323
  * @returns Async generator of Imports
2489
2324
  */
2490
2325
  async *listAll(options, requestOptions) {
2491
- let scoped = this.withRequestOptions(requestOptions);
2492
- let cursor = void 0;
2493
- const pageOptions = options ? { ...options } : {};
2494
- while (true) {
2495
- pageOptions.cursor = cursor;
2496
- const response = await scoped.list(pageOptions);
2497
- for (const importItem of response.data) {
2498
- yield importItem;
2499
- }
2500
- if (!response.hasMore || !response.nextCursor) {
2501
- break;
2502
- }
2503
- cursor = response.nextCursor;
2504
- scoped = scoped.forNextPage();
2505
- }
2326
+ yield* this.withRequestOptions(requestOptions).paginate(
2327
+ options?.cursor,
2328
+ (view, cursor) => view.list({ ...options, cursor })
2329
+ );
2506
2330
  }
2507
2331
  /**
2508
2332
  * Collect all Imports into an array
@@ -2511,12 +2335,9 @@ var ImportsClient = class extends WebsetsBaseClient {
2511
2335
  * @returns Promise resolving to an array of all Imports
2512
2336
  */
2513
2337
  async getAll(options, requestOptions) {
2514
- const scoped = this.withRequestOptions(requestOptions);
2515
- const imports = [];
2516
- for await (const importItem of scoped.listAll(options)) {
2517
- imports.push(importItem);
2518
- }
2519
- return imports;
2338
+ return collectAll(
2339
+ this.withRequestOptions(requestOptions).listAll(options)
2340
+ );
2520
2341
  }
2521
2342
  };
2522
2343
 
@@ -2550,21 +2371,10 @@ var WebsetItemsClient = class extends WebsetsBaseClient {
2550
2371
  * @returns Async generator of Webset Items
2551
2372
  */
2552
2373
  async *listAll(websetId, options, requestOptions) {
2553
- let scoped = this.withRequestOptions(requestOptions);
2554
- let cursor = void 0;
2555
- const pageOptions = options ? { ...options } : {};
2556
- while (true) {
2557
- pageOptions.cursor = cursor;
2558
- const response = await scoped.list(websetId, pageOptions);
2559
- for (const item of response.data) {
2560
- yield item;
2561
- }
2562
- if (!response.hasMore || !response.nextCursor) {
2563
- break;
2564
- }
2565
- cursor = response.nextCursor;
2566
- scoped = scoped.forNextPage();
2567
- }
2374
+ yield* this.withRequestOptions(requestOptions).paginate(
2375
+ options?.cursor,
2376
+ (view, cursor) => view.list(websetId, { ...options, cursor })
2377
+ );
2568
2378
  }
2569
2379
  /**
2570
2380
  * Collect all items from a Webset into an array
@@ -2574,12 +2384,9 @@ var WebsetItemsClient = class extends WebsetsBaseClient {
2574
2384
  * @returns Promise resolving to an array of all Webset Items
2575
2385
  */
2576
2386
  async getAll(websetId, options, requestOptions) {
2577
- const scoped = this.withRequestOptions(requestOptions);
2578
- const items = [];
2579
- for await (const item of scoped.listAll(websetId, options)) {
2580
- items.push(item);
2581
- }
2582
- return items;
2387
+ return collectAll(
2388
+ this.withRequestOptions(requestOptions).listAll(websetId, options)
2389
+ );
2583
2390
  }
2584
2391
  /**
2585
2392
  * Get an Item by ID
@@ -2718,21 +2525,10 @@ var WebsetMonitorsClient = class extends WebsetsBaseClient {
2718
2525
  * @returns Async generator of Monitors
2719
2526
  */
2720
2527
  async *listAll(options, requestOptions) {
2721
- let scoped = this.withRequestOptions(requestOptions);
2722
- let cursor = void 0;
2723
- const pageOptions = options ? { ...options } : {};
2724
- while (true) {
2725
- pageOptions.cursor = cursor;
2726
- const response = await scoped.list(pageOptions);
2727
- for (const monitor of response.data) {
2728
- yield monitor;
2729
- }
2730
- if (!response.hasMore || !response.nextCursor) {
2731
- break;
2732
- }
2733
- cursor = response.nextCursor;
2734
- scoped = scoped.forNextPage();
2735
- }
2528
+ yield* this.withRequestOptions(requestOptions).paginate(
2529
+ options?.cursor,
2530
+ (view, cursor) => view.list({ ...options, cursor })
2531
+ );
2736
2532
  }
2737
2533
  /**
2738
2534
  * Collect all Monitors into an array
@@ -2741,12 +2537,9 @@ var WebsetMonitorsClient = class extends WebsetsBaseClient {
2741
2537
  * @returns Promise resolving to an array of all Monitors
2742
2538
  */
2743
2539
  async getAll(options, requestOptions) {
2744
- const scoped = this.withRequestOptions(requestOptions);
2745
- const monitors = [];
2746
- for await (const monitor of scoped.listAll(options)) {
2747
- monitors.push(monitor);
2748
- }
2749
- return monitors;
2540
+ return collectAll(
2541
+ this.withRequestOptions(requestOptions).listAll(options)
2542
+ );
2750
2543
  }
2751
2544
  };
2752
2545
 
@@ -2844,21 +2637,10 @@ var WebsetWebhooksClient = class extends WebsetsBaseClient {
2844
2637
  * @returns Async generator of Webhooks
2845
2638
  */
2846
2639
  async *listAll(options, requestOptions) {
2847
- let scoped = this.withRequestOptions(requestOptions);
2848
- let cursor = void 0;
2849
- const pageOptions = options ? { ...options } : {};
2850
- while (true) {
2851
- pageOptions.cursor = cursor;
2852
- const response = await scoped.list(pageOptions);
2853
- for (const webhook of response.data) {
2854
- yield webhook;
2855
- }
2856
- if (!response.hasMore || !response.nextCursor) {
2857
- break;
2858
- }
2859
- cursor = response.nextCursor;
2860
- scoped = scoped.forNextPage();
2861
- }
2640
+ yield* this.withRequestOptions(requestOptions).paginate(
2641
+ options?.cursor,
2642
+ (view, cursor) => view.list({ ...options, cursor })
2643
+ );
2862
2644
  }
2863
2645
  /**
2864
2646
  * Collect all Webhooks into an array
@@ -2867,12 +2649,9 @@ var WebsetWebhooksClient = class extends WebsetsBaseClient {
2867
2649
  * @returns Promise resolving to an array of all Webhooks
2868
2650
  */
2869
2651
  async getAll(options, requestOptions) {
2870
- const scoped = this.withRequestOptions(requestOptions);
2871
- const webhooks = [];
2872
- for await (const webhook of scoped.listAll(options)) {
2873
- webhooks.push(webhook);
2874
- }
2875
- return webhooks;
2652
+ return collectAll(
2653
+ this.withRequestOptions(requestOptions).listAll(options)
2654
+ );
2876
2655
  }
2877
2656
  /**
2878
2657
  * Update a Webhook
@@ -2925,21 +2704,10 @@ var WebsetWebhooksClient = class extends WebsetsBaseClient {
2925
2704
  * @returns Async generator of Webhook attempts
2926
2705
  */
2927
2706
  async *listAllAttempts(id, options, requestOptions) {
2928
- let scoped = this.withRequestOptions(requestOptions);
2929
- let cursor = void 0;
2930
- const pageOptions = options ? { ...options } : {};
2931
- while (true) {
2932
- pageOptions.cursor = cursor;
2933
- const response = await scoped.listAttempts(id, pageOptions);
2934
- for (const attempt of response.data) {
2935
- yield attempt;
2936
- }
2937
- if (!response.hasMore || !response.nextCursor) {
2938
- break;
2939
- }
2940
- cursor = response.nextCursor;
2941
- scoped = scoped.forNextPage();
2942
- }
2707
+ yield* this.withRequestOptions(requestOptions).paginate(
2708
+ options?.cursor,
2709
+ (view, cursor) => view.listAttempts(id, { ...options, cursor })
2710
+ );
2943
2711
  }
2944
2712
  /**
2945
2713
  * Collect all attempts for a Webhook into an array
@@ -2949,12 +2717,9 @@ var WebsetWebhooksClient = class extends WebsetsBaseClient {
2949
2717
  * @returns Promise resolving to an array of all Webhook attempts
2950
2718
  */
2951
2719
  async getAllAttempts(id, options, requestOptions) {
2952
- const scoped = this.withRequestOptions(requestOptions);
2953
- const attempts = [];
2954
- for await (const attempt of scoped.listAllAttempts(id, options)) {
2955
- attempts.push(attempt);
2956
- }
2957
- return attempts;
2720
+ return collectAll(
2721
+ this.withRequestOptions(requestOptions).listAllAttempts(id, options)
2722
+ );
2958
2723
  }
2959
2724
  };
2960
2725
 
@@ -3053,21 +2818,10 @@ var WebsetsClient = class extends WebsetsBaseClient {
3053
2818
  * @returns Async generator of Websets
3054
2819
  */
3055
2820
  async *listAll(options, requestOptions) {
3056
- let scoped = this.withRequestOptions(requestOptions);
3057
- let cursor = void 0;
3058
- const pageOptions = options ? { ...options } : {};
3059
- while (true) {
3060
- pageOptions.cursor = cursor;
3061
- const response = await scoped.list(pageOptions);
3062
- for (const webset of response.data) {
3063
- yield webset;
3064
- }
3065
- if (!response.hasMore || !response.nextCursor) {
3066
- break;
3067
- }
3068
- cursor = response.nextCursor;
3069
- scoped = scoped.forNextPage();
3070
- }
2821
+ yield* this.withRequestOptions(requestOptions).paginate(
2822
+ options?.cursor,
2823
+ (view, cursor) => view.list({ ...options, cursor })
2824
+ );
3071
2825
  }
3072
2826
  /**
3073
2827
  * Collect all Websets into an array
@@ -3076,12 +2830,9 @@ var WebsetsClient = class extends WebsetsBaseClient {
3076
2830
  * @returns Promise resolving to an array of all Websets
3077
2831
  */
3078
2832
  async getAll(options, requestOptions) {
3079
- const scoped = this.withRequestOptions(requestOptions);
3080
- const websets = [];
3081
- for await (const webset of scoped.listAll(options)) {
3082
- websets.push(webset);
3083
- }
3084
- return websets;
2833
+ return collectAll(
2834
+ this.withRequestOptions(requestOptions).listAll(options)
2835
+ );
3085
2836
  }
3086
2837
  /**
3087
2838
  * Update a Webset
@@ -3588,7 +3339,47 @@ function isResponsesInput(value) {
3588
3339
  var fetchImpl = typeof global !== "undefined" && global.fetch ? global.fetch : import_cross_fetch.default;
3589
3340
  var HeadersImpl = typeof global !== "undefined" && global.Headers ? global.Headers : import_cross_fetch.Headers;
3590
3341
  var DEFAULT_MAX_CHARACTERS = 1e4;
3342
+ var DEFAULT_BASE_URL = "https://api.exa.ai";
3343
+ function resolveBaseURL(baseURL) {
3344
+ if (baseURL === void 0) {
3345
+ const fromEnvironment = typeof process === "undefined" ? void 0 : process.env?.EXA_BASE_URL?.trim();
3346
+ baseURL = fromEnvironment || DEFAULT_BASE_URL;
3347
+ }
3348
+ return baseURL.replace(/\/+$/, "");
3349
+ }
3350
+ function clientArguments(second, third) {
3351
+ if (typeof URL !== "undefined" && second instanceof URL) {
3352
+ second = String(second);
3353
+ }
3354
+ if (typeof second === "object" && second !== null) {
3355
+ if (third !== void 0) {
3356
+ throw new TypeError(
3357
+ "Pass the client options once, as the second argument or as the third after a base URL"
3358
+ );
3359
+ }
3360
+ return { baseURL: second.baseURL, options: second };
3361
+ }
3362
+ if (second != null && third?.baseURL !== void 0) {
3363
+ throw new TypeError(
3364
+ "Pass the base URL once, as the second argument or as options.baseURL"
3365
+ );
3366
+ }
3367
+ return { baseURL: second ?? third?.baseURL, options: third };
3368
+ }
3591
3369
  var DYNAMIC_HIGHLIGHTS_BETA = "dynamic-highlights-2026-08-28";
3370
+ async function resolveApiKey(apiKey, signal) {
3371
+ if (signal?.aborted) {
3372
+ throw signal.reason;
3373
+ }
3374
+ const pending = Promise.resolve(apiKey({ signal }));
3375
+ const key = await (signal ? untilAborted(pending, signal) : pending);
3376
+ if (typeof key !== "string" || !/^[\x21-\x7E]+$/.test(key)) {
3377
+ throw new TypeError(
3378
+ "apiKey must return a non-empty string of visible ASCII characters"
3379
+ );
3380
+ }
3381
+ return key;
3382
+ }
3592
3383
  var loggedWarnings = /* @__PURE__ */ new Set();
3593
3384
  function logWarningOnce(warning, context) {
3594
3385
  const request = `${context.method} ${context.endpoint}`;
@@ -3640,6 +3431,24 @@ function costDollarsOf(payload) {
3640
3431
  }
3641
3432
  return costDollars;
3642
3433
  }
3434
+ function streamErrorOf(payload, path, requestIdHeader) {
3435
+ const event = payload?.type === "error" ? payload : payload?.tag === "ERROR" ? payload.payload : void 0;
3436
+ if (typeof event !== "object" || event === null) {
3437
+ return void 0;
3438
+ }
3439
+ const { code, message, tag } = event.error ?? {};
3440
+ const requestId = typeof event.requestId === "string" ? event.requestId : requestIdHeader;
3441
+ return new ExaError(
3442
+ typeof message === "string" && message ? message : "Unknown error",
3443
+ typeof code === "number" ? code : 500 /* InternalServerError */,
3444
+ void 0,
3445
+ path,
3446
+ {
3447
+ requestId: requestId ?? void 0,
3448
+ tag: typeof tag === "string" ? tag : void 0
3449
+ }
3450
+ );
3451
+ }
3643
3452
  function citationsFromResults(results) {
3644
3453
  if (!Array.isArray(results)) {
3645
3454
  return void 0;
@@ -3666,36 +3475,47 @@ function withJsonSummarySchema(contents) {
3666
3475
  };
3667
3476
  }
3668
3477
  var Exa2 = class {
3669
- /**
3670
- * Constructs the Exa API client.
3671
- * @param {string} apiKey - The API key for authentication.
3672
- * @param {string} [baseURL] - The base URL of the Exa API.
3673
- * @param {ExaClientOptions} [options] - Client-wide settings (`timeout`, `warnings`).
3674
- * @throws {RangeError} When `options.timeout` is not an integer from 1 to 2147483647.
3675
- * @throws {TypeError} When `options.warnings` is not `"log"`, `"silent"` or a function.
3676
- */
3677
- constructor(apiKey, baseURL = "https://api.exa.ai", options) {
3478
+ constructor(apiKey, baseURLOrOptions, maybeOptions) {
3678
3479
  this.toolRegistry = new ToolRegistry();
3679
- this.baseURL = baseURL;
3480
+ const { baseURL, options } = clientArguments(
3481
+ baseURLOrOptions,
3482
+ maybeOptions
3483
+ );
3484
+ this.baseURL = resolveBaseURL(baseURL);
3680
3485
  this.warningHandler = warningHandlerFor(options?.warnings);
3681
3486
  setClientDefaults(
3682
3487
  this,
3683
3488
  options?.timeout === void 0 ? void 0 : { timeout: validateTimeout(options.timeout) }
3684
3489
  );
3685
- if (!apiKey) {
3686
- apiKey = process.env.EXA_API_KEY;
3490
+ const customFetch = options?.fetch;
3491
+ if (customFetch !== void 0 && typeof customFetch !== "function") {
3492
+ throw new TypeError("options.fetch must be a function");
3493
+ }
3494
+ const send = customFetch ?? fetchImpl;
3495
+ this.fetcher = (input, init) => send(input, init);
3496
+ if (typeof apiKey === "function") {
3497
+ this.apiKeySource = apiKey;
3498
+ this.headers = new HeadersImpl({
3499
+ "Content-Type": "application/json",
3500
+ "User-Agent": `exa-node ${package_default.version}`
3501
+ });
3502
+ } else {
3503
+ this.apiKeySource = void 0;
3687
3504
  if (!apiKey) {
3688
- throw new ExaError(
3689
- "API key must be provided as an argument or as an environment variable (EXA_API_KEY)",
3690
- 401 /* Unauthorized */
3691
- );
3505
+ apiKey = process.env.EXA_API_KEY;
3506
+ if (!apiKey) {
3507
+ throw new ExaError(
3508
+ "API key must be provided as an argument or as an environment variable (EXA_API_KEY)",
3509
+ 401 /* Unauthorized */
3510
+ );
3511
+ }
3692
3512
  }
3513
+ this.headers = new HeadersImpl({
3514
+ "x-api-key": apiKey,
3515
+ "Content-Type": "application/json",
3516
+ "User-Agent": `exa-node ${package_default.version}`
3517
+ });
3693
3518
  }
3694
- this.headers = new HeadersImpl({
3695
- "x-api-key": apiKey,
3696
- "Content-Type": "application/json",
3697
- "User-Agent": `exa-node ${package_default.version}`
3698
- });
3699
3519
  this.websets = new WebsetsClient(this);
3700
3520
  this.research = new ResearchClient(this);
3701
3521
  this.monitors = new SearchMonitorsClient(this);
@@ -3790,6 +3610,22 @@ var Exa2 = class {
3790
3610
  }
3791
3611
  return { query, ...body };
3792
3612
  }
3613
+ /**
3614
+ * Returns the headers a request sends, which are `headers` with the call's
3615
+ * `extraHeaders` on top and, when `apiKey` is a function, the key it returns
3616
+ * as `x-api-key` beneath them. The function is called only when neither
3617
+ * sets `x-api-key` nor removes it with `null`, whatever its case. Called
3618
+ * inside each request's lifecycle, so the request's `signal` and `timeout`
3619
+ * also bound the wait for the key.
3620
+ */
3621
+ async requestHeaders(headers, extraHeaders, signal) {
3622
+ const merged = mergeRequestHeaders(headers, extraHeaders);
3623
+ if (!this.apiKeySource || setsHeader(headers, "x-api-key") || setsHeader(extraHeaders, "x-api-key")) {
3624
+ return merged;
3625
+ }
3626
+ const apiKey = await resolveApiKey(this.apiKeySource, signal);
3627
+ return mergeRequestHeaders({ "x-api-key": apiKey }, merged);
3628
+ }
3793
3629
  /**
3794
3630
  * Makes a request to the Exa API.
3795
3631
  * @param {string} endpoint - The API endpoint to call.
@@ -3831,17 +3667,17 @@ var Exa2 = class {
3831
3667
  if (headers) {
3832
3668
  combinedHeaders = { ...combinedHeaders, ...headers };
3833
3669
  }
3834
- combinedHeaders = mergeRequestHeaders(
3835
- combinedHeaders,
3836
- requestOptions?.headers
3837
- );
3838
3670
  const { signal, dispose, toRequestError } = resolveRequestSignal(
3839
3671
  withClientDefaults(this, requestOptions)
3840
3672
  );
3841
3673
  try {
3842
- const response = await fetchImpl(url, {
3674
+ const response = await this.fetcher(url, {
3843
3675
  method,
3844
- headers: combinedHeaders,
3676
+ headers: await this.requestHeaders(
3677
+ combinedHeaders,
3678
+ requestOptions?.headers,
3679
+ signal
3680
+ ),
3845
3681
  body: body ? JSON.stringify(body) : void 0,
3846
3682
  signal
3847
3683
  });
@@ -3906,15 +3742,15 @@ var Exa2 = class {
3906
3742
  if (headers) {
3907
3743
  combinedHeaders = { ...combinedHeaders, ...headers };
3908
3744
  }
3909
- combinedHeaders = mergeRequestHeaders(
3910
- combinedHeaders,
3911
- requestOptions?.headers
3912
- );
3913
3745
  const { signal, dispose, needsDispose, stopTimeout, toRequestError } = resolveRequestSignal(withClientDefaults(this, requestOptions));
3914
3746
  try {
3915
- const response = await fetchImpl(url, {
3747
+ const response = await this.fetcher(url, {
3916
3748
  method,
3917
- headers: combinedHeaders,
3749
+ headers: await this.requestHeaders(
3750
+ combinedHeaders,
3751
+ requestOptions?.headers,
3752
+ signal
3753
+ ),
3918
3754
  body: body ? JSON.stringify(body) : void 0,
3919
3755
  signal
3920
3756
  });
@@ -4005,6 +3841,9 @@ var Exa2 = class {
4005
3841
  * A search without `outputSchema` has no text to stream. Its stream yields
4006
3842
  * one chunk with the results as `citations`, then the warnings chunk when
4007
3843
  * the API returns warnings. Call `search()` for every field of the results.
3844
+ *
3845
+ * If the API reports an error partway through, the stream yields the chunks
3846
+ * before it and then rejects with an `ExaError`.
4008
3847
  * @param {RequestOptions} [requestOptions] - Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`).
4009
3848
  */
4010
3849
  streamSearch(query, options, requestOptions) {
@@ -4258,18 +4097,29 @@ var Exa2 = class {
4258
4097
  continue;
4259
4098
  }
4260
4099
  this.reportWarnings(endpoint, "POST", chunkData, requestIdHeader);
4100
+ const error = streamErrorOf(chunkData, endpoint, requestIdHeader);
4101
+ if (error) {
4102
+ throw error;
4103
+ }
4261
4104
  yield* this.payloadChunks(chunkData);
4262
4105
  }
4263
4106
  }
4264
4107
  if (buffer.startsWith("data: ")) {
4265
4108
  const leftover = buffer.replace(/^data:\s*/, "").trim();
4266
4109
  if (leftover && leftover !== "[DONE]") {
4110
+ let error;
4267
4111
  try {
4268
4112
  const chunkData = JSON.parse(leftover);
4269
4113
  this.reportWarnings(endpoint, "POST", chunkData, requestIdHeader);
4270
- yield* this.payloadChunks(chunkData);
4114
+ error = streamErrorOf(chunkData, endpoint, requestIdHeader);
4115
+ if (!error) {
4116
+ yield* this.payloadChunks(chunkData);
4117
+ }
4271
4118
  } catch (e) {
4272
4119
  }
4120
+ if (error) {
4121
+ throw error;
4122
+ }
4273
4123
  }
4274
4124
  }
4275
4125
  } finally {