@xata.io/client 0.0.0-alpha.vf6f217e → 0.0.0-alpha.vf70b95a

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,39 +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
- if (typeof require === "function") {
174
- return require(nodeModule).execSync(fullCmd, execOptions).trim();
175
- }
176
- const { execSync } = await import(nodeModule);
177
- return execSync(fullCmd, execOptions).toString().trim();
176
+ const { apiKey } = getEnvironment();
177
+ return apiKey;
178
178
  } catch (err) {
179
+ return void 0;
179
180
  }
181
+ }
182
+ function getBranch() {
180
183
  try {
181
- if (isObject(Deno)) {
182
- const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
183
- return new TextDecoder().decode(await process2.output()).trim();
184
- }
184
+ const { branch } = getEnvironment();
185
+ return branch ?? "main";
185
186
  } catch (err) {
187
+ return void 0;
186
188
  }
187
189
  }
188
-
189
- function getAPIKey() {
190
+ function buildPreviewBranchName({ org, branch }) {
191
+ return `preview-${org}-${branch}`;
192
+ }
193
+ function getPreviewBranch() {
190
194
  try {
191
- const { apiKey } = getEnvironment();
192
- 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;
193
208
  } catch (err) {
194
209
  return void 0;
195
210
  }
@@ -302,7 +317,180 @@ function generateUUID() {
302
317
  });
303
318
  }
304
319
 
305
- const VERSION = "0.0.0-alpha.vf6f217e";
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.4";
306
494
 
