@xata.io/client 0.0.0-alpha.vff52a72 → 0.0.0-alpha.vff9649a

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
@@ -1,5 +1,6 @@
1
- const defaultTrace = async (_name, fn, _options) => {
1
+ const defaultTrace = async (name, fn, _options) => {
2
2
  return await fn({
3
+ name,
3
4
  setAttributes: () => {
4
5
  return;
5
6
  }
@@ -41,6 +42,18 @@ function isStringArray(value) {
41
42
  function isNumber(value) {
42
43
  return isDefined(value) && typeof value === "number";
43
44
  }
45
+ function parseNumber(value) {
46
+ if (isNumber(value)) {
47
+ return value;
48
+ }
49
+ if (isString(value)) {
50
+ const parsed = Number(value);
51
+ if (!Number.isNaN(parsed)) {
52
+ return parsed;
53
+ }
54
+ }
55
+ return void 0;
56
+ }
44
57
  function toBase64(value) {
45
58
  try {
46
59
  return btoa(value);
@@ -60,10 +73,20 @@ function deepMerge(a, b) {
60
73
  }
61
74
  return result;
62
75
  }
76
+ function chunk(array, chunkSize) {
77
+ const result = [];
78
+ for (let i = 0; i < array.length; i += chunkSize) {
79
+ result.push(array.slice(i, i + chunkSize));
80
+ }
81
+ return result;
82
+ }
83
+ async function timeout(ms) {
84
+ return new Promise((resolve) => setTimeout(resolve, ms));
85
+ }
63
86
 
64
87
  function getEnvironment() {
65
88
  try {
66
- if (isObject(process) && isObject(process.env)) {
89
+ if (isDefined(process) && isDefined(process.env)) {
67
90
  return {
68
91
  apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
69
92
  databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
@@ -94,6 +117,25 @@ function getEnvironment() {
94
117
  fallbackBranch: getGlobalFallbackBranch()
95
118
  };
96
119
  }
120
+ function getEnableBrowserVariable() {
121
+ try {
122
+ if (isObject(process) && isObject(process.env) && process.env.XATA_ENABLE_BROWSER !== void 0) {
123
+ return process.env.XATA_ENABLE_BROWSER === "true";
124
+ }
125
+ } catch (err) {
126
+ }
127
+ try {
128
+ if (isObject(Deno) && isObject(Deno.env) && Deno.env.get("XATA_ENABLE_BROWSER") !== void 0) {
129
+ return Deno.env.get("XATA_ENABLE_BROWSER") === "true";
130
+ }
131
+ } catch (err) {
132
+ }
133
+ try {
134
+ return XATA_ENABLE_BROWSER === true || XATA_ENABLE_BROWSER === "true";
135
+ } catch (err) {
136
+ return void 0;
137
+ }
138
+ }
97
139
  function getGlobalApiKey() {
98
140
  try {
99
141
  return XATA_API_KEY;
@@ -128,9 +170,6 @@ async function getGitBranch() {
128
170
  const nodeModule = ["child", "process"].join("_");
129
171
  const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
130
172
  try {
131
- if (typeof require === "function") {
132
- return require(nodeModule).execSync(fullCmd, execOptions).trim();
133
- }
134
173
  const { execSync } = await import(nodeModule);
135
174
  return execSync(fullCmd, execOptions).toString().trim();
136
175
  } catch (err) {
@@ -153,6 +192,29 @@ function getAPIKey() {
153
192
  }
154
193
  }
155
194
 
195
+ var __accessCheck$8 = (obj, member, msg) => {
196
+ if (!member.has(obj))
197
+ throw TypeError("Cannot " + msg);
198
+ };
199
+ var __privateGet$8 = (obj, member, getter) => {
200
+ __accessCheck$8(obj, member, "read from private field");
201
+ return getter ? getter.call(obj) : member.get(obj);
202
+ };
203
+ var __privateAdd$8 = (obj, member, value) => {
204
+ if (member.has(obj))
205
+ throw TypeError("Cannot add the same private member more than once");
206
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
207
+ };
208
+ var __privateSet$8 = (obj, member, value, setter) => {
209
+ __accessCheck$8(obj, member, "write to private field");
210
+ setter ? setter.call(obj, value) : member.set(obj, value);
211
+ return value;
212
+ };
213
+ var __privateMethod$4 = (obj, member, method) => {
214
+ __accessCheck$8(obj, member, "access private method");
215
+ return method;
216
+ };
217
+ var _fetch, _queue, _concurrency, _enqueue, enqueue_fn;
156
218
  function getFetchImplementation(userFetch) {
157
219
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
158
220
  const fetchImpl = userFetch ?? globalFetch;
@@ -163,8 +225,81 @@ function getFetchImplementation(userFetch) {
163
225
  }
164
226
  return fetchImpl;
165
227
  }
228
+ class ApiRequestPool {
229
+ constructor(concurrency = 10) {
230
+ __privateAdd$8(this, _enqueue);
231
+ __privateAdd$8(this, _fetch, void 0);
232
+ __privateAdd$8(this, _queue, void 0);
233
+ __privateAdd$8(this, _concurrency, void 0);
234
+ __privateSet$8(this, _queue, []);
235
+ __privateSet$8(this, _concurrency, concurrency);
236
+ this.running = 0;
237
+ this.started = 0;
238
+ }
239
+ setFetch(fetch2) {
240
+ __privateSet$8(this, _fetch, fetch2);
241
+ }
242
+ getFetch() {
243
+ if (!__privateGet$8(this, _fetch)) {
244
+ throw new Error("Fetch not set");
245
+ }
246
+ return __privateGet$8(this, _fetch);
247
+ }
248
+ request(url, options) {
249
+ const start = new Date();
250
+ const fetch2 = this.getFetch();
251
+ const runRequest = async (stalled = false) => {
252
+ const response = await fetch2(url, options);
253
+ if (response.status === 429) {
254
+ const rateLimitReset = parseNumber(response.headers?.get("x-ratelimit-reset")) ?? 1;
255
+ await timeout(rateLimitReset * 1e3);
256
+ return await runRequest(true);
257
+ }
258
+ if (stalled) {
259
+ const stalledTime = new Date().getTime() - start.getTime();
260
+ console.warn(`A request to Xata hit your workspace limits, was retried and stalled for ${stalledTime}ms`);
261
+ }
262
+ return response;
263
+ };
264
+ return __privateMethod$4(this, _enqueue, enqueue_fn).call(this, async () => {
265
+ return await runRequest();
266
+ });
267
+ }
268
+ }
269
+ _fetch = new WeakMap();
270
+ _queue = new WeakMap();
271
+ _concurrency = new WeakMap();
272
+ _enqueue = new WeakSet();
273
+ enqueue_fn = function(task) {
274
+ const promise = new Promise((resolve) => __privateGet$8(this, _queue).push(resolve)).finally(() => {
275
+ this.started--;
276
+ this.running++;
277
+ }).then(() => task()).finally(() => {
278
+ this.running--;
279
+ const next = __privateGet$8(this, _queue).shift();
280
+ if (next !== void 0) {
281
+ this.started++;
282
+ next();
283
+ }
284
+ });
285
+ if (this.running + this.started < __privateGet$8(this, _concurrency)) {
286
+ const next = __privateGet$8(this, _queue).shift();
287
+ if (next !== void 0) {
288
+ this.started++;
289
+ next();
290
+ }
291
+ }
292
+ return promise;
293
+ };
166
294
 
167
- const VERSION = "0.0.0-alpha.vff52a72";
295
+ function generateUUID() {
296
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
297
+ const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
298
+ return v.toString(16);
299
+ });
300
+ }
301
+
302
+ const VERSION = "0.21.6";
168
303
 
169
304
  class ErrorWithCause extends Error {
170
305
  constructor(message, options) {
@@ -175,7 +310,7 @@ class FetcherError extends ErrorWithCause {
175
310
  constructor(status, data, requestId) {
176
311
  super(getMessage(data));
177
312
  this.status = status;
178
- this.errors = isBulkError(data) ? data.errors : void 0;
313
+ this.errors = isBulkError(data) ? data.errors : [{ message: getMessage(data), status }];
179
314
  this.requestId = requestId;
180
315
  if (data instanceof Error) {
181
316
  this.stack = data.stack;
@@ -207,6 +342,7 @@ function getMessage(data) {
207
342
  }
208
343
  }
209
344
 
345
+ const pool = new ApiRequestPool();
210
346
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
211
347
  const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
212
348
  if (value === void 0 || value === null)
@@ -239,11 +375,12 @@ function hostHeader(url) {
239
375
  const { groups } = pattern.exec(url) ?? {};
240
376
  return groups?.host ? { Host: groups.host } : {};
241
377
  }
378
+ const defaultClientID = generateUUID();
242
379
  async function fetch$1({
243
380
  url: path,
244
381
  method,
245
382
  body,
246
- headers,
383
+ headers: customHeaders,
247
384
  pathParams,
248
385
  queryParams,
249
386
  fetchImpl,
@@ -254,9 +391,12 @@ async function fetch$1({
254
391
  trace,
255
392
  signal,
256
393
  clientID,
257
- sessionID
394
+ sessionID,
395
+ clientName,
396
+ fetchOptions = {}
258
397
  }) {
259
- return trace(
398
+ pool.setFetch(fetchImpl);
399
+ return await trace(
260
400
  `${method.toUpperCase()} ${path}`,
261
401
  async ({ setAttributes }) => {
262
402
  const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
@@ -266,23 +406,28 @@ async function fetch$1({
266
406
  [TraceAttributes.HTTP_URL]: url,
267
407
  [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
268
408
  });
269
- const response = await fetchImpl(url, {
409
+ const xataAgent = compact([
410
+ ["client", "TS_SDK"],
411
+ ["version", VERSION],
412
+ isDefined(clientName) ? ["service", clientName] : void 0
413
+ ]).map(([key, value]) => `${key}=${value}`).join("; ");
414
+ const headers = {
415
+ "Accept-Encoding": "identity",
416
+ "Content-Type": "application/json",
417
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
418
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
419
+ "X-Xata-Agent": xataAgent,
420
+ ...customHeaders,
421
+ ...hostHeader(fullUrl),
422
+ Authorization: `Bearer ${apiKey}`
423
+ };
424
+ const response = await pool.request(url, {
425
+ ...fetchOptions,
270
426
  method: method.toUpperCase(),
271
427
  body: body ? JSON.stringify(body) : void 0,
272
- headers: {
273
- "Content-Type": "application/json",
274
- "User-Agent": `Xata client-ts/${VERSION}`,
275
- "X-Xata-Client-ID": clientID ?? "",
276
- "X-Xata-Session-ID": sessionID ?? "",
277
- ...headers,
278
- ...hostHeader(fullUrl),
279
- Authorization: `Bearer ${apiKey}`
280
- },
428
+ headers,
281
429
  signal
282
430
  });
283
- if (response.status === 204) {
284
- return {};
285
- }
286
431
  const { host, protocol } = parseUrl(response.url);
287
432
  const requestId = response.headers?.get("x-request-id") ?? void 0;
288
433
  setAttributes({
@@ -292,6 +437,12 @@ async function fetch$1({
292
437
  [TraceAttributes.HTTP_HOST]: host,
293
438
  [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
294
439
  });
440
+ if (response.status === 204) {
441
+ return {};
442
+ }
443
+ if (response.status === 429) {
444
+ throw new FetcherError(response.status, "Rate limit exceeded", requestId);
445
+ }
295
446
  try {
296
447
  const jsonResponse = await response.json();
297
448
  if (response.ok) {
@@ -316,17 +467,12 @@ function parseUrl(url) {
316
467
 
317
468
  const dataPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "dataPlane" });
318
469
 
319
- const dEPRECATEDgetDatabaseList = (variables, signal) => dataPlaneFetch({ url: "/dbs", method: "get", ...variables, signal });
320
470
  const getBranchList = (variables, signal) => dataPlaneFetch({
321
471
  url: "/dbs/{dbName}",
322
472
  method: "get",
323
473
  ...variables,
324
474
  signal
325
475
  });
326
- const dEPRECATEDcreateDatabase = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}", method: "put", ...variables, signal });
327
- const dEPRECATEDdeleteDatabase = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}", method: "delete", ...variables, signal });
328
- const dEPRECATEDgetDatabaseMetadata = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/metadata", method: "get", ...variables, signal });
329
- const dEPRECATEDupdateDatabaseMetadata = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/metadata", method: "patch", ...variables, signal });
330
476
  const getBranchDetails = (variables, signal) => dataPlaneFetch({
331
477
  url: "/db/{dbBranchName}",
332
478
  method: "get",
@@ -365,6 +511,7 @@ const resolveBranch = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName
365
511
  const getBranchMigrationHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables, signal });
366
512
  const getBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables, signal });
367
513
  const executeBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables, signal });
514
+ const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
368
515
  const queryMigrationRequests = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/query", method: "post", ...variables, signal });
369
516
  const createMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations", method: "post", ...variables, signal });
370
517
  const getMigrationRequest = (variables, signal) => dataPlaneFetch({
@@ -464,13 +611,6 @@ const searchTable = (variables, signal) => dataPlaneFetch({
464
611
  const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
465
612
  const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
466
613
  const operationsByTag$2 = {
467
- database: {
468
- dEPRECATEDgetDatabaseList,
469
- dEPRECATEDcreateDatabase,
470
- dEPRECATEDdeleteDatabase,
471
- dEPRECATEDgetDatabaseMetadata,
472
- dEPRECATEDupdateDatabaseMetadata
473
- },
474
614
  branch: {
475
615
  getBranchList,
476
616
  getBranchDetails,
@@ -495,6 +635,16 @@ const operationsByTag$2 = {
495
635
  previewBranchSchemaEdit,
496
636
  applyBranchSchemaEdit
497
637
  },
638
+ records: {
639
+ branchTransaction,
640
+ insertRecord,
641
+ getRecord,
642
+ insertRecordWithID,
643
+ updateRecordWithID,
644
+ upsertRecordWithID,
645
+ deleteRecord,
646
+ bulkInsertTableRecords
647
+ },
498
648
  migrationRequests: {
499
649
  queryMigrationRequests,
500
650
  createMigrationRequest,
@@ -517,15 +667,6 @@ const operationsByTag$2 = {
517
667
  updateColumn,
518
668
  deleteColumn
519
669
  },
520
- records: {
521
- insertRecord,
522
- getRecord,
523
- insertRecordWithID,
524
- updateRecordWithID,
525
- upsertRecordWithID,
526
- deleteRecord,
527
- bulkInsertTableRecords
528
- },
529
670
  searchAndFilter: { queryTable, searchBranch, searchTable, summarizeTable, aggregateTable }
530
671
  };
531
672
 
@@ -699,12 +840,12 @@ function parseProviderString(provider = "production") {
699
840
  function parseWorkspacesUrlParts(url) {
700
841
  if (!isString(url))
701
842
  return null;
702
- const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))?\.xata\.sh.*/;
703
- const regexStaging = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))?\.xatabase\.co.*/;
843
+ const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/;
844
+ const regexStaging = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))\.xatabase\.co.*/;
704
845
  const match = url.match(regex) || url.match(regexStaging);
705
846
  if (!match)
706
847
  return null;
707
- return { workspace: match[1], region: match[2] ?? "eu-west-1" };
848
+ return { workspace: match[1], region: match[2] };
708
849
  }
709
850
 
710
851
  var __accessCheck$7 = (obj, member, msg) => {
@@ -733,6 +874,7 @@ class XataApiClient {
733
874
  const provider = options.host ?? "production";
734
875
  const apiKey = options.apiKey ?? getAPIKey();
735
876
  const trace = options.trace ?? defaultTrace;
877
+ const clientID = generateUUID();
736
878
  if (!apiKey) {
737
879
  throw new Error("Could not resolve a valid apiKey");
738
880
  }
@@ -741,7 +883,9 @@ class XataApiClient {
741
883
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
742
884
  fetchImpl: getFetchImplementation(options.fetch),
743
885
  apiKey,
744
- trace
886
+ trace,
887
+ clientName: options.clientName,
888
+ clientID
745
889
  });
746
890
  }
747
891
  get user() {
@@ -1343,6 +1487,19 @@ class RecordsApi {
1343
1487
  ...this.extraProps
1344
1488
  });
1345
1489
  }
1490
+ branchTransaction({
1491
+ workspace,
1492
+ region,
1493
+ database,
1494
+ branch,
1495
+ operations
1496
+ }) {
1497
+ return operationsByTag.records.branchTransaction({
1498
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1499
+ body: { operations },
1500
+ ...this.extraProps
1501
+ });
1502
+ }
1346
1503
  }
1347
1504
  class SearchAndFilterApi {
1348
1505
  constructor(extraProps) {
@@ -1357,11 +1514,12 @@ class SearchAndFilterApi {
1357
1514
  filter,
1358
1515
  sort,
1359
1516
  page,
1360
- columns
1517
+ columns,
1518
+ consistency
1361
1519
  }) {
1362
1520
  return operationsByTag.searchAndFilter.queryTable({
1363
1521
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1364
- body: { filter, sort, page, columns },
1522
+ body: { filter, sort, page, columns, consistency },
1365
1523
  ...this.extraProps
1366
1524
  });
1367
1525
  }
@@ -1413,11 +1571,12 @@ class SearchAndFilterApi {
1413
1571
  summaries,
1414
1572
  sort,
1415
1573
  summariesFilter,
1416
- page
1574
+ page,
1575
+ consistency
1417
1576
  }) {
1418
1577
  return operationsByTag.searchAndFilter.summarizeTable({
1419
1578
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1420
- body: { filter, columns, summaries, sort, summariesFilter, page },
1579
+ body: { filter, columns, summaries, sort, summariesFilter, page, consistency },
1421
1580
  ...this.extraProps
1422
1581
  });
1423
1582
  }
@@ -1731,13 +1890,6 @@ class XataApiPlugin {
1731
1890
  class XataPlugin {
1732
1891
  }
1733
1892
 
1734
- function generateUUID() {
1735
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
1736
- const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
1737
- return v.toString(16);
1738
- });
1739
- }
1740
-
1741
1893
  function cleanFilter(filter) {
1742
1894
  if (!filter)
1743
1895
  return void 0;
@@ -1777,11 +1929,11 @@ class Page {
1777
1929
  async previousPage(size, offset) {
1778
1930
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
1779
1931
  }
1780
- async firstPage(size, offset) {
1781
- return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
1932
+ async startPage(size, offset) {
1933
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, start: this.meta.page.cursor } });
1782
1934
  }
1783
- async lastPage(size, offset) {
1784
- return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
1935
+ async endPage(size, offset) {
1936
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, end: this.meta.page.cursor } });
1785
1937
  }
1786
1938
  hasNextPage() {
1787
1939
  return this.meta.page.more;
@@ -1793,7 +1945,7 @@ const PAGINATION_DEFAULT_SIZE = 20;
1793
1945
  const PAGINATION_MAX_OFFSET = 800;
1794
1946
  const PAGINATION_DEFAULT_OFFSET = 0;
1795
1947
  function isCursorPaginationOptions(options) {
1796
- return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
1948
+ return isDefined(options) && (isDefined(options.start) || isDefined(options.end) || isDefined(options.after) || isDefined(options.before));
1797
1949
  }
1798
1950
  const _RecordArray = class extends Array {
1799
1951
  constructor(...args) {
@@ -1825,12 +1977,12 @@ const _RecordArray = class extends Array {
1825
1977
  const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1826
1978
  return new _RecordArray(newPage);
1827
1979
  }
1828
- async firstPage(size, offset) {
1829
- const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1980
+ async startPage(size, offset) {
1981
+ const newPage = await __privateGet$6(this, _page).startPage(size, offset);
1830
1982
  return new _RecordArray(newPage);
1831
1983
  }
1832
- async lastPage(size, offset) {
1833
- const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1984
+ async endPage(size, offset) {
1985
+ const newPage = await __privateGet$6(this, _page).endPage(size, offset);
1834
1986
  return new _RecordArray(newPage);
1835
1987
  }
1836
1988
  hasNextPage() {
@@ -1885,8 +2037,10 @@ const _Query = class {
1885
2037
  __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1886
2038
  __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1887
2039
  __privateGet$5(this, _data).columns = data.columns ?? parent?.columns;
2040
+ __privateGet$5(this, _data).consistency = data.consistency ?? parent?.consistency;
1888
2041
  __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1889
2042
  __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
2043
+ __privateGet$5(this, _data).fetchOptions = data.fetchOptions ?? parent?.fetchOptions;
1890
2044
  this.any = this.any.bind(this);
1891
2045
  this.all = this.all.bind(this);
1892
2046
  this.not = this.not.bind(this);
@@ -2014,15 +2168,15 @@ const _Query = class {
2014
2168
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
2015
2169
  }
2016
2170
  nextPage(size, offset) {
2017
- return this.firstPage(size, offset);
2171
+ return this.startPage(size, offset);
2018
2172
  }
2019
2173
  previousPage(size, offset) {
2020
- return this.firstPage(size, offset);
2174
+ return this.startPage(size, offset);
2021
2175
  }
2022
- firstPage(size, offset) {
2176
+ startPage(size, offset) {
2023
2177
  return this.getPaginated({ pagination: { size, offset } });
2024
2178
  }
2025
- lastPage(size, offset) {
2179
+ endPage(size, offset) {
2026
2180
  return this.getPaginated({ pagination: { size, offset, before: "end" } });
2027
2181
  }
2028
2182
  hasNextPage() {
@@ -2105,7 +2259,8 @@ var __privateMethod$2 = (obj, member, method) => {
2105
2259
  __accessCheck$4(obj, member, "access private method");
2106
2260
  return method;
2107
2261
  };
2108
- var _table, _getFetchProps, _db, _cache, _schemaTables$2, _trace, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaTables$1, getSchemaTables_fn$1;
2262
+ var _table, _getFetchProps, _db, _cache, _schemaTables$2, _trace, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _insertRecords, insertRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _updateRecords, updateRecords_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _deleteRecords, deleteRecords_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaTables$1, getSchemaTables_fn$1;
2263
+ const BULK_OPERATION_MAX_SIZE = 1e3;
2109
2264
  class Repository extends Query {
2110
2265
  }
2111
2266
  class RestRepository extends Query {
@@ -2117,10 +2272,12 @@ class RestRepository extends Query {
2117
2272
  );
2118
2273
  __privateAdd$4(this, _insertRecordWithoutId);
2119
2274
  __privateAdd$4(this, _insertRecordWithId);
2120
- __privateAdd$4(this, _bulkInsertTableRecords);
2275
+ __privateAdd$4(this, _insertRecords);
2121
2276
  __privateAdd$4(this, _updateRecordWithID);
2277
+ __privateAdd$4(this, _updateRecords);
2122
2278
  __privateAdd$4(this, _upsertRecordWithID);
2123
2279
  __privateAdd$4(this, _deleteRecord);
2280
+ __privateAdd$4(this, _deleteRecords);
2124
2281
  __privateAdd$4(this, _setCacheQuery);
2125
2282
  __privateAdd$4(this, _getCacheQuery);
2126
2283
  __privateAdd$4(this, _getSchemaTables$1);
@@ -2154,20 +2311,22 @@ class RestRepository extends Query {
2154
2311
  if (Array.isArray(a)) {
2155
2312
  if (a.length === 0)
2156
2313
  return [];
2157
- const columns = isStringArray(b) ? b : void 0;
2158
- return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
2314
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: true });
2315
+ const columns = isStringArray(b) ? b : ["*"];
2316
+ const result = await this.read(ids, columns);
2317
+ return result;
2159
2318
  }
2160
2319
  if (isString(a) && isObject(b)) {
2161
2320
  if (a === "")
2162
2321
  throw new Error("The id can't be empty");
2163
2322
  const columns = isStringArray(c) ? c : void 0;
2164
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
2323
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
2165
2324
  }
2166
2325
  if (isObject(a) && isString(a.id)) {
2167
2326
  if (a.id === "")
2168
2327
  throw new Error("The id can't be empty");
2169
2328
  const columns = isStringArray(b) ? b : void 0;
2170
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
2329
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
2171
2330
  }
2172
2331
  if (isObject(a)) {
2173
2332
  const columns = isStringArray(b) ? b : void 0;
@@ -2242,19 +2401,29 @@ class RestRepository extends Query {
2242
2401
  if (Array.isArray(a)) {
2243
2402
  if (a.length === 0)
2244
2403
  return [];
2245
- if (a.length > 100) {
2246
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
2247
- }
2404
+ const existing = await this.read(a, ["id"]);
2405
+ const updates = a.filter((_item, index) => existing[index] !== null);
2406
+ await __privateMethod$2(this, _updateRecords, updateRecords_fn).call(this, updates, {
2407
+ ifVersion,
2408
+ upsert: false
2409
+ });
2248
2410
  const columns = isStringArray(b) ? b : ["*"];
2249
- return Promise.all(a.map((object) => this.update(object, columns)));
2250
- }
2251
- if (isString(a) && isObject(b)) {
2252
- const columns = isStringArray(c) ? c : void 0;
2253
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2411
+ const result = await this.read(a, columns);
2412
+ return result;
2254
2413
  }
2255
- if (isObject(a) && isString(a.id)) {
2256
- const columns = isStringArray(b) ? b : void 0;
2257
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
2414
+ try {
2415
+ if (isString(a) && isObject(b)) {
2416
+ const columns = isStringArray(c) ? c : void 0;
2417
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2418
+ }
2419
+ if (isObject(a) && isString(a.id)) {
2420
+ const columns = isStringArray(b) ? b : void 0;
2421
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
2422
+ }
2423
+ } catch (error) {
2424
+ if (error.status === 422)
2425
+ return null;
2426
+ throw error;
2258
2427
  }
2259
2428
  throw new Error("Invalid arguments for update method");
2260
2429
  });
@@ -2284,11 +2453,13 @@ class RestRepository extends Query {
2284
2453
  if (Array.isArray(a)) {
2285
2454
  if (a.length === 0)
2286
2455
  return [];
2287
- if (a.length > 100) {
2288
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
2289
- }
2456
+ await __privateMethod$2(this, _updateRecords, updateRecords_fn).call(this, a, {
2457
+ ifVersion,
2458
+ upsert: true
2459
+ });
2290
2460
  const columns = isStringArray(b) ? b : ["*"];
2291
- return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
2461
+ const result = await this.read(a, columns);
2462
+ return result;
2292
2463
  }
2293
2464
  if (isString(a) && isObject(b)) {
2294
2465
  const columns = isStringArray(c) ? c : void 0;
@@ -2307,8 +2478,10 @@ class RestRepository extends Query {
2307
2478
  if (Array.isArray(a)) {
2308
2479
  if (a.length === 0)
2309
2480
  return [];
2481
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: false });
2310
2482
  const columns = isStringArray(b) ? b : ["*"];
2311
- return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
2483
+ const result = await this.read(ids, columns);
2484
+ return result;
2312
2485
  }
2313
2486
  if (isString(a) && isObject(b)) {
2314
2487
  const columns = isStringArray(c) ? c : void 0;
@@ -2326,10 +2499,17 @@ class RestRepository extends Query {
2326
2499
  if (Array.isArray(a)) {
2327
2500
  if (a.length === 0)
2328
2501
  return [];
2329
- if (a.length > 100) {
2330
- console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
2331
- }
2332
- return Promise.all(a.map((id) => this.delete(id, b)));
2502
+ const ids = a.map((o) => {
2503
+ if (isString(o))
2504
+ return o;
2505
+ if (isString(o.id))
2506
+ return o.id;
2507
+ throw new Error("Invalid arguments for delete method");
2508
+ });
2509
+ const columns = isStringArray(b) ? b : ["*"];
2510
+ const result = await this.read(a, columns);
2511
+ await __privateMethod$2(this, _deleteRecords, deleteRecords_fn).call(this, ids);
2512
+ return result;
2333
2513
  }
2334
2514
  if (isString(a)) {
2335
2515
  return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
@@ -2374,7 +2554,9 @@ class RestRepository extends Query {
2374
2554
  prefix: options.prefix,
2375
2555
  highlight: options.highlight,
2376
2556
  filter: options.filter,
2377
- boosters: options.boosters
2557
+ boosters: options.boosters,
2558
+ page: options.page,
2559
+ target: options.target
2378
2560
  },
2379
2561
  ...fetchProps
2380
2562
  });
@@ -2416,8 +2598,10 @@ class RestRepository extends Query {
2416
2598
  filter: cleanFilter(data.filter),
2417
2599
  sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2418
2600
  page: data.pagination,
2419
- columns: data.columns ?? ["*"]
2601
+ columns: data.columns ?? ["*"],
2602
+ consistency: data.consistency
2420
2603
  },
2604
+ fetchOptions: data.fetchOptions,
2421
2605
  ...fetchProps
2422
2606
  });
2423
2607
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
@@ -2443,6 +2627,7 @@ class RestRepository extends Query {
2443
2627
  filter: cleanFilter(data.filter),
2444
2628
  sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2445
2629
  columns: data.columns,
2630
+ consistency: data.consistency,
2446
2631
  page: data.pagination?.size !== void 0 ? { size: data.pagination?.size } : void 0,
2447
2632
  summaries,
2448
2633
  summariesFilter
@@ -2496,31 +2681,40 @@ insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { crea
2496
2681
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2497
2682
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2498
2683
  };
2499
- _bulkInsertTableRecords = new WeakSet();
2500
- bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
2684
+ _insertRecords = new WeakSet();
2685
+ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2501
2686
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2502
- const records = objects.map((object) => transformObjectLinks(object));
2503
- const response = await bulkInsertTableRecords({
2504
- pathParams: {
2505
- workspace: "{workspaceId}",
2506
- dbBranchName: "{dbBranch}",
2507
- region: "{region}",
2508
- tableName: __privateGet$4(this, _table)
2509
- },
2510
- queryParams: { columns },
2511
- body: { records },
2512
- ...fetchProps
2513
- });
2514
- if (!isResponseWithRecords(response)) {
2515
- throw new Error("Request included columns but server didn't include them");
2687
+ const chunkedOperations = chunk(
2688
+ objects.map((object) => ({
2689
+ insert: { table: __privateGet$4(this, _table), record: transformObjectLinks(object), createOnly, ifVersion }
2690
+ })),
2691
+ BULK_OPERATION_MAX_SIZE
2692
+ );
2693
+ const ids = [];
2694
+ for (const operations of chunkedOperations) {
2695
+ const { results } = await branchTransaction({
2696
+ pathParams: {
2697
+ workspace: "{workspaceId}",
2698
+ dbBranchName: "{dbBranch}",
2699
+ region: "{region}"
2700
+ },
2701
+ body: { operations },
2702
+ ...fetchProps
2703
+ });
2704
+ for (const result of results) {
2705
+ if (result.operation === "insert") {
2706
+ ids.push(result.id);
2707
+ } else {
2708
+ ids.push(null);
2709
+ }
2710
+ }
2516
2711
  }
2517
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2518
- return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, columns));
2712
+ return ids;
2519
2713
  };
2520
2714
  _updateRecordWithID = new WeakSet();
2521
2715
  updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2522
2716
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2523
- const record = transformObjectLinks(object);
2717
+ const { id: _id, ...record } = transformObjectLinks(object);
2524
2718
  try {
2525
2719
  const response = await updateRecordWithID({
2526
2720
  pathParams: {
@@ -2543,6 +2737,36 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2543
2737
  throw e;
2544
2738
  }
2545
2739
  };
2740
+ _updateRecords = new WeakSet();
2741
+ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2742
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2743
+ const chunkedOperations = chunk(
2744
+ objects.map(({ id, ...object }) => ({
2745
+ update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields: transformObjectLinks(object) }
2746
+ })),
2747
+ BULK_OPERATION_MAX_SIZE
2748
+ );
2749
+ const ids = [];
2750
+ for (const operations of chunkedOperations) {
2751
+ const { results } = await branchTransaction({
2752
+ pathParams: {
2753
+ workspace: "{workspaceId}",
2754
+ dbBranchName: "{dbBranch}",
2755
+ region: "{region}"
2756
+ },
2757
+ body: { operations },
2758
+ ...fetchProps
2759
+ });
2760
+ for (const result of results) {
2761
+ if (result.operation === "update") {
2762
+ ids.push(result.id);
2763
+ } else {
2764
+ ids.push(null);
2765
+ }
2766
+ }
2767
+ }
2768
+ return ids;
2769
+ };
2546
2770
  _upsertRecordWithID = new WeakSet();
2547
2771
  upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2548
2772
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
@@ -2585,6 +2809,25 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2585
2809
  throw e;
2586
2810
  }
2587
2811
  };
2812
+ _deleteRecords = new WeakSet();
2813
+ deleteRecords_fn = async function(recordIds) {
2814
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2815
+ const chunkedOperations = chunk(
2816
+ recordIds.map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
2817
+ BULK_OPERATION_MAX_SIZE
2818
+ );
2819
+ for (const operations of chunkedOperations) {
2820
+ await branchTransaction({
2821
+ pathParams: {
2822
+ workspace: "{workspaceId}",
2823
+ dbBranchName: "{dbBranch}",
2824
+ region: "{region}"
2825
+ },
2826
+ body: { operations },
2827
+ ...fetchProps
2828
+ });
2829
+ }
2830
+ };
2588
2831
  _setCacheQuery = new WeakSet();
2589
2832
  setCacheQuery_fn = async function(query, meta, records) {
2590
2833
  await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
@@ -2621,23 +2864,23 @@ const transformObjectLinks = (object) => {
2621
2864
  }, {});
2622
2865
  };
2623
2866
  const initObject = (db, schemaTables, table, object, selectedColumns) => {
2624
- const result = {};
2867
+ const data = {};
2625
2868
  const { xata, ...rest } = object ?? {};
2626
- Object.assign(result, rest);
2869
+ Object.assign(data, rest);
2627
2870
  const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
2628
2871
  if (!columns)
2629
2872
  console.error(`Table ${table} not found in schema`);
2630
2873
  for (const column of columns ?? []) {
2631
2874
  if (!isValidColumn(selectedColumns, column))
2632
2875
  continue;
2633
- const value = result[column.name];
2876
+ const value = data[column.name];
2634
2877
  switch (column.type) {
2635
2878
  case "datetime": {
2636
- const date = value !== void 0 ? new Date(value) : void 0;
2637
- if (date && isNaN(date.getTime())) {
2879
+ const date = value !== void 0 ? new Date(value) : null;
2880
+ if (date !== null && isNaN(date.getTime())) {
2638
2881
  console.error(`Failed to parse date ${value} for field ${column.name}`);
2639
- } else if (date) {
2640
- result[column.name] = date;
2882
+ } else {
2883
+ data[column.name] = date;
2641
2884
  }
2642
2885
  break;
2643
2886
  }
@@ -2656,48 +2899,46 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
2656
2899
  }
2657
2900
  return acc;
2658
2901
  }, []);
2659
- result[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
2902
+ data[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
2660
2903
  } else {
2661
- result[column.name] = null;
2904
+ data[column.name] = null;
2662
2905
  }
2663
2906
  break;
2664
2907
  }
2665
2908
  default:
2666
- result[column.name] = value ?? null;
2909
+ data[column.name] = value ?? null;
2667
2910
  if (column.notNull === true && value === null) {
2668
2911
  console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
2669
2912
  }
2670
2913
  break;
2671
2914
  }
2672
2915
  }
2673
- result.read = function(columns2) {
2674
- return db[table].read(result["id"], columns2);
2916
+ const record = { ...data };
2917
+ record.read = function(columns2) {
2918
+ return db[table].read(record["id"], columns2);
2675
2919
  };
2676
- result.update = function(data, b, c) {
2920
+ record.update = function(data2, b, c) {
2677
2921
  const columns2 = isStringArray(b) ? b : ["*"];
2678
2922
  const ifVersion = parseIfVersion(b, c);
2679
- return db[table].update(result["id"], data, columns2, { ifVersion });
2923
+ return db[table].update(record["id"], data2, columns2, { ifVersion });
2680
2924
  };
2681
- result.replace = function(data, b, c) {
2925
+ record.replace = function(data2, b, c) {
2682
2926
  const columns2 = isStringArray(b) ? b : ["*"];
2683
2927
  const ifVersion = parseIfVersion(b, c);
2684
- return db[table].createOrReplace(result["id"], data, columns2, { ifVersion });
2928
+ return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
2685
2929
  };
2686
- result.delete = function() {
2687
- return db[table].delete(result["id"]);
2930
+ record.delete = function() {
2931
+ return db[table].delete(record["id"]);
2688
2932
  };
2689
- result.getMetadata = function() {
2933
+ record.getMetadata = function() {
2690
2934
  return xata;
2691
2935
  };
2692
- for (const prop of ["read", "update", "delete", "getMetadata"]) {
2693
- Object.defineProperty(result, prop, { enumerable: false });
2936
+ for (const prop of ["read", "update", "replace", "delete", "getMetadata"]) {
2937
+ Object.defineProperty(record, prop, { enumerable: false });
2694
2938
  }
2695
- Object.freeze(result);
2696
- return result;
2939
+ Object.freeze(record);
2940
+ return record;
2697
2941
  };
2698
- function isResponseWithRecords(value) {
2699
- return isObject(value) && Array.isArray(value.records);
2700
- }
2701
2942
  function extractId(value) {
2702
2943
  if (isString(value))
2703
2944
  return value;
@@ -2907,10 +3148,10 @@ _schemaTables = new WeakMap();
2907
3148
  _search = new WeakSet();
2908
3149
  search_fn = async function(query, options, getFetchProps) {
2909
3150
  const fetchProps = await getFetchProps();
2910
- const { tables, fuzziness, highlight, prefix } = options ?? {};
3151
+ const { tables, fuzziness, highlight, prefix, page } = options ?? {};
2911
3152
  const { records } = await searchBranch({
2912
3153
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
2913
- body: { tables, query, fuzziness, prefix, highlight },
3154
+ body: { tables, query, fuzziness, prefix, highlight, page },
2914
3155
  ...fetchProps
2915
3156
  });
2916
3157
  return records;
@@ -2928,18 +3169,30 @@ getSchemaTables_fn = async function(getFetchProps) {
2928
3169
  return schema.tables;
2929
3170
  };
2930
3171
 
3172
+ class TransactionPlugin extends XataPlugin {
3173
+ build({ getFetchProps }) {
3174
+ return {
3175
+ run: async (operations) => {
3176
+ const fetchProps = await getFetchProps();
3177
+ const response = await branchTransaction({
3178
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3179
+ body: { operations },
3180
+ ...fetchProps
3181
+ });
3182
+ return response;
3183
+ }
3184
+ };
3185
+ }
3186
+ }
3187
+
2931
3188
  const isBranchStrategyBuilder = (strategy) => {
2932
3189
  return typeof strategy === "function";
2933
3190
  };
2934
3191
 
2935
3192
  async function getCurrentBranchName(options) {
2936
3193
  const { branch, envBranch } = getEnvironment();
2937
- if (branch) {
2938
- const details = await getDatabaseBranch(branch, options);
2939
- if (details)
2940
- return branch;
2941
- console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
2942
- }
3194
+ if (branch)
3195
+ return branch;
2943
3196
  const gitBranch = envBranch || await getGitBranch();
2944
3197
  return resolveXataBranch(gitBranch, options);
2945
3198
  }
@@ -2971,7 +3224,8 @@ async function resolveXataBranch(gitBranch, options) {
2971
3224
  workspacesApiUrl: `${protocol}//${host}`,
2972
3225
  pathParams: { dbName, workspace, region },
2973
3226
  queryParams: { gitBranch, fallbackBranch },
2974
- trace: defaultTrace
3227
+ trace: defaultTrace,
3228
+ clientName: options?.clientName
2975
3229
  });
2976
3230
  return branch;
2977
3231
  }
@@ -3055,8 +3309,10 @@ const buildClient = (plugins) => {
3055
3309
  };
3056
3310
  const db = new SchemaPlugin(schemaTables).build(pluginOptions);
3057
3311
  const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
3312
+ const transactions = new TransactionPlugin().build(pluginOptions);
3058
3313
  this.db = db;
3059
3314
  this.search = search;
3315
+ this.transactions = transactions;
3060
3316
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
3061
3317
  if (namespace === void 0)
3062
3318
  continue;
@@ -3076,20 +3332,41 @@ const buildClient = (plugins) => {
3076
3332
  return { databaseURL, branch };
3077
3333
  }
3078
3334
  }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3335
+ const enableBrowser = options?.enableBrowser ?? getEnableBrowserVariable() ?? false;
3336
+ const isBrowser = typeof window !== "undefined" && typeof Deno === "undefined";
3337
+ if (isBrowser && !enableBrowser) {
3338
+ throw new Error(
3339
+ "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."
3340
+ );
3341
+ }
3079
3342
  const fetch = getFetchImplementation(options?.fetch);
3080
3343
  const databaseURL = options?.databaseURL || getDatabaseURL();
3081
3344
  const apiKey = options?.apiKey || getAPIKey();
3082
3345
  const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
3083
3346
  const trace = options?.trace ?? defaultTrace;
3084
- const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
3347
+ const clientName = options?.clientName;
3348
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({
3349
+ apiKey,
3350
+ databaseURL,
3351
+ fetchImpl: options?.fetch,
3352
+ clientName: options?.clientName
3353
+ });
3085
3354
  if (!apiKey) {
3086
3355
  throw new Error("Option apiKey is required");
3087
3356
  }
3088
3357
  if (!databaseURL) {
3089
3358
  throw new Error("Option databaseURL is required");
3090
3359
  }
3091
- return { fetch, databaseURL, apiKey, branch, cache, trace, clientID: generateUUID() };
3092
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace, clientID }) {
3360
+ return { fetch, databaseURL, apiKey, branch, cache, trace, clientID: generateUUID(), enableBrowser, clientName };
3361
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
3362
+ fetch,
3363
+ apiKey,
3364
+ databaseURL,
3365
+ branch,
3366
+ trace,
3367
+ clientID,
3368
+ clientName
3369
+ }) {
3093
3370
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
3094
3371
  if (!branchValue)
3095
3372
  throw new Error("Unable to resolve branch value");
@@ -3103,7 +3380,8 @@ const buildClient = (plugins) => {
3103
3380
  return databaseURL + newPath;
3104
3381
  },
3105
3382
  trace,
3106
- clientID
3383
+ clientID,
3384
+ clientName
3107
3385
  };
3108
3386
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
3109
3387
  if (__privateGet(this, _branch))
@@ -3194,7 +3472,7 @@ const deserialize = (json) => {
3194
3472
  };
3195
3473
 
3196
3474
  function buildWorkerRunner(config) {
3197
- return function xataWorker(name, _worker) {
3475
+ return function xataWorker(name, worker) {
3198
3476
  return async (...args) => {
3199
3477
  const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
3200
3478
  const result = await fetch(url, {
@@ -3215,5 +3493,5 @@ class XataError extends Error {
3215
3493
  }
3216
3494
  }
3217
3495
 
3218
- 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, 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 };
3496
+ 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, 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 };
3219
3497
  //# sourceMappingURL=index.mjs.map