@xata.io/client 0.0.0-alpha.vebc4a36 → 0.0.0-alpha.vec0147b

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
@@ -91,8 +91,10 @@ function getEnvironment() {
91
91
  apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
92
92
  databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
93
93
  branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
94
- envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
95
- fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
94
+ deployPreview: process.env.XATA_PREVIEW,
95
+ deployPreviewBranch: process.env.XATA_PREVIEW_BRANCH,
96
+ vercelGitCommitRef: process.env.VERCEL_GIT_COMMIT_REF,
97
+ vercelGitRepoOwner: process.env.VERCEL_GIT_REPO_OWNER
96
98
  };
97
99
  }
98
100
  } catch (err) {
@@ -103,8 +105,10 @@ function getEnvironment() {
103
105
  apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
104
106
  databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
105
107
  branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
106
- envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
107
- fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
108
+ deployPreview: Deno.env.get("XATA_PREVIEW"),
109
+ deployPreviewBranch: Deno.env.get("XATA_PREVIEW_BRANCH"),
110
+ vercelGitCommitRef: Deno.env.get("VERCEL_GIT_COMMIT_REF"),
111
+ vercelGitRepoOwner: Deno.env.get("VERCEL_GIT_REPO_OWNER")
108
112
  };
109
113
  }
110
114
  } catch (err) {
@@ -113,8 +117,10 @@ function getEnvironment() {
113
117
  apiKey: getGlobalApiKey(),
114
118
  databaseURL: getGlobalDatabaseURL(),
115
119
  branch: getGlobalBranch(),
116
- envBranch: void 0,
117
- fallbackBranch: getGlobalFallbackBranch()
120
+ deployPreview: void 0,
121
+ deployPreviewBranch: void 0,
122
+ vercelGitCommitRef: void 0,
123
+ vercelGitRepoOwner: void 0
118
124
  };
119
125
  }
120
126
  function getEnableBrowserVariable() {
@@ -157,36 +163,48 @@ function getGlobalBranch() {
157
163
  return void 0;
158
164
  }
159
165
  }