307
495
  class ErrorWithCause extends Error {
308
496
  constructor(message, options) {
@@ -386,7 +574,7 @@ async function fetch$1({
386
574
  headers: customHeaders,
387
575
  pathParams,
388
576
  queryParams,
389
- fetchImpl,
577
+ fetch: fetch2,
390
578
  apiKey,
391
579
  endpoint,
392
580
  apiUrl,
@@ -396,12 +584,13 @@ async function fetch$1({
396
584
  clientID,
397
585
  sessionID,
398
586
  clientName,
587
+ xataAgentExtra,
399
588
  fetchOptions = {}
400
589
  }) {
401
- pool.setFetch(fetchImpl);
590
+ pool.setFetch(fetch2);
402
591
  return await trace(
403
592
  `${method.toUpperCase()} ${path}`,
404
- async ({ name, setAttributes }) => {
593
+ async ({ setAttributes }) => {
405
594
  const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
406
595
  const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
407
596
  const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
@@ -412,7 +601,8 @@ async function fetch$1({
412
601
  const xataAgent = compact([
413
602
  ["client", "TS_SDK"],
414
603
  ["version", VERSION],
415
- isDefined(clientName) ? ["service", clientName] : void 0
604
+ isDefined(clientName) ? ["service", clientName] : void 0,
605
+ ...Object.entries(xataAgentExtra ?? {})
416
606
  ]).map(([key, value]) => `${key}=${value}`).join("; ");
417
607
  const headers = {
418
608
  "Accept-Encoding": "identity",
@@ -459,6 +649,59 @@ async function fetch$1({
459
649
  { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
460
650
  );
461
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
+ }
462
705
  function parseUrl(url) {
463
706
  try {
464
707
  const { host, protocol } = new URL(url);
@@ -470,17 +713,12 @@ function parseUrl(url) {
470
713
 
471
714
  const dataPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "dataPlane" });
472
715
 
473
- const dEPRECATEDgetDatabaseList = (variables, signal) => dataPlaneFetch({ url: "/dbs", method: "get", ...variables, signal });
474
716
  const getBranchList = (variables, signal) => dataPlaneFetch({
475
717
  url: "/dbs/{dbName}",
476
718
  method: "get",
477
719
  ...variables,
478
720
  signal
479
721
  });
480
- const dEPRECATEDcreateDatabase = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}", method: "put", ...variables, signal });
481
- const dEPRECATEDdeleteDatabase = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}", method: "delete", ...variables, signal });
482
- const dEPRECATEDgetDatabaseMetadata = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/metadata", method: "get", ...variables, signal });
483
- const dEPRECATEDupdateDatabaseMetadata = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/metadata", method: "patch", ...variables, signal });
484
722
  const getBranchDetails = (variables, signal) => dataPlaneFetch({
485
723
  url: "/db/{dbBranchName}",
486
724
  method: "get",
@@ -494,6 +732,12 @@ const deleteBranch = (variables, signal) => dataPlaneFetch({
494
732
  ...variables,
495
733
  signal
496
734
  });
735
+ const copyBranch = (variables, signal) => dataPlaneFetch({
736
+ url: "/db/{dbBranchName}/copy",
737
+ method: "post",
738
+ ...variables,
739
+ signal
740
+ });
497
741
  const updateBranchMetadata = (variables, signal) => dataPlaneFetch({
498
742
  url: "/db/{dbBranchName}/metadata",
499
743
  method: "put",
@@ -519,7 +763,6 @@ const resolveBranch = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName
519
763
  const getBranchMigrationHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables, signal });
520
764
  const getBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables, signal });
521
765
  const executeBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables, signal });
522
- const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
523
766
  const queryMigrationRequests = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/query", method: "post", ...variables, signal });
524
767
  const createMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations", method: "post", ...variables, signal });
525
768
  const getMigrationRequest = (variables, signal) => dataPlaneFetch({
@@ -544,6 +787,7 @@ const compareBranchSchemas = (variables, signal) => dataPlaneFetch({ url: "/db/{
544
787
  const updateBranchSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/update", method: "post", ...variables, signal });
545
788
  const previewBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables, signal });
546
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 });
547
791
  const createTable = (variables, signal) => dataPlaneFetch({
548
792
  url: "/db/{dbBranchName}/tables/{tableName}",
549
793
  method: "put",
@@ -586,7 +830,38 @@ const deleteColumn = (variables, signal) => dataPlaneFetch({
586
830
  ...variables,
587
831
  signal
588
832
  });
833
+ const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
589
834
  const insertRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
835
+ const getFileItem = (variables, signal) => dataPlaneFetch({
836
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
837
+ method: "get",
838
+ ...variables,
839
+ signal
840
+ });
841
+ const putFileItem = (variables, signal) => dataPlaneFetch({
842
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
843
+ method: "put",
844
+ ...variables,
845
+ signal
846
+ });
847
+ const deleteFileItem = (variables, signal) => dataPlaneFetch({
848
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
849
+ method: "delete",
850
+ ...variables,
851
+ signal
852
+ });
853
+ const getFile = (variables, signal) => dataPlaneFetch({
854
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
855
+ method: "get",
856
+ ...variables,
857
+ signal
858
+ });
859
+ const putFile = (variables, signal) => dataPlaneFetch({
860
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
861
+ method: "put",
862
+ ...variables,
863
+ signal
864
+ });
590
865
  const getRecord = (variables, signal) => dataPlaneFetch({
591
866
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
592
867
  method: "get",
@@ -616,21 +891,28 @@ const searchTable = (variables, signal) => dataPlaneFetch({
616
891
  ...variables,
617
892
  signal
618
893
  });
894
+ const sqlQuery = (variables, signal) => dataPlaneFetch({
895
+ url: "/db/{dbBranchName}/sql",
896
+ method: "post",
897
+ ...variables,
898
+ signal
899
+ });
900
+ const vectorSearchTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/vectorSearch", method: "post", ...variables, signal });
901
+ const askTable = (variables, signal) => dataPlaneFetch({
902
+ url: "/db/{dbBranchName}/tables/{tableName}/ask",
903
+ method: "post",
904
+ ...variables,
905
+ signal
906
+ });
619
907
  const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
620
908
  const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
621
909
  const operationsByTag$2 = {
622
- database: {
623
- dEPRECATEDgetDatabaseList,
624
- dEPRECATEDcreateDatabase,
625
- dEPRECATEDdeleteDatabase,
626
- dEPRECATEDgetDatabaseMetadata,
627
- dEPRECATEDupdateDatabaseMetadata
628
- },
629
910
  branch: {
630
911
  getBranchList,
631
912
  getBranchDetails,
632
913
  createBranch,
633
914
  deleteBranch,
915
+ copyBranch,
634
916
  updateBranchMetadata,
635
917
  getBranchMetadata,
636
918
  getBranchStats,
@@ -648,17 +930,8 @@ const operationsByTag$2 = {
648
930
  compareBranchSchemas,
649
931
  updateBranchSchema,
650
932
  previewBranchSchemaEdit,
651
- applyBranchSchemaEdit
652
- },
653
- records: {
654
- branchTransaction,
655
- insertRecord,
656
- getRecord,
657
- insertRecordWithID,
658
- updateRecordWithID,
659
- upsertRecordWithID,
660
- deleteRecord,
661
- bulkInsertTableRecords
933
+ applyBranchSchemaEdit,
934
+ pushBranchMigrations
662
935
  },
663
936
  migrationRequests: {
664
937
  queryMigrationRequests,
@@ -682,7 +955,27 @@ const operationsByTag$2 = {
682
955
  updateColumn,
683
956
  deleteColumn
684
957
  },
685
- searchAndFilter: { queryTable, searchBranch, searchTable, summarizeTable, aggregateTable }
958
+ records: {
959
+ branchTransaction,
960
+ insertRecord,
961
+ getRecord,
962
+ insertRecordWithID,
963
+ updateRecordWithID,
964
+ upsertRecordWithID,
965
+ deleteRecord,
966
+ bulkInsertTableRecords
967
+ },
968
+ files: { getFileItem, putFileItem, deleteFileItem, getFile, putFile },
969
+ searchAndFilter: {
970
+ queryTable,
971
+ searchBranch,
972
+ searchTable,
973
+ sqlQuery,
974
+ vectorSearchTable,
975
+ askTable,
976
+ summarizeTable,
977
+ aggregateTable
978
+ }
686
979
  };
687
980
 
688
981
  const controlPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "controlPlane" });
@@ -781,6 +1074,10 @@ const deleteDatabase = (variables, signal) => controlPlaneFetch({
781
1074
  });
782
1075
  const getDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "get", ...variables, signal });
783
1076
  const updateDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "patch", ...variables, signal });
1077
+ const renameDatabase = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/rename", method: "post", ...variables, signal });
1078
+ const getDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "get", ...variables, signal });
1079
+ const updateDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "put", ...variables, signal });
1080
+ const deleteDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "delete", ...variables, signal });
784
1081
  const listRegions = (variables, signal) => controlPlaneFetch({
785
1082
  url: "/workspaces/{workspaceId}/regions",
786
1083
  method: "get",
@@ -813,6 +1110,10 @@ const operationsByTag$1 = {
813
1110
  deleteDatabase,
814
1111
  getDatabaseMetadata,
815
1112
  updateDatabaseMetadata,
1113
+ renameDatabase,
1114
+ getDatabaseGithubSettings,
1115
+ updateDatabaseGithubSettings,
1116
+ deleteDatabaseGithubSettings,
816
1117
  listRegions
817
1118
  }
818
1119
  };
@@ -833,8 +1134,12 @@ const providers = {
833
1134
  workspaces: "https://{workspaceId}.{region}.xata.sh"
834
1135
  },
835
1136
  staging: {
836
- main: "https://staging.xatabase.co",
837
- workspaces: "https://{workspaceId}.staging.{region}.xatabase.co"
1137
+ main: "https://api.staging-xata.dev",
1138
+ workspaces: "https://{workspaceId}.{region}.staging-xata.dev"
1139
+ },
1140
+ dev: {
1141
+ main: "https://api.dev-xata.dev",
1142
+ workspaces: "https://{workspaceId}.{region}.dev-xata.dev"
838
1143
  }
839
1144
  };
840
1145
  function isHostProviderAlias(alias) {
@@ -852,12 +1157,19 @@ function parseProviderString(provider = "production") {
852
1157
  return null;
853
1158
  return { main, workspaces };
854
1159
  }
1160
+ function buildProviderString(provider) {
1161
+ if (isHostProviderAlias(provider))
1162
+ return provider;
1163
+ return `${provider.main},${provider.workspaces}`;
1164
+ }
855
1165
  function parseWorkspacesUrlParts(url) {
856
1166
  if (!isString(url))
857
1167
  return null;
858
1168
  const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/;
859
- const regexStaging = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))\.xatabase\.co.*/;
860
- const match = url.match(regex) || url.match(regexStaging);
1169
+ const regexDev = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.dev-xata\.dev.*/;
1170
+ const regexStaging = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.staging-xata\.dev.*/;
1171
+ const regexProdTesting = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.tech.*/;
1172
+ const match = url.match(regex) || url.match(regexDev) || url.match(regexStaging) || url.match(regexProdTesting);
861
1173
  if (!match)
862
1174
  return null;
863
1175
  return { workspace: match[1], region: match[2] };
@@ -896,10 +1208,11 @@ class XataApiClient {
896
1208
  __privateSet$7(this, _extraProps, {
897
1209
  apiUrl: getHostUrl(provider, "main"),
898
1210
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
899
- fetchImpl: getFetchImplementation(options.fetch),
1211
+ fetch: getFetchImplementation(options.fetch),
900
1212
  apiKey,
901
1213
  trace,
902
1214
  clientName: options.clientName,
1215
+ xataAgentExtra: options.xataAgentExtra,
903
1216
  clientID
904
1217
  });
905
1218
  }
@@ -953,6 +1266,11 @@ class XataApiClient {
953
1266
  __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
954
1267
  return __privateGet$7(this, _namespaces).records;
955
1268
  }
1269
+ get files() {
1270
+ if (!__privateGet$7(this, _namespaces).files)
1271
+ __privateGet$7(this, _namespaces).files = new FilesApi(__privateGet$7(this, _extraProps));
1272
+ return __privateGet$7(this, _namespaces).files;
1273
+ }
956
1274
  get searchAndFilter() {
957
1275
  if (!__privateGet$7(this, _namespaces).searchAndFilter)
958
1276
  __privateGet$7(this, _namespaces).searchAndFilter = new SearchAndFilterApi(__privateGet$7(this, _extraProps));
@@ -1161,6 +1479,20 @@ class BranchApi {
1161
1479
  ...this.extraProps
1162
1480
  });
1163
1481
  }
1482
+ copyBranch({
1483
+ workspace,
1484
+ region,
1485
+ database,
1486
+ branch,
1487
+ destinationBranch,
1488
+ limit
1489
+ }) {
1490
+ return operationsByTag.branch.copyBranch({
1491
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1492
+ body: { destinationBranch, limit },
1493
+ ...this.extraProps
1494
+ });
1495
+ }
1164
1496
  updateBranchMetadata({
1165
1497
  workspace,
1166
1498
  region,
@@ -1516,6 +1848,126 @@ class RecordsApi {
1516
1848
  });
1517
1849
  }
1518
1850
  }
1851
+ class FilesApi {
1852
+ constructor(extraProps) {
1853
+ this.extraProps = extraProps;
1854
+ }
1855
+ getFileItem({
1856
+ workspace,
1857
+ region,
1858
+ database,
1859
+ branch,
1860
+ table,
1861
+ record,
1862
+ column,
1863
+ fileId
1864
+ }) {
1865
+ return operationsByTag.files.getFileItem({
1866
+ pathParams: {
1867
+ workspace,
1868
+ region,
1869
+ dbBranchName: `${database}:${branch}`,
1870
+ tableName: table,
1871
+ recordId: record,
1872
+ columnName: column,
1873
+ fileId
1874
+ },
1875
+ ...this.extraProps
1876
+ });
1877
+ }
1878
+ putFileItem({
1879
+ workspace,
1880
+ region,
1881
+ database,
1882
+ branch,
1883
+ table,
1884
+ record,
1885
+ column,
1886
+ fileId,
1887
+ file
1888
+ }) {
1889
+ return operationsByTag.files.putFileItem({
1890
+ pathParams: {
1891
+ workspace,
1892
+ region,
1893
+ dbBranchName: `${database}:${branch}`,
1894
+ tableName: table,
1895
+ recordId: record,
1896
+ columnName: column,
1897
+ fileId
1898
+ },
1899
+ body: file,
1900
+ ...this.extraProps
1901
+ });
1902
+ }
1903
+ deleteFileItem({
1904
+ workspace,
1905
+ region,
1906
+ database,
1907
+ branch,
1908
+ table,
1909
+ record,
1910
+ column,
1911
+ fileId
1912
+ }) {
1913
+ return operationsByTag.files.deleteFileItem({
1914
+ pathParams: {
1915
+ workspace,
1916
+ region,
1917
+ dbBranchName: `${database}:${branch}`,
1918
+ tableName: table,
1919
+ recordId: record,
1920
+ columnName: column,
1921
+ fileId
1922
+ },
1923
+ ...this.extraProps
1924
+ });
1925
+ }
1926
+ getFile({
1927
+ workspace,
1928
+ region,
1929
+ database,
1930
+ branch,
1931
+ table,
1932
+ record,
1933
+ column
1934
+ }) {
1935
+ return operationsByTag.files.getFile({
1936
+ pathParams: {
1937
+ workspace,
1938
+ region,
1939
+ dbBranchName: `${database}:${branch}`,
1940
+ tableName: table,
1941
+ recordId: record,
1942
+ columnName: column
1943
+ },
1944
+ ...this.extraProps
1945
+ });
1946
+ }
1947
+ putFile({
1948
+ workspace,
1949
+ region,
1950
+ database,
1951
+ branch,
1952
+ table,
1953
+ record,
1954
+ column,
1955
+ file
1956
+ }) {
1957
+ return operationsByTag.files.putFile({
1958
+ pathParams: {
1959
+ workspace,
1960
+ region,
1961
+ dbBranchName: `${database}:${branch}`,
1962
+ tableName: table,
1963
+ recordId: record,
1964
+ columnName: column
1965
+ },
1966
+ body: file,
1967
+ ...this.extraProps
1968
+ });
1969
+ }
1970
+ }
1519
1971
  class SearchAndFilterApi {
1520
1972
  constructor(extraProps) {
1521
1973
  this.extraProps = extraProps;
@@ -1575,6 +2027,38 @@ class SearchAndFilterApi {
1575
2027
  ...this.extraProps
1576
2028
  });
1577
2029
  }
2030
+ vectorSearchTable({
2031
+ workspace,
2032
+ region,
2033
+ database,
2034
+ branch,
2035
+ table,
2036
+ queryVector,
2037
+ column,
2038
+ similarityFunction,
2039
+ size,
2040
+ filter
2041
+ }) {
2042
+ return operationsByTag.searchAndFilter.vectorSearchTable({
2043
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2044
+ body: { queryVector, column, similarityFunction, size, filter },
2045
+ ...this.extraProps
2046
+ });
2047
+ }
2048
+ askTable({
2049
+ workspace,
2050
+ region,
2051
+ database,
2052
+ branch,
2053
+ table,
2054
+ options
2055
+ }) {
2056
+ return operationsByTag.searchAndFilter.askTable({
2057
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2058
+ body: { ...options },
2059
+ ...this.extraProps
2060
+ });
2061
+ }
1578
2062
  summarizeTable({
1579
2063
  workspace,
1580
2064
  region,
@@ -1775,11 +2259,13 @@ class MigrationsApi {
1775
2259
  region,
1776
2260
  database,
1777
2261
  branch,
1778
- schema
2262
+ schema,
2263
+ schemaOperations,
2264
+ branchOperations
1779
2265
  }) {
1780
2266
  return operationsByTag.migrations.compareBranchWithUserSchema({
1781
2267
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1782
- body: { schema },
2268
+ body: { schema, schemaOperations, branchOperations },
1783
2269
  ...this.extraProps
1784
2270
  });
1785
2271
  }
@@ -1789,11 +2275,12 @@ class MigrationsApi {
1789
2275
  database,
1790
2276
  branch,
1791
2277
  compare,
1792
- schema
2278
+ sourceBranchOperations,
2279
+ targetBranchOperations
1793
2280
  }) {
1794
2281
  return operationsByTag.migrations.compareBranchSchemas({
1795
2282
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, branchName: compare },
1796
- body: { schema },
2283
+ body: { sourceBranchOperations, targetBranchOperations },
1797
2284
  ...this.extraProps
1798
2285
  });
1799
2286
  }
@@ -1836,6 +2323,19 @@ class MigrationsApi {
1836
2323
  ...this.extraProps
1837
2324
  });
1838
2325
  }
2326
+ pushBranchMigrations({
2327
+ workspace,
2328
+ region,
2329
+ database,
2330
+ branch,
2331
+ migrations
2332
+ }) {
2333
+ return operationsByTag.migrations.pushBranchMigrations({
2334
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2335
+ body: { migrations },
2336
+ ...this.extraProps
2337
+ });
2338
+ }
1839
2339
  }
1840
2340
  class DatabaseApi {
1841
2341
  constructor(extraProps) {
@@ -1887,6 +2387,46 @@ class DatabaseApi {
1887
2387
  ...this.extraProps
1888
2388
  });
1889
2389
  }
2390
+ renameDatabase({
2391
+ workspace,
2392
+ database,
2393
+ newName
2394
+ }) {
2395
+ return operationsByTag.databases.renameDatabase({
2396
+ pathParams: { workspaceId: workspace, dbName: database },
2397
+ body: { newName },
2398
+ ...this.extraProps
2399
+ });
2400
+ }
2401
+ getDatabaseGithubSettings({
2402
+ workspace,
2403
+ database
2404
+ }) {
2405
+ return operationsByTag.databases.getDatabaseGithubSettings({
2406
+ pathParams: { workspaceId: workspace, dbName: database },
2407
+ ...this.extraProps
2408
+ });
2409
+ }
2410
+ updateDatabaseGithubSettings({
2411
+ workspace,
2412
+ database,
2413
+ settings
2414
+ }) {
2415
+ return operationsByTag.databases.updateDatabaseGithubSettings({
2416
+ pathParams: { workspaceId: workspace, dbName: database },
2417
+ body: settings,
2418
+ ...this.extraProps
2419
+ });
2420
+ }
2421
+ deleteDatabaseGithubSettings({
2422
+ workspace,
2423
+ database
2424
+ }) {
2425
+ return operationsByTag.databases.deleteDatabaseGithubSettings({
2426
+ pathParams: { workspaceId: workspace, dbName: database },
2427
+ ...this.extraProps
2428
+ });
2429
+ }
1890
2430
  listRegions({ workspace }) {
1891
2431
  return operationsByTag.databases.listRegions({
1892
2432
  pathParams: { workspaceId: workspace },
@@ -1896,9 +2436,8 @@ class DatabaseApi {
1896
2436
  }
1897
2437
 
1898
2438
  class XataApiPlugin {
1899
- async build(options) {
1900
- const { fetchImpl, apiKey } = await options.getFetchProps();
1901
- return new XataApiClient({ fetch: fetchImpl, apiKey });
2439
+ build(options) {
2440
+ return new XataApiClient(options);
1902
2441
  }
1903
2442
  }
1904
2443
 
@@ -1981,6 +2520,12 @@ const _RecordArray = class extends Array {
1981
2520
  toArray() {
1982
2521
  return new Array(...this);
1983
2522
  }
2523
+ toSerializable() {
2524
+ return JSON.parse(this.toString());
2525
+ }
2526
+ toString() {
2527
+ return JSON.stringify(this.toArray());
2528
+ }
1984
2529
  map(callbackfn, thisArg) {
1985
2530
  return this.toArray().map(callbackfn, thisArg);
1986
2531
  }
@@ -2233,7 +2778,11 @@ function isSortFilterString(value) {
2233
2778
  return isString(value);
2234
2779
  }
2235
2780
  function isSortFilterBase(filter) {
2236
- return isObject(filter) && Object.values(filter).every((value) => value === "asc" || value === "desc");
2781
+ return isObject(filter) && Object.entries(filter).every(([key, value]) => {
2782
+ if (key === "*")
2783
+ return value === "random";
2784
+ return value === "asc" || value === "desc";
2785
+ });
2237
2786
  }
2238
2787
  function isSortFilterObject(filter) {
2239
2788
  return isObject(filter) && !isSortFilterBase(filter) && filter.column !== void 0;
@@ -2306,10 +2855,7 @@ class RestRepository extends Query {
2306
2855
  __privateSet$4(this, _db, options.db);
2307
2856
  __privateSet$4(this, _cache, options.pluginOptions.cache);
2308
2857
  __privateSet$4(this, _schemaTables$2, options.schemaTables);
2309
- __privateSet$4(this, _getFetchProps, async () => {
2310
- const props = await options.pluginOptions.getFetchProps();
2311
- return { ...props, sessionID: generateUUID() };
2312
- });
2858
+ __privateSet$4(this, _getFetchProps, () => ({ ...options.pluginOptions, sessionID: generateUUID() }));
2313
2859
  const trace = options.pluginOptions.trace ?? defaultTrace;
2314
2860
  __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
2315
2861
  return trace(name, fn, {
@@ -2366,7 +2912,6 @@ class RestRepository extends Query {
2366
2912
  }
2367
2913
  const id = extractId(a);
2368
2914
  if (id) {
2369
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2370
2915
  try {
2371
2916
  const response = await getRecord({
2372
2917
  pathParams: {
@@ -2377,7 +2922,7 @@ class RestRepository extends Query {
2377
2922
  recordId: id
2378
2923
  },
2379
2924
  queryParams: { columns },
2380
- ...fetchProps
2925
+ ...__privateGet$4(this, _getFetchProps).call(this)
2381
2926
  });
2382
2927
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2383
2928
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2555,7 +3100,6 @@ class RestRepository extends Query {
2555
3100
  }
2556
3101
  async search(query, options = {}) {
2557
3102
  return __privateGet$4(this, _trace).call(this, "search", async () => {
2558
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2559
3103
  const { records } = await searchTable({
2560
3104
  pathParams: {
2561
3105
  workspace: "{workspaceId}",
@@ -2573,7 +3117,29 @@ class RestRepository extends Query {
2573
3117
  page: options.page,
2574
3118
  target: options.target
2575
3119
  },
2576
- ...fetchProps
3120
+ ...__privateGet$4(this, _getFetchProps).call(this)
3121
+ });
3122
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3123
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
3124
+ });
3125
+ }
3126
+ async vectorSearch(column, query, options) {
3127
+ return __privateGet$4(this, _trace).call(this, "vectorSearch", async () => {
3128
+ const { records } = await vectorSearchTable({
3129
+ pathParams: {
3130
+ workspace: "{workspaceId}",
3131
+ dbBranchName: "{dbBranch}",
3132
+ region: "{region}",
3133
+ tableName: __privateGet$4(this, _table)
3134
+ },
3135
+ body: {
3136
+ column,
3137
+ queryVector: query,
3138
+ similarityFunction: options?.similarityFunction,
3139
+ size: options?.size,
3140
+ filter: options?.filter
3141
+ },
3142
+ ...__privateGet$4(this, _getFetchProps).call(this)
2577
3143
  });
2578
3144
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2579
3145
  return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
@@ -2581,7 +3147,6 @@ class RestRepository extends Query {
2581
3147
  }
2582
3148
  async aggregate(aggs, filter) {
2583
3149
  return __privateGet$4(this, _trace).call(this, "aggregate", async () => {
2584
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2585
3150
  const result = await aggregateTable({
2586
3151
  pathParams: {
2587
3152
  workspace: "{workspaceId}",
@@ -2590,7 +3155,7 @@ class RestRepository extends Query {
2590
3155
  tableName: __privateGet$4(this, _table)
2591
3156
  },
2592
3157
  body: { aggs, filter },
2593
- ...fetchProps
3158
+ ...__privateGet$4(this, _getFetchProps).call(this)
2594
3159
  });
2595
3160
  return result;
2596
3161
  });
@@ -2601,7 +3166,6 @@ class RestRepository extends Query {
2601
3166
  if (cacheQuery)
2602
3167
  return new Page(query, cacheQuery.meta, cacheQuery.records);
2603
3168
  const data = query.getQueryOptions();
2604
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2605
3169
  const { meta, records: objects } = await queryTable({
2606
3170
  pathParams: {
2607
3171
  workspace: "{workspaceId}",
@@ -2617,7 +3181,7 @@ class RestRepository extends Query {
2617
3181
  consistency: data.consistency
2618
3182
  },
2619
3183
  fetchOptions: data.fetchOptions,
2620
- ...fetchProps
3184
+ ...__privateGet$4(this, _getFetchProps).call(this)
2621
3185
  });
2622
3186
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2623
3187
  const records = objects.map(
@@ -2630,7 +3194,6 @@ class RestRepository extends Query {
2630
3194
  async summarizeTable(query, summaries, summariesFilter) {
2631
3195
  return __privateGet$4(this, _trace).call(this, "summarize", async () => {
2632
3196
  const data = query.getQueryOptions();
2633
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2634
3197
  const result = await summarizeTable({
2635
3198
  pathParams: {
2636
3199
  workspace: "{workspaceId}",
@@ -2647,11 +3210,39 @@ class RestRepository extends Query {
2647
3210
  summaries,
2648
3211
  summariesFilter
2649
3212
  },
2650
- ...fetchProps
3213
+ ...__privateGet$4(this, _getFetchProps).call(this)
2651
3214
  });
2652
3215
  return result;
2653
3216
  });
2654
3217
  }
3218
+ ask(question, options) {
3219
+ const params = {
3220
+ pathParams: {
3221
+ workspace: "{workspaceId}",
3222
+ dbBranchName: "{dbBranch}",
3223
+ region: "{region}",
3224
+ tableName: __privateGet$4(this, _table)
3225
+ },
3226
+ body: {
3227
+ question,
3228
+ ...options
3229
+ },
3230
+ ...__privateGet$4(this, _getFetchProps).call(this)
3231
+ };
3232
+ if (options?.onMessage) {
3233
+ fetchSSERequest({
3234
+ endpoint: "dataPlane",
3235
+ url: "/db/{dbBranchName}/tables/{tableName}/ask",
3236
+ method: "POST",
3237
+ onMessage: (message) => {
3238
+ options.onMessage?.({ answer: message.text, records: message.records });
3239
+ },
3240
+ ...params
3241
+ });
3242
+ } else {
3243
+ return askTable(params);
3244
+ }
3245
+ }
2655
3246
  }
2656
3247
  _table = new WeakMap();
2657
3248
  _getFetchProps = new WeakMap();
@@ -2661,7 +3252,6 @@ _schemaTables$2 = new WeakMap();
2661
3252
  _trace = new WeakMap();
2662
3253
  _insertRecordWithoutId = new WeakSet();
2663
3254
  insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
2664
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2665
3255
  const record = transformObjectLinks(object);
2666
3256
  const response = await insertRecord({
2667
3257
  pathParams: {
@@ -2672,14 +3262,13 @@ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
2672
3262
  },
2673
3263
  queryParams: { columns },
2674
3264
  body: record,
2675
- ...fetchProps
3265
+ ...__privateGet$4(this, _getFetchProps).call(this)
2676
3266
  });
2677
3267
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2678
3268
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2679
3269
  };
2680
3270
  _insertRecordWithId = new WeakSet();
2681
3271
  insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { createOnly, ifVersion }) {
2682
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2683
3272
  const record = transformObjectLinks(object);
2684
3273
  const response = await insertRecordWithID({
2685
3274
  pathParams: {
@@ -2691,14 +3280,13 @@ insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { crea
2691
3280
  },
2692
3281
  body: record,
2693
3282
  queryParams: { createOnly, columns, ifVersion },
2694
- ...fetchProps
3283
+ ...__privateGet$4(this, _getFetchProps).call(this)
2695
3284
  });
2696
3285
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2697
3286
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2698
3287
  };
2699
3288
  _insertRecords = new WeakSet();
2700
3289
  insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2701
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2702
3290
  const chunkedOperations = chunk(
2703
3291
  objects.map((object) => ({
2704
3292
  insert: { table: __privateGet$4(this, _table), record: transformObjectLinks(object), createOnly, ifVersion }
@@ -2714,7 +3302,7 @@ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2714
3302
  region: "{region}"
2715
3303
  },
2716
3304
  body: { operations },
2717
- ...fetchProps
3305
+ ...__privateGet$4(this, _getFetchProps).call(this)
2718
3306
  });
2719
3307
  for (const result of results) {
2720
3308
  if (result.operation === "insert") {
@@ -2728,7 +3316,6 @@ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2728
3316
  };
2729
3317
  _updateRecordWithID = new WeakSet();
2730
3318
  updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2731
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2732
3319
  const { id: _id, ...record } = transformObjectLinks(object);
2733
3320
  try {
2734
3321
  const response = await updateRecordWithID({
@@ -2741,7 +3328,7 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2741
3328
  },
2742
3329
  queryParams: { columns, ifVersion },
2743
3330
  body: record,
2744
- ...fetchProps
3331
+ ...__privateGet$4(this, _getFetchProps).call(this)
2745
3332
  });
2746
3333
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2747
3334
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2754,7 +3341,6 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2754
3341
  };
2755
3342
  _updateRecords = new WeakSet();
2756
3343
  updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2757
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2758
3344
  const chunkedOperations = chunk(
2759
3345
  objects.map(({ id, ...object }) => ({
2760
3346
  update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields: transformObjectLinks(object) }
@@ -2770,7 +3356,7 @@ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2770
3356
  region: "{region}"
2771
3357
  },
2772
3358
  body: { operations },
2773
- ...fetchProps
3359
+ ...__privateGet$4(this, _getFetchProps).call(this)
2774
3360
  });
2775
3361
  for (const result of results) {
2776
3362
  if (result.operation === "update") {
@@ -2784,7 +3370,6 @@ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2784
3370
  };
2785
3371
  _upsertRecordWithID = new WeakSet();
2786
3372
  upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2787
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2788
3373
  const response = await upsertRecordWithID({
2789
3374
  pathParams: {
2790
3375
  workspace: "{workspaceId}",
@@ -2795,14 +3380,13 @@ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2795
3380
  },
2796
3381
  queryParams: { columns, ifVersion },
2797
3382
  body: object,
2798
- ...fetchProps
3383
+ ...__privateGet$4(this, _getFetchProps).call(this)
2799
3384
  });
2800
3385
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2801
3386
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2802
3387
  };
2803
3388
  _deleteRecord = new WeakSet();
2804
3389
  deleteRecord_fn = async function(recordId, columns = ["*"]) {
2805
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2806
3390
  try {
2807
3391
  const response = await deleteRecord({
2808
3392
  pathParams: {
@@ -2813,7 +3397,7 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2813
3397
  recordId
2814
3398
  },
2815
3399
  queryParams: { columns },
2816
- ...fetchProps
3400
+ ...__privateGet$4(this, _getFetchProps).call(this)
2817
3401
  });
2818
3402
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2819
3403
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2826,7 +3410,6 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2826
3410
  };
2827
3411
  _deleteRecords = new WeakSet();
2828
3412
  deleteRecords_fn = async function(recordIds) {
2829
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2830
3413
  const chunkedOperations = chunk(
2831
3414
  recordIds.map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
2832
3415
  BULK_OPERATION_MAX_SIZE
@@ -2839,21 +3422,22 @@ deleteRecords_fn = async function(recordIds) {
2839
3422
  region: "{region}"
2840
3423
  },
2841
3424
  body: { operations },
2842
- ...fetchProps
3425
+ ...__privateGet$4(this, _getFetchProps).call(this)
2843
3426
  });
2844
3427
  }
2845
3428
  };
2846
3429
  _setCacheQuery = new WeakSet();
2847
3430
  setCacheQuery_fn = async function(query, meta, records) {
2848
- await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
3431
+ await __privateGet$4(this, _cache)?.set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
2849
3432
  };
2850
3433
  _getCacheQuery = new WeakSet();
2851
3434
  getCacheQuery_fn = async function(query) {
2852
3435
  const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
2853
- const result = await __privateGet$4(this, _cache).get(key);
3436
+ const result = await __privateGet$4(this, _cache)?.get(key);
2854
3437
  if (!result)
2855
3438
  return null;
2856
- const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
3439
+ const defaultTTL = __privateGet$4(this, _cache)?.defaultQueryTTL ?? -1;
3440
+ const { cache: ttl = defaultTTL } = query.getQueryOptions();
2857
3441
  if (ttl < 0)
2858
3442
  return null;
2859
3443
  const hasExpired = result.date.getTime() + ttl < Date.now();
@@ -2863,10 +3447,9 @@ _getSchemaTables$1 = new WeakSet();
2863
3447
  getSchemaTables_fn$1 = async function() {
2864
3448
  if (__privateGet$4(this, _schemaTables$2))
2865
3449
  return __privateGet$4(this, _schemaTables$2);
2866
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2867
3450
  const { schema } = await getBranchDetails({
2868
3451
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
2869
- ...fetchProps
3452
+ ...__privateGet$4(this, _getFetchProps).call(this)
2870
3453
  });
2871
3454
  __privateSet$4(this, _schemaTables$2, schema.tables);
2872
3455
  return schema.tables;
@@ -2879,23 +3462,23 @@ const transformObjectLinks = (object) => {
2879
3462
  }, {});
2880
3463
  };
2881
3464
  const initObject = (db, schemaTables, table, object, selectedColumns) => {
2882
- const result = {};
3465
+ const data = {};
2883
3466
  const { xata, ...rest } = object ?? {};
2884
- Object.assign(result, rest);
3467
+ Object.assign(data, rest);
2885
3468
  const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
2886
3469
  if (!columns)
2887
3470
  console.error(`Table ${table} not found in schema`);
2888
3471
  for (const column of columns ?? []) {
2889
3472
  if (!isValidColumn(selectedColumns, column))
2890
3473
  continue;
2891
- const value = result[column.name];
3474
+ const value = data[column.name];
2892
3475
  switch (column.type) {
2893
3476
  case "datetime": {
2894
3477
  const date = value !== void 0 ? new Date(value) : null;
2895
3478
  if (date !== null && isNaN(date.getTime())) {
2896
3479
  console.error(`Failed to parse date ${value} for field ${column.name}`);
2897
3480
  } else {
2898
- result[column.name] = date;
3481
+ data[column.name] = date;
2899
3482
  }
2900
3483
  break;
2901
3484
  }
@@ -2914,44 +3497,51 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
2914
3497
  }
2915
3498
  return acc;
2916
3499
  }, []);
2917
- result[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
3500
+ data[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
2918
3501
  } else {
2919
- result[column.name] = null;
3502
+ data[column.name] = null;
2920
3503
  }
2921
3504
  break;
2922
3505
  }
2923
3506
  default:
2924
- result[column.name] = value ?? null;
3507
+ data[column.name] = value ?? null;
2925
3508
  if (column.notNull === true && value === null) {
2926
3509
  console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
2927
3510
  }
2928
3511
  break;
2929
3512
  }
2930
3513
  }
2931
- result.read = function(columns2) {
2932
- return db[table].read(result["id"], columns2);
3514
+ const record = { ...data };
3515
+ record.read = function(columns2) {
3516
+ return db[table].read(record["id"], columns2);
2933
3517
  };
2934
- result.update = function(data, b, c) {
3518
+ record.update = function(data2, b, c) {
2935
3519
  const columns2 = isStringArray(b) ? b : ["*"];
2936
3520
  const ifVersion = parseIfVersion(b, c);
2937
- return db[table].update(result["id"], data, columns2, { ifVersion });
3521
+ return db[table].update(record["id"], data2, columns2, { ifVersion });
2938
3522
  };
2939
- result.replace = function(data, b, c) {
3523
+ record.replace = function(data2, b, c) {
2940
3524
  const columns2 = isStringArray(b) ? b : ["*"];
2941
3525
  const ifVersion = parseIfVersion(b, c);
2942
- return db[table].createOrReplace(result["id"], data, columns2, { ifVersion });
3526
+ return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
2943
3527
  };
2944
- result.delete = function() {
2945
- return db[table].delete(result["id"]);
3528
+ record.delete = function() {
3529
+ return db[table].delete(record["id"]);
2946
3530
  };
2947
- result.getMetadata = function() {
3531
+ record.getMetadata = function() {
2948
3532
  return xata;
2949
3533
  };
2950
- for (const prop of ["read", "update", "replace", "delete", "getMetadata"]) {
2951
- Object.defineProperty(result, prop, { enumerable: false });
3534
+ record.toSerializable = function() {
3535
+ return JSON.parse(JSON.stringify(transformObjectLinks(data)));
3536
+ };
3537
+ record.toString = function() {
3538
+ return JSON.stringify(transformObjectLinks(data));
3539
+ };
3540
+ for (const prop of ["read", "update", "replace", "delete", "getMetadata", "toSerializable", "toString"]) {
3541
+ Object.defineProperty(record, prop, { enumerable: false });
2952
3542
  }
2953
- Object.freeze(result);
2954
- return result;
3543
+ Object.freeze(record);
3544
+ return record;
2955
3545
  };
2956
3546
  function extractId(value) {
2957
3547
  if (isString(value))
@@ -3135,19 +3725,19 @@ class SearchPlugin extends XataPlugin {
3135
3725
  __privateAdd$1(this, _schemaTables, void 0);
3136
3726
  __privateSet$1(this, _schemaTables, schemaTables);
3137
3727
  }
3138
- build({ getFetchProps }) {
3728
+ build(pluginOptions) {
3139
3729
  return {
3140
3730
  all: async (query, options = {}) => {
3141
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
3142
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
3731
+ const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
3732
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
3143
3733
  return records.map((record) => {
3144
3734
  const { table = "orphan" } = record.xata;
3145
3735
  return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
3146
3736
  });
3147
3737
  },
3148
3738
  byTable: async (query, options = {}) => {
3149
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
3150
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
3739
+ const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
3740
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
3151
3741
  return records.reduce((acc, record) => {
3152
3742
  const { table = "orphan" } = record.xata;
3153
3743
  const items = acc[table] ?? [];
@@ -3160,38 +3750,35 @@ class SearchPlugin extends XataPlugin {
3160
3750
  }
3161
3751
  _schemaTables = new WeakMap();
3162
3752
  _search = new WeakSet();
3163
- search_fn = async function(query, options, getFetchProps) {
3164
- const fetchProps = await getFetchProps();
3753
+ search_fn = async function(query, options, pluginOptions) {
3165
3754
  const { tables, fuzziness, highlight, prefix, page } = options ?? {};
3166
3755
  const { records } = await searchBranch({
3167
3756
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3168
3757
  body: { tables, query, fuzziness, prefix, highlight, page },
3169
- ...fetchProps
3758
+ ...pluginOptions
3170
3759
  });
3171
3760
  return records;
3172
3761
  };
3173
3762
  _getSchemaTables = new WeakSet();
3174
- getSchemaTables_fn = async function(getFetchProps) {
3763
+ getSchemaTables_fn = async function(pluginOptions) {
3175
3764
  if (__privateGet$1(this, _schemaTables))
3176
3765
  return __privateGet$1(this, _schemaTables);
3177
- const fetchProps = await getFetchProps();
3178
3766
  const { schema } = await getBranchDetails({
3179
3767
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3180
- ...fetchProps
3768
+ ...pluginOptions
3181
3769
  });
3182
3770
  __privateSet$1(this, _schemaTables, schema.tables);
3183
3771
  return schema.tables;
3184
3772
  };
3185
3773
 
3186
3774
  class TransactionPlugin extends XataPlugin {
3187
- build({ getFetchProps }) {
3775
+ build(pluginOptions) {
3188
3776
  return {
3189
3777
  run: async (operations) => {
3190
- const fetchProps = await getFetchProps();
3191
3778
  const response = await branchTransaction({
3192
3779
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3193
3780
  body: { operations },
3194
- ...fetchProps
3781
+ ...pluginOptions
3195
3782
  });
3196
3783
  return response;
3197
3784
  }
@@ -3199,90 +3786,6 @@ class TransactionPlugin extends XataPlugin {
3199
3786
  }
3200
3787
  }
3201
3788
 
3202
- const isBranchStrategyBuilder = (strategy) => {
3203
- return typeof strategy === "function";
3204
- };
3205
-
3206
- async function getCurrentBranchName(options) {
3207
- const { branch, envBranch } = getEnvironment();
3208
- if (branch)
3209
- return branch;
3210
- const gitBranch = envBranch || await getGitBranch();
3211
- return resolveXataBranch(gitBranch, options);
3212
- }
3213
- async function getCurrentBranchDetails(options) {
3214
- const branch = await getCurrentBranchName(options);
3215
- return getDatabaseBranch(branch, options);
3216
- }
3217
- async function resolveXataBranch(gitBranch, options) {
3218
- const databaseURL = options?.databaseURL || getDatabaseURL();
3219
- const apiKey = options?.apiKey || getAPIKey();
3220
- if (!databaseURL)
3221
- throw new Error(
3222
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
3223
- );
3224
- if (!apiKey)
3225
- throw new Error(
3226
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
3227
- );
3228
- const [protocol, , host, , dbName] = databaseURL.split("/");
3229
- const urlParts = parseWorkspacesUrlParts(host);
3230
- if (!urlParts)
3231
- throw new Error(`Unable to parse workspace and region: ${databaseURL}`);
3232
- const { workspace, region } = urlParts;
3233
- const { fallbackBranch } = getEnvironment();
3234
- const { branch } = await resolveBranch({
3235
- apiKey,
3236
- apiUrl: databaseURL,
3237
- fetchImpl: getFetchImplementation(options?.fetchImpl),
3238
- workspacesApiUrl: `${protocol}//${host}`,
3239
- pathParams: { dbName, workspace, region },
3240
- queryParams: { gitBranch, fallbackBranch },
3241
- trace: defaultTrace,
3242
- clientName: options?.clientName
3243
- });
3244
- return branch;
3245
- }
3246
- async function getDatabaseBranch(branch, options) {
3247
- const databaseURL = options?.databaseURL || getDatabaseURL();
3248
- const apiKey = options?.apiKey || getAPIKey();
3249
- if (!databaseURL)
3250
- throw new Error(
3251
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
3252
- );
3253
- if (!apiKey)
3254
- throw new Error(
3255
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
3256
- );
3257
- const [protocol, , host, , database] = databaseURL.split("/");
3258
- const urlParts = parseWorkspacesUrlParts(host);
3259
- if (!urlParts)
3260
- throw new Error(`Unable to parse workspace and region: ${databaseURL}`);
3261
- const { workspace, region } = urlParts;
3262
- try {
3263
- return await getBranchDetails({
3264
- apiKey,
3265
- apiUrl: databaseURL,
3266
- fetchImpl: getFetchImplementation(options?.fetchImpl),
3267
- workspacesApiUrl: `${protocol}//${host}`,
3268
- pathParams: { dbBranchName: `${database}:${branch}`, workspace, region },
3269
- trace: defaultTrace
3270
- });
3271
- } catch (err) {
3272
- if (isObject(err) && err.status === 404)
3273
- return null;
3274
- throw err;
3275
- }
3276
- }
3277
- function getDatabaseURL() {
3278
- try {
3279
- const { databaseURL } = getEnvironment();
3280
- return databaseURL;
3281
- } catch (err) {
3282
- return void 0;
3283
- }
3284
- }
3285
-
3286
3789
  var __accessCheck = (obj, member, msg) => {
3287
3790
  if (!member.has(obj))
3288
3791
  throw TypeError("Cannot " + msg);
@@ -3306,20 +3809,18 @@ var __privateMethod = (obj, member, method) => {
3306
3809
  return method;
3307
3810
  };
3308
3811
  const buildClient = (plugins) => {
3309
- var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
3812
+ var _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _a;
3310
3813
  return _a = class {
3311
3814
  constructor(options = {}, schemaTables) {
3312
3815
  __privateAdd(this, _parseOptions);
3313
3816
  __privateAdd(this, _getFetchProps);
3314
- __privateAdd(this, _evaluateBranch);
3315
- __privateAdd(this, _branch, void 0);
3316
3817
  __privateAdd(this, _options, void 0);
3317
3818
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
3318
3819
  __privateSet(this, _options, safeOptions);
3319
3820
  const pluginOptions = {
3320
- getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
3821
+ ...__privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
3321
3822
  cache: safeOptions.cache,
3322
- trace: safeOptions.trace
3823
+ host: safeOptions.host
3323
3824
  };
3324
3825
  const db = new SchemaPlugin(schemaTables).build(pluginOptions);
3325
3826
  const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
@@ -3330,24 +3831,17 @@ const buildClient = (plugins) => {
3330
3831
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
3331
3832
  if (namespace === void 0)
3332
3833
  continue;
3333
- const result = namespace.build(pluginOptions);
3334
- if (result instanceof Promise) {
3335
- void result.then((namespace2) => {
3336
- this[key] = namespace2;
3337
- });
3338
- } else {
3339
- this[key] = result;
3340
- }
3834
+ this[key] = namespace.build(pluginOptions);
3341
3835
  }
3342
3836
  }
3343
3837
  async getConfig() {
3344
3838
  const databaseURL = __privateGet(this, _options).databaseURL;
3345
- const branch = await __privateGet(this, _options).branch();
3839
+ const branch = __privateGet(this, _options).branch;
3346
3840
  return { databaseURL, branch };
3347
3841
  }
3348
- }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3842
+ }, _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3349
3843
  const enableBrowser = options?.enableBrowser ?? getEnableBrowserVariable() ?? false;
3350
- const isBrowser = typeof window !== "undefined";
3844
+ const isBrowser = typeof window !== "undefined" && typeof Deno === "undefined";
3351
3845
  if (isBrowser && !enableBrowser) {
3352
3846
  throw new Error(
3353
3847
  "You are trying to use Xata from the browser, which is potentially a non-secure environment. If you understand the security concerns, such as leaking your credentials, pass `enableBrowser: true` to the client options to remove this error."
@@ -3359,60 +3853,71 @@ const buildClient = (plugins) => {
3359
3853
  const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
3360
3854
  const trace = options?.trace ?? defaultTrace;
3361
3855
  const clientName = options?.clientName;
3362
- const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({
3363
- apiKey,
3364
- databaseURL,
3365
- fetchImpl: options?.fetch,
3366
- clientName: options?.clientName
3367
- });
3856
+ const host = options?.host ?? "production";
3857
+ const xataAgentExtra = options?.xataAgentExtra;
3368
3858
  if (!apiKey) {
3369
3859
  throw new Error("Option apiKey is required");
3370
3860
  }
3371
3861
  if (!databaseURL) {
3372
3862
  throw new Error("Option databaseURL is required");
3373
3863
  }
3374
- return { fetch, databaseURL, apiKey, branch, cache, trace, clientID: generateUUID(), enableBrowser, clientName };
3375
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
3864
+ const envBranch = getBranch();
3865
+ const previewBranch = getPreviewBranch();
3866
+ const branch = options?.branch || previewBranch || envBranch || "main";
3867
+ if (!!previewBranch && branch !== previewBranch) {
3868
+ console.warn(
3869
+ `Ignoring preview branch ${previewBranch} because branch option was passed to the client constructor with value ${branch}`
3870
+ );
3871
+ } else if (!!envBranch && branch !== envBranch) {
3872
+ console.warn(
3873
+ `Ignoring branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
3874
+ );
3875
+ } else if (!!previewBranch && !!envBranch && previewBranch !== envBranch) {
3876
+ console.warn(
3877
+ `Ignoring preview branch ${previewBranch} and branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
3878
+ );
3879
+ } else if (!previewBranch && !envBranch && options?.branch === void 0) {
3880
+ console.warn(
3881
+ `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.`
3882
+ );
3883
+ }
3884
+ return {
3885
+ fetch,
3886
+ databaseURL,
3887
+ apiKey,
3888
+ branch,
3889
+ cache,
3890
+ trace,
3891
+ host,
3892
+ clientID: generateUUID(),
3893
+ enableBrowser,
3894
+ clientName,
3895
+ xataAgentExtra
3896
+ };
3897
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = function({
3376
3898
  fetch,
3377
3899
  apiKey,
3378
3900
  databaseURL,
3379
3901
  branch,
3380
3902
  trace,
3381
3903
  clientID,
3382
- clientName
3904
+ clientName,
3905
+ xataAgentExtra
3383
3906
  }) {
3384
- const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
3385
- if (!branchValue)
3386
- throw new Error("Unable to resolve branch value");
3387
3907
  return {
3388
- fetchImpl: fetch,
3908
+ fetch,
3389
3909
  apiKey,
3390
3910
  apiUrl: "",
3391
3911
  workspacesApiUrl: (path, params) => {
3392
3912
  const hasBranch = params.dbBranchName ?? params.branch;
3393
- const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branchValue}` : "");
3913
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branch}` : "");
3394
3914
  return databaseURL + newPath;
3395
3915
  },
3396
3916
  trace,
3397
3917
  clientID,
3398
- clientName
3399
- };
3400
- }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
3401
- if (__privateGet(this, _branch))
3402
- return __privateGet(this, _branch);
3403
- if (param === void 0)
3404
- return void 0;
3405
- const strategies = Array.isArray(param) ? [...param] : [param];
3406
- const evaluateBranch = async (strategy) => {
3407
- return isBranchStrategyBuilder(strategy) ? await strategy() : strategy;
3918
+ clientName,
3919
+ xataAgentExtra
3408
3920
  };
3409
- for await (const strategy of strategies) {
3410
- const branch = await evaluateBranch(strategy);
3411
- if (branch) {
3412
- __privateSet(this, _branch, branch);
3413
- return branch;
3414
- }
3415
- }
3416
3921
  }, _a;
3417
3922
  };
3418
3923
  class BaseClient extends buildClient() {
@@ -3507,5 +4012,5 @@ class XataError extends Error {
3507
4012
  }
3508
4013
  }
3509
4014
 
3510
- export { BaseClient, 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, dEPRECATEDcreateDatabase, dEPRECATEDdeleteDatabase, dEPRECATEDgetDatabaseList, dEPRECATEDgetDatabaseMetadata, dEPRECATEDupdateDatabaseMetadata, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, deserialize, endsWith, equals, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchSchemaHistory, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, 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, updateDatabaseMetadata, updateMigrationRequest, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID };
4015
+ 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, deleteFileItem, 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, getFile, getFileItem, 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, putFile, putFileItem, queryMigrationRequests, queryTable, removeGitBranchesEntry, removeWorkspaceMember, renameDatabase, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, serialize, setTableSchema, sqlQuery, startsWith, summarizeTable, updateBranchMetadata, updateBranchSchema, updateColumn, updateDatabaseGithubSettings, updateDatabaseMetadata, updateMigrationRequest, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID, vectorSearchTable };
3511
4016
  //# sourceMappingURL=index.mjs.map