160
- function getGlobalFallbackBranch() {
166
+ function getDatabaseURL() {
161
167
  try {
162
- return XATA_FALLBACK_BRANCH;
168
+ const { databaseURL } = getEnvironment();
169
+ return databaseURL;
163
170
  } catch (err) {
164
171
  return void 0;
165
172
  }
166
173
  }
167
- async function getGitBranch() {
168
- const cmd = ["git", "branch", "--show-current"];
169
- const fullCmd = cmd.join(" ");
170
- const nodeModule = ["child", "process"].join("_");
171
- const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
174
+ function getAPIKey() {
172
175
  try {
173
- const { execSync } = await import(nodeModule);
174
- return execSync(fullCmd, execOptions).toString().trim();
176
+ const { apiKey } = getEnvironment();
177
+ return apiKey;
175
178
  } catch (err) {
179
+ return void 0;
176
180
  }
181
+ }
182
+ function getBranch() {
177
183
  try {
178
- if (isObject(Deno)) {
179
- const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
180
- return new TextDecoder().decode(await process2.output()).trim();
181
- }
184
+ const { branch } = getEnvironment();
185
+ return branch ?? "main";
182
186
  } catch (err) {
187
+ return void 0;
183
188
  }
184
189
  }
185
-
186
- function getAPIKey() {
190
+ function buildPreviewBranchName({ org, branch }) {
191
+ return `preview-${org}-${branch}`;
192
+ }
193
+ function getPreviewBranch() {
187
194
  try {
188
- const { apiKey } = getEnvironment();
189
- return apiKey;
195
+ const { deployPreview, deployPreviewBranch, vercelGitCommitRef, vercelGitRepoOwner } = getEnvironment();
196
+ if (deployPreviewBranch)
197
+ return deployPreviewBranch;
198
+ switch (deployPreview) {
199
+ case "vercel": {
200
+ if (!vercelGitCommitRef || !vercelGitRepoOwner) {
201
+ console.warn("XATA_PREVIEW=vercel but VERCEL_GIT_COMMIT_REF or VERCEL_GIT_REPO_OWNER is not valid");
202
+ return void 0;
203
+ }
204
+ return buildPreviewBranchName({ org: vercelGitRepoOwner, branch: vercelGitCommitRef });
205
+ }
206
+ }
207
+ return void 0;
190
208
  } catch (err) {
191
209
  return void 0;
192
210
  }
@@ -299,7 +317,180 @@ function generateUUID() {
299
317
  });
300
318
  }
301
319
 
302
- const VERSION = "0.22.1";
320
+ async function getBytes(stream, onChunk) {
321
+ const reader = stream.getReader();
322
+ let result;
323
+ while (!(result = await reader.read()).done) {
324
+ onChunk(result.value);
325
+ }
326
+ }
327
+ function getLines(onLine) {
328
+ let buffer;
329
+ let position;
330
+ let fieldLength;
331
+ let discardTrailingNewline = false;
332
+ return function onChunk(arr) {
333
+ if (buffer === void 0) {
334
+ buffer = arr;
335
+ position = 0;
336
+ fieldLength = -1;
337
+ } else {
338
+ buffer = concat(buffer, arr);
339
+ }
340
+ const bufLength = buffer.length;
341
+ let lineStart = 0;
342
+ while (position < bufLength) {
343
+ if (discardTrailingNewline) {
344
+ if (buffer[position] === 10 /* NewLine */) {
345
+ lineStart = ++position;
346
+ }
347
+ discardTrailingNewline = false;
348
+ }
349
+ let lineEnd = -1;
350
+ for (; position < bufLength && lineEnd === -1; ++position) {
351
+ switch (buffer[position]) {
352
+ case 58 /* Colon */:
353
+ if (fieldLength === -1) {
354
+ fieldLength = position - lineStart;
355
+ }
356
+ break;
357
+ case 13 /* CarriageReturn */:
358
+ discardTrailingNewline = true;
359
+ case 10 /* NewLine */:
360
+ lineEnd = position;
361
+ break;
362
+ }
363
+ }
364
+ if (lineEnd === -1) {
365
+ break;
366
+ }
367
+ onLine(buffer.subarray(lineStart, lineEnd), fieldLength);
368
+ lineStart = position;
369
+ fieldLength = -1;
370
+ }
371
+ if (lineStart === bufLength) {
372
+ buffer = void 0;
373
+ } else if (lineStart !== 0) {
374
+ buffer = buffer.subarray(lineStart);
375
+ position -= lineStart;
376
+ }
377
+ };
378
+ }
379
+ function getMessages(onId, onRetry, onMessage) {
380
+ let message = newMessage();
381
+ const decoder = new TextDecoder();
382
+ return function onLine(line, fieldLength) {
383
+ if (line.length === 0) {
384
+ onMessage?.(message);
385
+ message = newMessage();
386
+ } else if (fieldLength > 0) {
387
+ const field = decoder.decode(line.subarray(0, fieldLength));
388
+ const valueOffset = fieldLength + (line[fieldLength + 1] === 32 /* Space */ ? 2 : 1);
389
+ const value = decoder.decode(line.subarray(valueOffset));
390
+ switch (field) {
391
+ case "data":
392
+ message.data = message.data ? message.data + "\n" + value : value;
393
+ break;
394
+ case "event":
395
+ message.event = value;
396
+ break;
397
+ case "id":
398
+ onId(message.id = value);
399
+ break;
400
+ case "retry":
401
+ const retry = parseInt(value, 10);
402
+ if (!isNaN(retry)) {
403
+ onRetry(message.retry = retry);
404
+ }
405
+ break;
406
+ }
407
+ }
408
+ };
409
+ }
410
+ function concat(a, b) {
411
+ const res = new Uint8Array(a.length + b.length);
412
+ res.set(a);
413
+ res.set(b, a.length);
414
+ return res;
415
+ }
416
+ function newMessage() {
417
+ return {
418
+ data: "",
419
+ event: "",
420
+ id: "",
421
+ retry: void 0
422
+ };
423
+ }
424
+ const EventStreamContentType = "text/event-stream";
425
+ const LastEventId = "last-event-id";
426
+ function fetchEventSource(input, {
427
+ signal: inputSignal,
428
+ headers: inputHeaders,
429
+ onopen: inputOnOpen,
430
+ onmessage,
431
+ onclose,
432
+ onerror,
433
+ fetch: inputFetch,
434
+ ...rest
435
+ }) {
436
+ return new Promise((resolve, reject) => {
437
+ const headers = { ...inputHeaders };
438
+ if (!headers.accept) {
439
+ headers.accept = EventStreamContentType;
440
+ }
441
+ let curRequestController;
442
+ function dispose() {
443
+ curRequestController.abort();
444
+ }
445
+ inputSignal?.addEventListener("abort", () => {
446
+ dispose();
447
+ resolve();
448
+ });
449
+ const fetchImpl = inputFetch ?? fetch;
450
+ const onopen = inputOnOpen ?? defaultOnOpen;
451
+ async function create() {
452
+ curRequestController = new AbortController();
453
+ try {
454
+ const response = await fetchImpl(input, {
455
+ ...rest,
456
+ headers,
457
+ signal: curRequestController.signal
458
+ });
459
+ await onopen(response);
460
+ await getBytes(
461
+ response.body,
462
+ getLines(
463
+ getMessages(
464
+ (id) => {
465
+ if (id) {
466
+ headers[LastEventId] = id;
467
+ } else {
468
+ delete headers[LastEventId];
469
+ }
470
+ },
471
+ (_retry) => {
472
+ },
473
+ onmessage
474
+ )
475
+ )
476
+ );
477
+ onclose?.();
478
+ dispose();
479
+ resolve();
480
+ } catch (err) {
481
+ }
482
+ }
483
+ create();
484
+ });
485
+ }
486
+ function defaultOnOpen(response) {
487
+ const contentType = response.headers?.get("content-type");
488
+ if (!contentType?.startsWith(EventStreamContentType)) {
489
+ throw new Error(`Expected content-type to be ${EventStreamContentType}, Actual: ${contentType}`);
490
+ }
491
+ }
492
+
493
+ const VERSION = "0.23.3";
303
494
 
304
495
  class ErrorWithCause extends Error {
305
496
  constructor(message, options) {
@@ -383,7 +574,7 @@ async function fetch$1({
383
574
  headers: customHeaders,
384
575
  pathParams,
385
576
  queryParams,
386
- fetchImpl,
577
+ fetch: fetch2,
387
578
  apiKey,
388
579
  endpoint,
389
580
  apiUrl,
@@ -396,7 +587,7 @@ async function fetch$1({
396
587
  xataAgentExtra,
397
588
  fetchOptions = {}
398
589
  }) {
399
- pool.setFetch(fetchImpl);
590
+ pool.setFetch(fetch2);
400
591
  return await trace(
401
592
  `${method.toUpperCase()} ${path}`,
402
593
  async ({ setAttributes }) => {
@@ -458,6 +649,59 @@ async function fetch$1({
458
649
  { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
459
650
  );
460
651
  }
652
+ function fetchSSERequest({
653
+ url: path,
654
+ method,
655
+ body,
656
+ headers: customHeaders,
657
+ pathParams,
658
+ queryParams,
659
+ fetch: fetch2,
660
+ apiKey,
661
+ endpoint,
662
+ apiUrl,
663
+ workspacesApiUrl,
664
+ onMessage,
665
+ onError,
666
+ onClose,
667
+ signal,
668
+ clientID,
669
+ sessionID,
670
+ clientName,
671
+ xataAgentExtra
672
+ }) {
673
+ const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
674
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
675
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
676
+ void fetchEventSource(url, {
677
+ method,
678
+ body: JSON.stringify(body),
679
+ fetch: fetch2,
680
+ signal,
681
+ headers: {
682
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
683
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
684
+ "X-Xata-Agent": compact([
685
+ ["client", "TS_SDK"],
686
+ ["version", VERSION],
687
+ isDefined(clientName) ? ["service", clientName] : void 0,
688
+ ...Object.entries(xataAgentExtra ?? {})
689
+ ]).map(([key, value]) => `${key}=${value}`).join("; "),
690
+ ...customHeaders,
691
+ Authorization: `Bearer ${apiKey}`,
692
+ "Content-Type": "application/json"
693
+ },
694
+ onmessage(ev) {
695
+ onMessage?.(JSON.parse(ev.data));
696
+ },
697
+ onerror(ev) {
698
+ onError?.(JSON.parse(ev.data));
699
+ },
700
+ onclose() {
701
+ onClose?.();
702
+ }
703
+ });
704
+ }
461
705
  function parseUrl(url) {
462
706
  try {
463
707
  const { host, protocol } = new URL(url);
@@ -488,6 +732,12 @@ const deleteBranch = (variables, signal) => dataPlaneFetch({
488
732
  ...variables,
489
733
  signal
490
734
  });
735
+ const copyBranch = (variables, signal) => dataPlaneFetch({
736
+ url: "/db/{dbBranchName}/copy",
737
+ method: "post",
738
+ ...variables,
739
+ signal
740
+ });
491
741
  const updateBranchMetadata = (variables, signal) => dataPlaneFetch({
492
742
  url: "/db/{dbBranchName}/metadata",
493
743
  method: "put",
@@ -537,6 +787,7 @@ const compareBranchSchemas = (variables, signal) => dataPlaneFetch({ url: "/db/{
537
787
  const updateBranchSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/update", method: "post", ...variables, signal });
538
788
  const previewBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables, signal });
539
789
  const applyBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables, signal });
790
+ const pushBranchMigrations = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/push", method: "post", ...variables, signal });
540
791
  const createTable = (variables, signal) => dataPlaneFetch({
541
792
  url: "/db/{dbBranchName}/tables/{tableName}",
542
793
  method: "put",
@@ -610,7 +861,19 @@ const searchTable = (variables, signal) => dataPlaneFetch({
610
861
  ...variables,
611
862
  signal
612
863
  });
864
+ const sqlQuery = (variables, signal) => dataPlaneFetch({
865
+ url: "/db/{dbBranchName}/sql",
866
+ method: "post",
867
+ ...variables,
868
+ signal
869
+ });
613
870
  const vectorSearchTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/vectorSearch", method: "post", ...variables, signal });
871
+ const askTable = (variables, signal) => dataPlaneFetch({
872
+ url: "/db/{dbBranchName}/tables/{tableName}/ask",
873
+ method: "post",
874
+ ...variables,
875
+ signal
876
+ });
614
877
  const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
615
878
  const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
616
879
  const operationsByTag$2 = {
@@ -619,6 +882,7 @@ const operationsByTag$2 = {
619
882
  getBranchDetails,
620
883
  createBranch,
621
884
  deleteBranch,
885
+ copyBranch,
622
886
  updateBranchMetadata,
623
887
  getBranchMetadata,
624
888
  getBranchStats,
@@ -636,7 +900,8 @@ const operationsByTag$2 = {
636
900
  compareBranchSchemas,
637
901
  updateBranchSchema,
638
902
  previewBranchSchemaEdit,
639
- applyBranchSchemaEdit
903
+ applyBranchSchemaEdit,
904
+ pushBranchMigrations
640
905
  },
641
906
  migrationRequests: {
642
907
  queryMigrationRequests,
@@ -670,7 +935,16 @@ const operationsByTag$2 = {
670
935
  deleteRecord,
671
936
  bulkInsertTableRecords
672
937
  },
673
- searchAndFilter: { queryTable, searchBranch, searchTable, vectorSearchTable, summarizeTable, aggregateTable }
938
+ searchAndFilter: {
939
+ queryTable,
940
+ searchBranch,
941
+ searchTable,
942
+ sqlQuery,
943
+ vectorSearchTable,
944
+ askTable,
945
+ summarizeTable,
946
+ aggregateTable
947
+ }
674
948
  };
675
949
 
676
950
  const controlPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "controlPlane" });
@@ -829,6 +1103,10 @@ const providers = {
829
1103
  staging: {
830
1104
  main: "https://api.staging-xata.dev",
831
1105
  workspaces: "https://{workspaceId}.{region}.staging-xata.dev"
1106
+ },
1107
+ dev: {
1108
+ main: "https://api.dev-xata.dev",
1109
+ workspaces: "https://{workspaceId}.{region}.dev-xata.dev"
832
1110
  }
833
1111
  };
834
1112
  function isHostProviderAlias(alias) {
@@ -846,6 +1124,11 @@ function parseProviderString(provider = "production") {
846
1124
  return null;
847
1125
  return { main, workspaces };
848
1126
  }
1127
+ function buildProviderString(provider) {
1128
+ if (isHostProviderAlias(provider))
1129
+ return provider;
1130
+ return `${provider.main},${provider.workspaces}`;
1131
+ }
849
1132
  function parseWorkspacesUrlParts(url) {
850
1133
  if (!isString(url))
851
1134
  return null;
@@ -892,7 +1175,7 @@ class XataApiClient {
892
1175
  __privateSet$7(this, _extraProps, {
893
1176
  apiUrl: getHostUrl(provider, "main"),
894
1177
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
895
- fetchImpl: getFetchImplementation(options.fetch),
1178
+ fetch: getFetchImplementation(options.fetch),
896
1179
  apiKey,
897
1180
  trace,
898
1181
  clientName: options.clientName,
@@ -1158,6 +1441,20 @@ class BranchApi {
1158
1441
  ...this.extraProps
1159
1442
  });
1160
1443
  }
1444
+ copyBranch({
1445
+ workspace,
1446
+ region,
1447
+ database,
1448
+ branch,
1449
+ destinationBranch,
1450
+ limit
1451
+ }) {
1452
+ return operationsByTag.branch.copyBranch({
1453
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1454
+ body: { destinationBranch, limit },
1455
+ ...this.extraProps
1456
+ });
1457
+ }
1161
1458
  updateBranchMetadata({
1162
1459
  workspace,
1163
1460
  region,
@@ -1572,6 +1869,38 @@ class SearchAndFilterApi {
1572
1869
  ...this.extraProps
1573
1870
  });
1574
1871
  }
1872
+ vectorSearchTable({
1873
+ workspace,
1874
+ region,
1875
+ database,
1876
+ branch,
1877
+ table,
1878
+ queryVector,
1879
+ column,
1880
+ similarityFunction,
1881
+ size,
1882
+ filter
1883
+ }) {
1884
+ return operationsByTag.searchAndFilter.vectorSearchTable({
1885
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1886
+ body: { queryVector, column, similarityFunction, size, filter },
1887
+ ...this.extraProps
1888
+ });
1889
+ }
1890
+ askTable({
1891
+ workspace,
1892
+ region,
1893
+ database,
1894
+ branch,
1895
+ table,
1896
+ options
1897
+ }) {
1898
+ return operationsByTag.searchAndFilter.askTable({
1899
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1900
+ body: { ...options },
1901
+ ...this.extraProps
1902
+ });
1903
+ }
1575
1904
  summarizeTable({
1576
1905
  workspace,
1577
1906
  region,
@@ -1836,6 +2165,19 @@ class MigrationsApi {
1836
2165
  ...this.extraProps
1837
2166
  });
1838
2167
  }
2168
+ pushBranchMigrations({
2169
+ workspace,
2170
+ region,
2171
+ database,
2172
+ branch,
2173
+ migrations
2174
+ }) {
2175
+ return operationsByTag.migrations.pushBranchMigrations({
2176
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2177
+ body: { migrations },
2178
+ ...this.extraProps
2179
+ });
2180
+ }
1839
2181
  }
1840
2182
  class DatabaseApi {
1841
2183
  constructor(extraProps) {
@@ -1925,9 +2267,8 @@ class DatabaseApi {
1925
2267
  }
1926
2268
 
1927
2269
  class XataApiPlugin {
1928
- async build(options) {
1929
- const { fetchImpl, apiKey } = await options.getFetchProps();
1930
- return new XataApiClient({ fetch: fetchImpl, apiKey });
2270
+ build(options) {
2271
+ return new XataApiClient(options);
1931
2272
  }
1932
2273
  }
1933
2274
 
@@ -2268,7 +2609,11 @@ function isSortFilterString(value) {
2268
2609
  return isString(value);
2269
2610
  }
2270
2611
  function isSortFilterBase(filter) {
2271
- return isObject(filter) && Object.values(filter).every((value) => value === "asc" || value === "desc");
2612
+ return isObject(filter) && Object.entries(filter).every(([key, value]) => {
2613
+ if (key === "*")
2614
+ return value === "random";
2615
+ return value === "asc" || value === "desc";
2616
+ });
2272
2617
  }
2273
2618
  function isSortFilterObject(filter) {
2274
2619
  return isObject(filter) && !isSortFilterBase(filter) && filter.column !== void 0;
@@ -2341,10 +2686,7 @@ class RestRepository extends Query {
2341
2686
  __privateSet$4(this, _db, options.db);
2342
2687
  __privateSet$4(this, _cache, options.pluginOptions.cache);
2343
2688
  __privateSet$4(this, _schemaTables$2, options.schemaTables);
2344
- __privateSet$4(this, _getFetchProps, async () => {
2345
- const props = await options.pluginOptions.getFetchProps();
2346
- return { ...props, sessionID: generateUUID() };
2347
- });
2689
+ __privateSet$4(this, _getFetchProps, () => ({ ...options.pluginOptions, sessionID: generateUUID() }));
2348
2690
  const trace = options.pluginOptions.trace ?? defaultTrace;
2349
2691
  __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
2350
2692
  return trace(name, fn, {
@@ -2401,7 +2743,6 @@ class RestRepository extends Query {
2401
2743
  }
2402
2744
  const id = extractId(a);
2403
2745
  if (id) {
2404
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2405
2746
  try {
2406
2747
  const response = await getRecord({
2407
2748
  pathParams: {
@@ -2412,7 +2753,7 @@ class RestRepository extends Query {
2412
2753
  recordId: id
2413
2754
  },
2414
2755
  queryParams: { columns },
2415
- ...fetchProps
2756
+ ...__privateGet$4(this, _getFetchProps).call(this)
2416
2757
  });
2417
2758
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2418
2759
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2590,7 +2931,6 @@ class RestRepository extends Query {
2590
2931
  }
2591
2932
  async search(query, options = {}) {
2592
2933
  return __privateGet$4(this, _trace).call(this, "search", async () => {
2593
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2594
2934
  const { records } = await searchTable({
2595
2935
  pathParams: {
2596
2936
  workspace: "{workspaceId}",
@@ -2608,15 +2948,14 @@ class RestRepository extends Query {
2608
2948
  page: options.page,
2609
2949
  target: options.target
2610
2950
  },
2611
- ...fetchProps
2951
+ ...__privateGet$4(this, _getFetchProps).call(this)
2612
2952
  });
2613
2953
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2614
2954
  return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
2615
2955
  });
2616
2956
  }
2617
2957
  async vectorSearch(column, query, options) {
2618
- return __privateGet$4(this, _trace).call(this, "searchVector", async () => {
2619
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2958
+ return __privateGet$4(this, _trace).call(this, "vectorSearch", async () => {
2620
2959
  const { records } = await vectorSearchTable({
2621
2960
  pathParams: {
2622
2961
  workspace: "{workspaceId}",
@@ -2627,11 +2966,11 @@ class RestRepository extends Query {
2627
2966
  body: {
2628
2967
  column,
2629
2968
  queryVector: query,
2630
- spaceFunction: options?.spaceFunction,
2969
+ similarityFunction: options?.similarityFunction,
2631
2970
  size: options?.size,
2632
2971
  filter: options?.filter
2633
2972
  },
2634
- ...fetchProps
2973
+ ...__privateGet$4(this, _getFetchProps).call(this)
2635
2974
  });
2636
2975
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2637
2976
  return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
@@ -2639,7 +2978,6 @@ class RestRepository extends Query {
2639
2978
  }
2640
2979
  async aggregate(aggs, filter) {
2641
2980
  return __privateGet$4(this, _trace).call(this, "aggregate", async () => {
2642
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2643
2981
  const result = await aggregateTable({
2644
2982
  pathParams: {
2645
2983
  workspace: "{workspaceId}",
@@ -2648,7 +2986,7 @@ class RestRepository extends Query {
2648
2986
  tableName: __privateGet$4(this, _table)
2649
2987
  },
2650
2988
  body: { aggs, filter },
2651
- ...fetchProps
2989
+ ...__privateGet$4(this, _getFetchProps).call(this)
2652
2990
  });
2653
2991
  return result;
2654
2992
  });
@@ -2659,7 +2997,6 @@ class RestRepository extends Query {
2659
2997
  if (cacheQuery)
2660
2998
  return new Page(query, cacheQuery.meta, cacheQuery.records);
2661
2999
  const data = query.getQueryOptions();
2662
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2663
3000
  const { meta, records: objects } = await queryTable({
2664
3001
  pathParams: {
2665
3002
  workspace: "{workspaceId}",
@@ -2675,7 +3012,7 @@ class RestRepository extends Query {
2675
3012
  consistency: data.consistency
2676
3013
  },
2677
3014
  fetchOptions: data.fetchOptions,
2678
- ...fetchProps
3015
+ ...__privateGet$4(this, _getFetchProps).call(this)
2679
3016
  });
2680
3017
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2681
3018
  const records = objects.map(
@@ -2688,7 +3025,6 @@ class RestRepository extends Query {
2688
3025
  async summarizeTable(query, summaries, summariesFilter) {
2689
3026
  return __privateGet$4(this, _trace).call(this, "summarize", async () => {
2690
3027
  const data = query.getQueryOptions();
2691
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2692
3028
  const result = await summarizeTable({
2693
3029
  pathParams: {
2694
3030
  workspace: "{workspaceId}",
@@ -2705,11 +3041,39 @@ class RestRepository extends Query {
2705
3041
  summaries,
2706
3042
  summariesFilter
2707
3043
  },
2708
- ...fetchProps
3044
+ ...__privateGet$4(this, _getFetchProps).call(this)
2709
3045
  });
2710
3046
  return result;
2711
3047
  });
2712
3048
  }
3049
+ ask(question, options) {
3050
+ const params = {
3051
+ pathParams: {
3052
+ workspace: "{workspaceId}",
3053
+ dbBranchName: "{dbBranch}",
3054
+ region: "{region}",
3055
+ tableName: __privateGet$4(this, _table)
3056
+ },
3057
+ body: {
3058
+ question,
3059
+ ...options
3060
+ },
3061
+ ...__privateGet$4(this, _getFetchProps).call(this)
3062
+ };
3063
+ if (options?.onMessage) {
3064
+ fetchSSERequest({
3065
+ endpoint: "dataPlane",
3066
+ url: "/db/{dbBranchName}/tables/{tableName}/ask",
3067
+ method: "POST",
3068
+ onMessage: (message) => {
3069
+ options.onMessage?.({ answer: message.text, records: message.records });
3070
+ },
3071
+ ...params
3072
+ });
3073
+ } else {
3074
+ return askTable(params);
3075
+ }
3076
+ }
2713
3077
  }
2714
3078
  _table = new WeakMap();
2715
3079
  _getFetchProps = new WeakMap();
@@ -2719,7 +3083,6 @@ _schemaTables$2 = new WeakMap();
2719
3083
  _trace = new WeakMap();
2720
3084
  _insertRecordWithoutId = new WeakSet();
2721
3085
  insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
2722
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2723
3086
  const record = transformObjectLinks(object);
2724
3087
  const response = await insertRecord({
2725
3088
  pathParams: {
@@ -2730,14 +3093,13 @@ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
2730
3093
  },
2731
3094
  queryParams: { columns },
2732
3095
  body: record,
2733
- ...fetchProps
3096
+ ...__privateGet$4(this, _getFetchProps).call(this)
2734
3097
  });
2735
3098
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2736
3099
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2737
3100
  };
2738
3101
  _insertRecordWithId = new WeakSet();
2739
3102
  insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { createOnly, ifVersion }) {
2740
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2741
3103
  const record = transformObjectLinks(object);
2742
3104
  const response = await insertRecordWithID({
2743
3105
  pathParams: {
@@ -2749,14 +3111,13 @@ insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { crea
2749
3111
  },
2750
3112
  body: record,
2751
3113
  queryParams: { createOnly, columns, ifVersion },
2752
- ...fetchProps
3114
+ ...__privateGet$4(this, _getFetchProps).call(this)
2753
3115
  });
2754
3116
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2755
3117
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2756
3118
  };
2757
3119
  _insertRecords = new WeakSet();
2758
3120
  insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2759
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2760
3121
  const chunkedOperations = chunk(
2761
3122
  objects.map((object) => ({
2762
3123
  insert: { table: __privateGet$4(this, _table), record: transformObjectLinks(object), createOnly, ifVersion }
@@ -2772,7 +3133,7 @@ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2772
3133
  region: "{region}"
2773
3134
  },
2774
3135
  body: { operations },
2775
- ...fetchProps
3136
+ ...__privateGet$4(this, _getFetchProps).call(this)
2776
3137
  });
2777
3138
  for (const result of results) {
2778
3139
  if (result.operation === "insert") {
@@ -2786,7 +3147,6 @@ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2786
3147
  };
2787
3148
  _updateRecordWithID = new WeakSet();
2788
3149
  updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2789
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2790
3150
  const { id: _id, ...record } = transformObjectLinks(object);
2791
3151
  try {
2792
3152
  const response = await updateRecordWithID({
@@ -2799,7 +3159,7 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2799
3159
  },
2800
3160
  queryParams: { columns, ifVersion },
2801
3161
  body: record,
2802
- ...fetchProps
3162
+ ...__privateGet$4(this, _getFetchProps).call(this)
2803
3163
  });
2804
3164
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2805
3165
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2812,7 +3172,6 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2812
3172
  };
2813
3173
  _updateRecords = new WeakSet();
2814
3174
  updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2815
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2816
3175
  const chunkedOperations = chunk(
2817
3176
  objects.map(({ id, ...object }) => ({
2818
3177
  update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields: transformObjectLinks(object) }
@@ -2828,7 +3187,7 @@ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2828
3187
  region: "{region}"
2829
3188
  },
2830
3189
  body: { operations },
2831
- ...fetchProps
3190
+ ...__privateGet$4(this, _getFetchProps).call(this)
2832
3191
  });
2833
3192
  for (const result of results) {
2834
3193
  if (result.operation === "update") {
@@ -2842,7 +3201,6 @@ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2842
3201
  };
2843
3202
  _upsertRecordWithID = new WeakSet();
2844
3203
  upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2845
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2846
3204
  const response = await upsertRecordWithID({
2847
3205
  pathParams: {
2848
3206
  workspace: "{workspaceId}",
@@ -2853,14 +3211,13 @@ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2853
3211
  },
2854
3212
  queryParams: { columns, ifVersion },
2855
3213
  body: object,
2856
- ...fetchProps
3214
+ ...__privateGet$4(this, _getFetchProps).call(this)
2857
3215
  });
2858
3216
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2859
3217
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2860
3218
  };
2861
3219
  _deleteRecord = new WeakSet();
2862
3220
  deleteRecord_fn = async function(recordId, columns = ["*"]) {
2863
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2864
3221
  try {
2865
3222
  const response = await deleteRecord({
2866
3223
  pathParams: {
@@ -2871,7 +3228,7 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2871
3228
  recordId
2872
3229
  },
2873
3230
  queryParams: { columns },
2874
- ...fetchProps
3231
+ ...__privateGet$4(this, _getFetchProps).call(this)
2875
3232
  });
2876
3233
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2877
3234
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2884,7 +3241,6 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2884
3241
  };
2885
3242
  _deleteRecords = new WeakSet();
2886
3243
  deleteRecords_fn = async function(recordIds) {
2887
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2888
3244
  const chunkedOperations = chunk(
2889
3245
  recordIds.map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
2890
3246
  BULK_OPERATION_MAX_SIZE
@@ -2897,21 +3253,22 @@ deleteRecords_fn = async function(recordIds) {
2897
3253
  region: "{region}"
2898
3254
  },
2899
3255
  body: { operations },
2900
- ...fetchProps
3256
+ ...__privateGet$4(this, _getFetchProps).call(this)
2901
3257
  });
2902
3258
  }
2903
3259
  };
2904
3260
  _setCacheQuery = new WeakSet();
2905
3261
  setCacheQuery_fn = async function(query, meta, records) {
2906
- await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
3262
+ await __privateGet$4(this, _cache)?.set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
2907
3263
  };
2908
3264
  _getCacheQuery = new WeakSet();
2909
3265
  getCacheQuery_fn = async function(query) {
2910
3266
  const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
2911
- const result = await __privateGet$4(this, _cache).get(key);
3267
+ const result = await __privateGet$4(this, _cache)?.get(key);
2912
3268
  if (!result)
2913
3269
  return null;
2914
- const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
3270
+ const defaultTTL = __privateGet$4(this, _cache)?.defaultQueryTTL ?? -1;
3271
+ const { cache: ttl = defaultTTL } = query.getQueryOptions();
2915
3272
  if (ttl < 0)
2916
3273
  return null;
2917
3274
  const hasExpired = result.date.getTime() + ttl < Date.now();
@@ -2921,10 +3278,9 @@ _getSchemaTables$1 = new WeakSet();
2921
3278
  getSchemaTables_fn$1 = async function() {
2922
3279
  if (__privateGet$4(this, _schemaTables$2))
2923
3280
  return __privateGet$4(this, _schemaTables$2);
2924
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2925
3281
  const { schema } = await getBranchDetails({
2926
3282
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
2927
- ...fetchProps
3283
+ ...__privateGet$4(this, _getFetchProps).call(this)
2928
3284
  });
2929
3285
  __privateSet$4(this, _schemaTables$2, schema.tables);
2930
3286
  return schema.tables;
@@ -3200,19 +3556,19 @@ class SearchPlugin extends XataPlugin {
3200
3556
  __privateAdd$1(this, _schemaTables, void 0);
3201
3557
  __privateSet$1(this, _schemaTables, schemaTables);
3202
3558
  }
3203
- build({ getFetchProps }) {
3559
+ build(pluginOptions) {
3204
3560
  return {
3205
3561
  all: async (query, options = {}) => {
3206
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
3207
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
3562
+ const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
3563
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
3208
3564
  return records.map((record) => {
3209
3565
  const { table = "orphan" } = record.xata;
3210
3566
  return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
3211
3567
  });
3212
3568
  },
3213
3569
  byTable: async (query, options = {}) => {
3214
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
3215
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
3570
+ const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
3571
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
3216
3572
  return records.reduce((acc, record) => {
3217
3573
  const { table = "orphan" } = record.xata;
3218
3574
  const items = acc[table] ?? [];
@@ -3225,38 +3581,35 @@ class SearchPlugin extends XataPlugin {
3225
3581
  }
3226
3582
  _schemaTables = new WeakMap();
3227
3583
  _search = new WeakSet();
3228
- search_fn = async function(query, options, getFetchProps) {
3229
- const fetchProps = await getFetchProps();
3584
+ search_fn = async function(query, options, pluginOptions) {
3230
3585
  const { tables, fuzziness, highlight, prefix, page } = options ?? {};
3231
3586
  const { records } = await searchBranch({
3232
3587
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3233
3588
  body: { tables, query, fuzziness, prefix, highlight, page },
3234
- ...fetchProps
3589
+ ...pluginOptions
3235
3590
  });
3236
3591
  return records;
3237
3592
  };
3238
3593
  _getSchemaTables = new WeakSet();
3239
- getSchemaTables_fn = async function(getFetchProps) {
3594
+ getSchemaTables_fn = async function(pluginOptions) {
3240
3595
  if (__privateGet$1(this, _schemaTables))
3241
3596
  return __privateGet$1(this, _schemaTables);
3242
- const fetchProps = await getFetchProps();
3243
3597
  const { schema } = await getBranchDetails({
3244
3598
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3245
- ...fetchProps
3599
+ ...pluginOptions
3246
3600
  });
3247
3601
  __privateSet$1(this, _schemaTables, schema.tables);
3248
3602
  return schema.tables;
3249
3603
  };
3250
3604
 
3251
3605
  class TransactionPlugin extends XataPlugin {
3252
- build({ getFetchProps }) {
3606
+ build(pluginOptions) {
3253
3607
  return {
3254
3608
  run: async (operations) => {
3255
- const fetchProps = await getFetchProps();
3256
3609
  const response = await branchTransaction({
3257
3610
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3258
3611
  body: { operations },
3259
- ...fetchProps
3612
+ ...pluginOptions
3260
3613
  });
3261
3614
  return response;
3262
3615
  }
@@ -3264,91 +3617,6 @@ class TransactionPlugin extends XataPlugin {
3264
3617
  }
3265
3618
  }
3266
3619
 
3267
- const isBranchStrategyBuilder = (strategy) => {
3268
- return typeof strategy === "function";
3269
- };
3270
-
3271
- async function getCurrentBranchName(options) {
3272
- const { branch, envBranch } = getEnvironment();
3273
- if (branch)
3274
- return branch;
3275
- const gitBranch = envBranch || await getGitBranch();
3276
- return resolveXataBranch(gitBranch, options);
3277
- }
3278
- async function getCurrentBranchDetails(options) {
3279
- const branch = await getCurrentBranchName(options);
3280
- return getDatabaseBranch(branch, options);
3281
- }
3282
- async function resolveXataBranch(gitBranch, options) {
3283
- const databaseURL = options?.databaseURL || getDatabaseURL();
3284
- const apiKey = options?.apiKey || getAPIKey();
3285
- if (!databaseURL)
3286
- throw new Error(
3287
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
3288
- );
3289
- if (!apiKey)
3290
- throw new Error(
3291
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
3292
- );
3293
- const [protocol, , host, , dbName] = databaseURL.split("/");
3294
- const urlParts = parseWorkspacesUrlParts(host);
3295
- if (!urlParts)
3296
- throw new Error(`Unable to parse workspace and region: ${databaseURL}`);
3297
- const { workspace, region } = urlParts;
3298
- const { fallbackBranch } = getEnvironment();
3299
- const { branch } = await resolveBranch({
3300
- apiKey,
3301
- apiUrl: databaseURL,
3302
- fetchImpl: getFetchImplementation(options?.fetchImpl),
3303
- workspacesApiUrl: `${protocol}//${host}`,
3304
- pathParams: { dbName, workspace, region },
3305
- queryParams: { gitBranch, fallbackBranch },
3306
- trace: defaultTrace,
3307
- clientName: options?.clientName,
3308
- xataAgentExtra: options?.xataAgentExtra
3309
- });
3310
- return branch;
3311
- }
3312
- async function getDatabaseBranch(branch, options) {
3313
- const databaseURL = options?.databaseURL || getDatabaseURL();
3314
- const apiKey = options?.apiKey || getAPIKey();
3315
- if (!databaseURL)
3316
- throw new Error(
3317
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
3318
- );
3319
- if (!apiKey)
3320
- throw new Error(
3321
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
3322
- );
3323
- const [protocol, , host, , database] = databaseURL.split("/");
3324
- const urlParts = parseWorkspacesUrlParts(host);
3325
- if (!urlParts)
3326
- throw new Error(`Unable to parse workspace and region: ${databaseURL}`);
3327
- const { workspace, region } = urlParts;
3328
- try {
3329
- return await getBranchDetails({
3330
- apiKey,
3331
- apiUrl: databaseURL,
3332
- fetchImpl: getFetchImplementation(options?.fetchImpl),
3333
- workspacesApiUrl: `${protocol}//${host}`,
3334
- pathParams: { dbBranchName: `${database}:${branch}`, workspace, region },
3335
- trace: defaultTrace
3336
- });
3337
- } catch (err) {
3338
- if (isObject(err) && err.status === 404)
3339
- return null;
3340
- throw err;
3341
- }
3342
- }
3343
- function getDatabaseURL() {
3344
- try {
3345
- const { databaseURL } = getEnvironment();
3346
- return databaseURL;
3347
- } catch (err) {
3348
- return void 0;
3349
- }
3350
- }
3351
-
3352
3620
  var __accessCheck = (obj, member, msg) => {
3353
3621
  if (!member.has(obj))
3354
3622
  throw TypeError("Cannot " + msg);
@@ -3372,20 +3640,18 @@ var __privateMethod = (obj, member, method) => {
3372
3640
  return method;
3373
3641
  };
3374
3642
  const buildClient = (plugins) => {
3375
- var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
3643
+ var _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _a;
3376
3644
  return _a = class {
3377
3645
  constructor(options = {}, schemaTables) {
3378
3646
  __privateAdd(this, _parseOptions);
3379
3647
  __privateAdd(this, _getFetchProps);
3380
- __privateAdd(this, _evaluateBranch);
3381
- __privateAdd(this, _branch, void 0);
3382
3648
  __privateAdd(this, _options, void 0);
3383
3649
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
3384
3650
  __privateSet(this, _options, safeOptions);
3385
3651
  const pluginOptions = {
3386
- getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
3652
+ ...__privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
3387
3653
  cache: safeOptions.cache,
3388
- trace: safeOptions.trace
3654
+ host: safeOptions.host
3389
3655
  };
3390
3656
  const db = new SchemaPlugin(schemaTables).build(pluginOptions);
3391
3657
  const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
@@ -3396,22 +3662,15 @@ const buildClient = (plugins) => {
3396
3662
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
3397
3663
  if (namespace === void 0)
3398
3664
  continue;
3399
- const result = namespace.build(pluginOptions);
3400
- if (result instanceof Promise) {
3401
- void result.then((namespace2) => {
3402
- this[key] = namespace2;
3403
- });
3404
- } else {
3405
- this[key] = result;
3406
- }
3665
+ this[key] = namespace.build(pluginOptions);
3407
3666
  }
3408
3667
  }
3409
3668
  async getConfig() {
3410
3669
  const databaseURL = __privateGet(this, _options).databaseURL;
3411
- const branch = await __privateGet(this, _options).branch();
3670
+ const branch = __privateGet(this, _options).branch;
3412
3671
  return { databaseURL, branch };
3413
3672
  }
3414
- }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3673
+ }, _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3415
3674
  const enableBrowser = options?.enableBrowser ?? getEnableBrowserVariable() ?? false;
3416
3675
  const isBrowser = typeof window !== "undefined" && typeof Deno === "undefined";
3417
3676
  if (isBrowser && !enableBrowser) {
@@ -3425,20 +3684,34 @@ const buildClient = (plugins) => {
3425
3684
  const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
3426
3685
  const trace = options?.trace ?? defaultTrace;
3427
3686
  const clientName = options?.clientName;
3687
+ const host = options?.host ?? "production";
3428
3688
  const xataAgentExtra = options?.xataAgentExtra;
3429
- const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({
3430
- apiKey,
3431
- databaseURL,
3432
- fetchImpl: options?.fetch,
3433
- clientName,
3434
- xataAgentExtra
3435
- });
3436
3689
  if (!apiKey) {
3437
3690
  throw new Error("Option apiKey is required");
3438
3691
  }
3439
3692
  if (!databaseURL) {
3440
3693
  throw new Error("Option databaseURL is required");
3441
3694
  }
3695
+ const envBranch = getBranch();
3696
+ const previewBranch = getPreviewBranch();
3697
+ const branch = options?.branch || previewBranch || envBranch || "main";
3698
+ if (!!previewBranch && branch !== previewBranch) {
3699
+ console.warn(
3700
+ `Ignoring preview branch ${previewBranch} because branch option was passed to the client constructor with value ${branch}`
3701
+ );
3702
+ } else if (!!envBranch && branch !== envBranch) {
3703
+ console.warn(
3704
+ `Ignoring branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
3705
+ );
3706
+ } else if (!!previewBranch && !!envBranch && previewBranch !== envBranch) {
3707
+ console.warn(
3708
+ `Ignoring preview branch ${previewBranch} and branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
3709
+ );
3710
+ } else if (!previewBranch && !envBranch && options?.branch === void 0) {
3711
+ console.warn(
3712
+ `No branch was passed to the client constructor. Using default branch ${branch}. You can set the branch with the environment variable XATA_BRANCH or by passing the branch option to the client constructor.`
3713
+ );
3714
+ }
3442
3715
  return {
3443
3716
  fetch,
3444
3717
  databaseURL,
@@ -3446,12 +3719,13 @@ const buildClient = (plugins) => {
3446
3719
  branch,
3447
3720
  cache,
3448
3721
  trace,
3722
+ host,
3449
3723
  clientID: generateUUID(),
3450
3724
  enableBrowser,
3451
3725
  clientName,
3452
3726
  xataAgentExtra
3453
3727
  };
3454
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
3728
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = function({
3455
3729
  fetch,
3456
3730
  apiKey,
3457
3731
  databaseURL,
@@ -3461,16 +3735,13 @@ const buildClient = (plugins) => {
3461
3735
  clientName,
3462
3736
  xataAgentExtra
3463
3737
  }) {
3464
- const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
3465
- if (!branchValue)
3466
- throw new Error("Unable to resolve branch value");
3467
3738
  return {
3468
- fetchImpl: fetch,
3739
+ fetch,
3469
3740
  apiKey,
3470
3741
  apiUrl: "",
3471
3742
  workspacesApiUrl: (path, params) => {
3472
3743
  const hasBranch = params.dbBranchName ?? params.branch;
3473
- const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branchValue}` : "");
3744
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branch}` : "");
3474
3745
  return databaseURL + newPath;
3475
3746
  },
3476
3747
  trace,
@@ -3478,22 +3749,6 @@ const buildClient = (plugins) => {
3478
3749
  clientName,
3479
3750
  xataAgentExtra
3480
3751
  };
3481
- }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
3482
- if (__privateGet(this, _branch))
3483
- return __privateGet(this, _branch);
3484
- if (param === void 0)
3485
- return void 0;
3486
- const strategies = Array.isArray(param) ? [...param] : [param];
3487
- const evaluateBranch = async (strategy) => {
3488
- return isBranchStrategyBuilder(strategy) ? await strategy() : strategy;
3489
- };
3490
- for await (const strategy of strategies) {
3491
- const branch = await evaluateBranch(strategy);
3492
- if (branch) {
3493
- __privateSet(this, _branch, branch);
3494
- return branch;
3495
- }
3496
- }
3497
3752
  }, _a;
3498
3753
  };
3499
3754
  class BaseClient extends buildClient() {
@@ -3588,5 +3843,5 @@ class XataError extends Error {
3588
3843
  }
3589
3844
  }
3590
3845
 
3591
- export { BaseClient, FetcherError, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, Serializer, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, aggregateTable, applyBranchSchemaEdit, branchTransaction, buildClient, buildWorkerRunner, bulkInsertTableRecords, cancelWorkspaceMemberInvite, compareBranchSchemas, compareBranchWithUserSchema, compareMigrationRequest, contains, createBranch, createDatabase, createMigrationRequest, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteDatabaseGithubSettings, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, deserialize, endsWith, equals, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchSchemaHistory, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseGithubSettings, getDatabaseList, getDatabaseMetadata, getDatabaseURL, getGitBranchesMapping, getHostUrl, getMigrationRequest, getMigrationRequestIsMerged, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, greaterEquals, greaterThan, greaterThanEquals, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isHostProviderAlias, isHostProviderBuilder, isIdentifiable, isNot, isXataRecord, le, lessEquals, lessThan, lessThanEquals, listMigrationRequestsCommits, listRegions, lt, lte, mergeMigrationRequest, notExists, operationsByTag, parseProviderString, parseWorkspacesUrlParts, pattern, previewBranchSchemaEdit, queryMigrationRequests, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, serialize, setTableSchema, startsWith, summarizeTable, updateBranchMetadata, updateBranchSchema, updateColumn, updateDatabaseGithubSettings, updateDatabaseMetadata, updateMigrationRequest, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID, vectorSearchTable };
3846
+ export { BaseClient, FetcherError, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, Serializer, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, aggregateTable, applyBranchSchemaEdit, askTable, branchTransaction, buildClient, buildPreviewBranchName, buildProviderString, buildWorkerRunner, bulkInsertTableRecords, cancelWorkspaceMemberInvite, compareBranchSchemas, compareBranchWithUserSchema, compareMigrationRequest, contains, copyBranch, createBranch, createDatabase, createMigrationRequest, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteDatabaseGithubSettings, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, deserialize, endsWith, equals, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranch, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchSchemaHistory, getBranchStats, getColumn, getDatabaseGithubSettings, getDatabaseList, getDatabaseMetadata, getDatabaseURL, getGitBranchesMapping, getHostUrl, getMigrationRequest, getMigrationRequestIsMerged, getPreviewBranch, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, greaterEquals, greaterThan, greaterThanEquals, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isHostProviderAlias, isHostProviderBuilder, isIdentifiable, isNot, isXataRecord, le, lessEquals, lessThan, lessThanEquals, listMigrationRequestsCommits, listRegions, lt, lte, mergeMigrationRequest, notExists, operationsByTag, parseProviderString, parseWorkspacesUrlParts, pattern, previewBranchSchemaEdit, pushBranchMigrations, queryMigrationRequests, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, serialize, setTableSchema, sqlQuery, startsWith, summarizeTable, updateBranchMetadata, updateBranchSchema, updateColumn, updateDatabaseGithubSettings, updateDatabaseMetadata, updateMigrationRequest, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID, vectorSearchTable };
3592
3847
  //# sourceMappingURL=index.mjs.map