@xata.io/client 0.0.0-alpha.vfde8eac → 0.0.0-alpha.vfe07d64

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.cjs CHANGED
@@ -1,27 +1,8 @@
1
1
  'use strict';
2
2
 
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- function _interopNamespace(e) {
6
- if (e && e.__esModule) return e;
7
- var n = Object.create(null);
8
- if (e) {
9
- Object.keys(e).forEach(function (k) {
10
- if (k !== 'default') {
11
- var d = Object.getOwnPropertyDescriptor(e, k);
12
- Object.defineProperty(n, k, d.get ? d : {
13
- enumerable: true,
14
- get: function () { return e[k]; }
15
- });
16
- }
17
- });
18
- }
19
- n["default"] = e;
20
- return Object.freeze(n);
21
- }
22
-
23
- const defaultTrace = async (_name, fn, _options) => {
3
+ const defaultTrace = async (name, fn, _options) => {
24
4
  return await fn({
5
+ name,
25
6
  setAttributes: () => {
26
7
  return;
27
8
  }
@@ -63,6 +44,18 @@ function isStringArray(value) {
63
44
  function isNumber(value) {
64
45
  return isDefined(value) && typeof value === "number";
65
46
  }
47
+ function parseNumber(value) {
48
+ if (isNumber(value)) {
49
+ return value;
50
+ }
51
+ if (isString(value)) {
52
+ const parsed = Number(value);
53
+ if (!Number.isNaN(parsed)) {
54
+ return parsed;
55
+ }
56
+ }
57
+ return void 0;
58
+ }
66
59
  function toBase64(value) {
67
60
  try {
68
61
  return btoa(value);
@@ -82,10 +75,20 @@ function deepMerge(a, b) {
82
75
  }
83
76
  return result;
84
77
  }
78
+ function chunk(array, chunkSize) {
79
+ const result = [];
80
+ for (let i = 0; i < array.length; i += chunkSize) {
81
+ result.push(array.slice(i, i + chunkSize));
82
+ }
83
+ return result;
84
+ }
85
+ async function timeout(ms) {
86
+ return new Promise((resolve) => setTimeout(resolve, ms));
87
+ }
85
88
 
86
89
  function getEnvironment() {
87
90
  try {
88
- if (isObject(process) && isObject(process.env)) {
91
+ if (isDefined(process) && isDefined(process.env)) {
89
92
  return {
90
93
  apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
91
94
  databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
@@ -116,6 +119,25 @@ function getEnvironment() {
116
119
  fallbackBranch: getGlobalFallbackBranch()
117
120
  };
118
121
  }
122
+ function getEnableBrowserVariable() {
123
+ try {
124
+ if (isObject(process) && isObject(process.env) && process.env.XATA_ENABLE_BROWSER !== void 0) {
125
+ return process.env.XATA_ENABLE_BROWSER === "true";
126
+ }
127
+ } catch (err) {
128
+ }
129
+ try {
130
+ if (isObject(Deno) && isObject(Deno.env) && Deno.env.get("XATA_ENABLE_BROWSER") !== void 0) {
131
+ return Deno.env.get("XATA_ENABLE_BROWSER") === "true";
132
+ }
133
+ } catch (err) {
134
+ }
135
+ try {
136
+ return XATA_ENABLE_BROWSER === true || XATA_ENABLE_BROWSER === "true";
137
+ } catch (err) {
138
+ return void 0;
139
+ }
140
+ }
119
141
  function getGlobalApiKey() {
120
142
  try {
121
143
  return XATA_API_KEY;
@@ -153,8 +175,6 @@ async function getGitBranch() {
153
175
  if (typeof require === "function") {
154
176
  return require(nodeModule).execSync(fullCmd, execOptions).trim();
155
177
  }
156
- const { execSync } = await (function (t) { return Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require(t)); }); })(nodeModule);
157
- return execSync(fullCmd, execOptions).toString().trim();
158
178
  } catch (err) {
159
179
  }
160
180
  try {
@@ -175,6 +195,29 @@ function getAPIKey() {
175
195
  }
176
196
  }
177
197
 
198
+ var __accessCheck$8 = (obj, member, msg) => {
199
+ if (!member.has(obj))
200
+ throw TypeError("Cannot " + msg);
201
+ };
202
+ var __privateGet$8 = (obj, member, getter) => {
203
+ __accessCheck$8(obj, member, "read from private field");
204
+ return getter ? getter.call(obj) : member.get(obj);
205
+ };
206
+ var __privateAdd$8 = (obj, member, value) => {
207
+ if (member.has(obj))
208
+ throw TypeError("Cannot add the same private member more than once");
209
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
210
+ };
211
+ var __privateSet$8 = (obj, member, value, setter) => {
212
+ __accessCheck$8(obj, member, "write to private field");
213
+ setter ? setter.call(obj, value) : member.set(obj, value);
214
+ return value;
215
+ };
216
+ var __privateMethod$4 = (obj, member, method) => {
217
+ __accessCheck$8(obj, member, "access private method");
218
+ return method;
219
+ };
220
+ var _fetch, _queue, _concurrency, _enqueue, enqueue_fn;
178
221
  function getFetchImplementation(userFetch) {
179
222
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
180
223
  const fetchImpl = userFetch ?? globalFetch;
@@ -185,8 +228,81 @@ function getFetchImplementation(userFetch) {
185
228
  }
186
229
  return fetchImpl;
187
230
  }
231
+ class ApiRequestPool {
232
+ constructor(concurrency = 10) {
233
+ __privateAdd$8(this, _enqueue);
234
+ __privateAdd$8(this, _fetch, void 0);
235
+ __privateAdd$8(this, _queue, void 0);
236
+ __privateAdd$8(this, _concurrency, void 0);
237
+ __privateSet$8(this, _queue, []);
238
+ __privateSet$8(this, _concurrency, concurrency);
239
+ this.running = 0;
240
+ this.started = 0;
241
+ }
242
+ setFetch(fetch2) {
243
+ __privateSet$8(this, _fetch, fetch2);
244
+ }
245
+ getFetch() {
246
+ if (!__privateGet$8(this, _fetch)) {
247
+ throw new Error("Fetch not set");
248
+ }
249
+ return __privateGet$8(this, _fetch);
250
+ }
251
+ request(url, options) {
252
+ const start = new Date();
253
+ const fetch2 = this.getFetch();
254
+ const runRequest = async (stalled = false) => {
255
+ const response = await fetch2(url, options);
256
+ if (response.status === 429) {
257
+ const rateLimitReset = parseNumber(response.headers?.get("x-ratelimit-reset")) ?? 1;
258
+ await timeout(rateLimitReset * 1e3);
259
+ return await runRequest(true);
260
+ }
261
+ if (stalled) {
262
+ const stalledTime = new Date().getTime() - start.getTime();
263
+ console.warn(`A request to Xata hit your workspace limits, was retried and stalled for ${stalledTime}ms`);
264
+ }
265
+ return response;
266
+ };
267
+ return __privateMethod$4(this, _enqueue, enqueue_fn).call(this, async () => {
268
+ return await runRequest();
269
+ });
270
+ }
271
+ }
272
+ _fetch = new WeakMap();
273
+ _queue = new WeakMap();
274
+ _concurrency = new WeakMap();
275
+ _enqueue = new WeakSet();
276
+ enqueue_fn = function(task) {
277
+ const promise = new Promise((resolve) => __privateGet$8(this, _queue).push(resolve)).finally(() => {
278
+ this.started--;
279
+ this.running++;
280
+ }).then(() => task()).finally(() => {
281
+ this.running--;
282
+ const next = __privateGet$8(this, _queue).shift();
283
+ if (next !== void 0) {
284
+ this.started++;
285
+ next();
286
+ }
287
+ });
288
+ if (this.running + this.started < __privateGet$8(this, _concurrency)) {
289
+ const next = __privateGet$8(this, _queue).shift();
290
+ if (next !== void 0) {
291
+ this.started++;
292
+ next();
293
+ }
294
+ }
295
+ return promise;
296
+ };
297
+
298
+ function generateUUID() {
299
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
300
+ const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
301
+ return v.toString(16);
302
+ });
303
+ }
188
304
 
189
- const VERSION = "0.0.0-alpha.vfde8eac";
305
+ const VERSION = "0.22.1";
190
306
 
191
307
  class ErrorWithCause extends Error {
192
308
  constructor(message, options) {
@@ -197,7 +313,7 @@ class FetcherError extends ErrorWithCause {
197
313
  constructor(status, data, requestId) {
198
314
  super(getMessage(data));
199
315
  this.status = status;
200
- this.errors = isBulkError(data) ? data.errors : void 0;
316
+ this.errors = isBulkError(data) ? data.errors : [{ message: getMessage(data), status }];
201
317
  this.requestId = requestId;
202
318
  if (data instanceof Error) {
203
319
  this.stack = data.stack;
@@ -229,6 +345,7 @@ function getMessage(data) {
229
345
  }
230
346
  }
231
347
 
348
+ const pool = new ApiRequestPool();
232
349
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
233
350
  const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
234
351
  if (value === void 0 || value === null)
@@ -261,11 +378,12 @@ function hostHeader(url) {
261
378
  const { groups } = pattern.exec(url) ?? {};
262
379
  return groups?.host ? { Host: groups.host } : {};
263
380
  }
381
+ const defaultClientID = generateUUID();
264
382
  async function fetch$1({
265
383
  url: path,
266
384
  method,
267
385
  body,
268
- headers,
386
+ headers: customHeaders,
269
387
  pathParams,
270
388
  queryParams,
271
389
  fetchImpl,
@@ -276,9 +394,13 @@ async function fetch$1({
276
394
  trace,
277
395
  signal,
278
396
  clientID,
279
- sessionID
397
+ sessionID,
398
+ clientName,
399
+ xataAgentExtra,
400
+ fetchOptions = {}
280
401
  }) {
281
- return trace(
402
+ pool.setFetch(fetchImpl);
403
+ return await trace(
282
404
  `${method.toUpperCase()} ${path}`,
283
405
  async ({ setAttributes }) => {
284
406
  const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
@@ -288,23 +410,29 @@ async function fetch$1({
288
410
  [TraceAttributes.HTTP_URL]: url,
289
411
  [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
290
412
  });
291
- const response = await fetchImpl(url, {
413
+ const xataAgent = compact([
414
+ ["client", "TS_SDK"],
415
+ ["version", VERSION],
416
+ isDefined(clientName) ? ["service", clientName] : void 0,
417
+ ...Object.entries(xataAgentExtra ?? {})
418
+ ]).map(([key, value]) => `${key}=${value}`).join("; ");
419
+ const headers = {
420
+ "Accept-Encoding": "identity",
421
+ "Content-Type": "application/json",
422
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
423
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
424
+ "X-Xata-Agent": xataAgent,
425
+ ...customHeaders,
426
+ ...hostHeader(fullUrl),
427
+ Authorization: `Bearer ${apiKey}`
428
+ };
429
+ const response = await pool.request(url, {
430
+ ...fetchOptions,
292
431
  method: method.toUpperCase(),
293
432
  body: body ? JSON.stringify(body) : void 0,
294
- headers: {
295
- "Content-Type": "application/json",
296
- "User-Agent": `Xata client-ts/${VERSION}`,
297
- "X-Xata-Client-ID": clientID ?? "",
298
- "X-Xata-Session-ID": sessionID ?? "",
299
- ...headers,
300
- ...hostHeader(fullUrl),
301
- Authorization: `Bearer ${apiKey}`
302
- },
433
+ headers,
303
434
  signal
304
435
  });
305
- if (response.status === 204) {
306
- return {};
307
- }
308
436
  const { host, protocol } = parseUrl(response.url);
309
437
  const requestId = response.headers?.get("x-request-id") ?? void 0;
310
438
  setAttributes({
@@ -314,6 +442,12 @@ async function fetch$1({
314
442
  [TraceAttributes.HTTP_HOST]: host,
315
443
  [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
316
444
  });
445
+ if (response.status === 204) {
446
+ return {};
447
+ }
448
+ if (response.status === 429) {
449
+ throw new FetcherError(response.status, "Rate limit exceeded", requestId);
450
+ }
317
451
  try {
318
452
  const jsonResponse = await response.json();
319
453
  if (response.ok) {
@@ -338,32 +472,12 @@ function parseUrl(url) {
338
472
 
339
473
  const dataPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "dataPlane" });
340
474
 
341
- const getDatabaseList = (variables, signal) => dataPlaneFetch({
342
- url: "/dbs",
343
- method: "get",
344
- ...variables,
345
- signal
346
- });
347
475
  const getBranchList = (variables, signal) => dataPlaneFetch({
348
476
  url: "/dbs/{dbName}",
349
477
  method: "get",
350
478
  ...variables,
351
479
  signal
352
480
  });
353
- const createDatabase = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}", method: "put", ...variables, signal });
354
- const deleteDatabase = (variables, signal) => dataPlaneFetch({
355
- url: "/dbs/{dbName}",
356
- method: "delete",
357
- ...variables,
358
- signal
359
- });
360
- const getDatabaseMetadata = (variables, signal) => dataPlaneFetch({
361
- url: "/dbs/{dbName}/metadata",
362
- method: "get",
363
- ...variables,
364
- signal
365
- });
366
- const updateDatabaseMetadata = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/metadata", method: "patch", ...variables, signal });
367
481
  const getBranchDetails = (variables, signal) => dataPlaneFetch({
368
482
  url: "/db/{dbBranchName}",
369
483
  method: "get",
@@ -468,6 +582,7 @@ const deleteColumn = (variables, signal) => dataPlaneFetch({
468
582
  ...variables,
469
583
  signal
470
584
  });
585
+ const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
471
586
  const insertRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
472
587
  const getRecord = (variables, signal) => dataPlaneFetch({
473
588
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
@@ -501,7 +616,6 @@ const searchTable = (variables, signal) => dataPlaneFetch({
501
616
  const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
502
617
  const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
503
618
  const operationsByTag$2 = {
504
- database: { getDatabaseList, createDatabase, deleteDatabase, getDatabaseMetadata, updateDatabaseMetadata },
505
619
  branch: {
506
620
  getBranchList,
507
621
  getBranchDetails,
@@ -549,6 +663,7 @@ const operationsByTag$2 = {
549
663
  deleteColumn
550
664
  },
551
665
  records: {
666
+ branchTransaction,
552
667
  insertRecord,
553
668
  getRecord,
554
669
  insertRecordWithID,
@@ -641,16 +756,24 @@ const updateWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ u
641
756
  const cancelWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "delete", ...variables, signal });
642
757
  const acceptWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept", method: "post", ...variables, signal });
643
758
  const resendWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}/resend", method: "post", ...variables, signal });
644
- const cPGetDatabaseList = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs", method: "get", ...variables, signal });
645
- const cPCreateDatabase = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "put", ...variables, signal });
646
- const cPDeleteDatabase = (variables, signal) => controlPlaneFetch({
759
+ const getDatabaseList = (variables, signal) => controlPlaneFetch({
760
+ url: "/workspaces/{workspaceId}/dbs",
761
+ method: "get",
762
+ ...variables,
763
+ signal
764
+ });
765
+ const createDatabase = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "put", ...variables, signal });
766
+ const deleteDatabase = (variables, signal) => controlPlaneFetch({
647
767
  url: "/workspaces/{workspaceId}/dbs/{dbName}",
648
768
  method: "delete",
649
769
  ...variables,
650
770
  signal
651
771
  });
652
- const cPGetCPDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "get", ...variables, signal });
653
- const cPUpdateCPDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "patch", ...variables, signal });
772
+ const getDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "get", ...variables, signal });
773
+ const updateDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "patch", ...variables, signal });
774
+ const getDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "get", ...variables, signal });
775
+ const updateDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "put", ...variables, signal });
776
+ const deleteDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "delete", ...variables, signal });
654
777
  const listRegions = (variables, signal) => controlPlaneFetch({
655
778
  url: "/workspaces/{workspaceId}/regions",
656
779
  method: "get",
@@ -678,11 +801,14 @@ const operationsByTag$1 = {
678
801
  resendWorkspaceMemberInvite
679
802
  },
680
803
  databases: {
681
- cPGetDatabaseList,
682
- cPCreateDatabase,
683
- cPDeleteDatabase,
684
- cPGetCPDatabaseMetadata,
685
- cPUpdateCPDatabaseMetadata,
804
+ getDatabaseList,
805
+ createDatabase,
806
+ deleteDatabase,
807
+ getDatabaseMetadata,
808
+ updateDatabaseMetadata,
809
+ getDatabaseGithubSettings,
810
+ updateDatabaseGithubSettings,
811
+ deleteDatabaseGithubSettings,
686
812
  listRegions
687
813
  }
688
814
  };
@@ -725,12 +851,13 @@ function parseProviderString(provider = "production") {
725
851
  function parseWorkspacesUrlParts(url) {
726
852
  if (!isString(url))
727
853
  return null;
728
- const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))?\.xata\.sh.*/;
729
- const regexStaging = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))?\.xatabase\.co.*/;
730
- const match = url.match(regex) || url.match(regexStaging);
854
+ const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/;
855
+ const regexStaging = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))\.xatabase\.co.*/;
856
+ const regexDev = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))\.xata\.tech.*/;
857
+ const match = url.match(regex) || url.match(regexStaging) || url.match(regexDev);
731
858
  if (!match)
732
859
  return null;
733
- return { workspace: match[1], region: match[2] ?? "eu-west-1" };
860
+ return { workspace: match[1], region: match[2] };
734
861
  }
735
862
 
736
863
  var __accessCheck$7 = (obj, member, msg) => {
@@ -759,6 +886,7 @@ class XataApiClient {
759
886
  const provider = options.host ?? "production";
760
887
  const apiKey = options.apiKey ?? getAPIKey();
761
888
  const trace = options.trace ?? defaultTrace;
889
+ const clientID = generateUUID();
762
890
  if (!apiKey) {
763
891
  throw new Error("Could not resolve a valid apiKey");
764
892
  }
@@ -767,7 +895,10 @@ class XataApiClient {
767
895
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
768
896
  fetchImpl: getFetchImplementation(options.fetch),
769
897
  apiKey,
770
- trace
898
+ trace,
899
+ clientName: options.clientName,
900
+ xataAgentExtra: options.xataAgentExtra,
901
+ clientID
771
902
  });
772
903
  }
773
904
  get user() {
@@ -1369,6 +1500,19 @@ class RecordsApi {
1369
1500
  ...this.extraProps
1370
1501
  });
1371
1502
  }
1503
+ branchTransaction({
1504
+ workspace,
1505
+ region,
1506
+ database,
1507
+ branch,
1508
+ operations
1509
+ }) {
1510
+ return operationsByTag.records.branchTransaction({
1511
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1512
+ body: { operations },
1513
+ ...this.extraProps
1514
+ });
1515
+ }
1372
1516
  }
1373
1517
  class SearchAndFilterApi {
1374
1518
  constructor(extraProps) {
@@ -1383,11 +1527,12 @@ class SearchAndFilterApi {
1383
1527
  filter,
1384
1528
  sort,
1385
1529
  page,
1386
- columns
1530
+ columns,
1531
+ consistency
1387
1532
  }) {
1388
1533
  return operationsByTag.searchAndFilter.queryTable({
1389
1534
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1390
- body: { filter, sort, page, columns },
1535
+ body: { filter, sort, page, columns, consistency },
1391
1536
  ...this.extraProps
1392
1537
  });
1393
1538
  }
@@ -1439,11 +1584,12 @@ class SearchAndFilterApi {
1439
1584
  summaries,
1440
1585
  sort,
1441
1586
  summariesFilter,
1442
- page
1587
+ page,
1588
+ consistency
1443
1589
  }) {
1444
1590
  return operationsByTag.searchAndFilter.summarizeTable({
1445
1591
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1446
- body: { filter, columns, summaries, sort, summariesFilter, page },
1592
+ body: { filter, columns, summaries, sort, summariesFilter, page, consistency },
1447
1593
  ...this.extraProps
1448
1594
  });
1449
1595
  }
@@ -1627,11 +1773,13 @@ class MigrationsApi {
1627
1773
  region,
1628
1774
  database,
1629
1775
  branch,
1630
- schema
1776
+ schema,
1777
+ schemaOperations,
1778
+ branchOperations
1631
1779
  }) {
1632
1780
  return operationsByTag.migrations.compareBranchWithUserSchema({
1633
1781
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1634
- body: { schema },
1782
+ body: { schema, schemaOperations, branchOperations },
1635
1783
  ...this.extraProps
1636
1784
  });
1637
1785
  }
@@ -1641,11 +1789,12 @@ class MigrationsApi {
1641
1789
  database,
1642
1790
  branch,
1643
1791
  compare,
1644
- schema
1792
+ sourceBranchOperations,
1793
+ targetBranchOperations
1645
1794
  }) {
1646
1795
  return operationsByTag.migrations.compareBranchSchemas({
1647
1796
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, branchName: compare },
1648
- body: { schema },
1797
+ body: { sourceBranchOperations, targetBranchOperations },
1649
1798
  ...this.extraProps
1650
1799
  });
1651
1800
  }
@@ -1694,7 +1843,7 @@ class DatabaseApi {
1694
1843
  this.extraProps = extraProps;
1695
1844
  }
1696
1845
  getDatabaseList({ workspace }) {
1697
- return operationsByTag.databases.cPGetDatabaseList({
1846
+ return operationsByTag.databases.getDatabaseList({
1698
1847
  pathParams: { workspaceId: workspace },
1699
1848
  ...this.extraProps
1700
1849
  });
@@ -1704,7 +1853,7 @@ class DatabaseApi {
1704
1853
  database,
1705
1854
  data
1706
1855
  }) {
1707
- return operationsByTag.databases.cPCreateDatabase({
1856
+ return operationsByTag.databases.createDatabase({
1708
1857
  pathParams: { workspaceId: workspace, dbName: database },
1709
1858
  body: data,
1710
1859
  ...this.extraProps
@@ -1714,7 +1863,7 @@ class DatabaseApi {
1714
1863
  workspace,
1715
1864
  database
1716
1865
  }) {
1717
- return operationsByTag.databases.cPDeleteDatabase({
1866
+ return operationsByTag.databases.deleteDatabase({
1718
1867
  pathParams: { workspaceId: workspace, dbName: database },
1719
1868
  ...this.extraProps
1720
1869
  });
@@ -1723,7 +1872,7 @@ class DatabaseApi {
1723
1872
  workspace,
1724
1873
  database
1725
1874
  }) {
1726
- return operationsByTag.databases.cPGetCPDatabaseMetadata({
1875
+ return operationsByTag.databases.getDatabaseMetadata({
1727
1876
  pathParams: { workspaceId: workspace, dbName: database },
1728
1877
  ...this.extraProps
1729
1878
  });
@@ -1733,12 +1882,41 @@ class DatabaseApi {
1733
1882
  database,
1734
1883
  metadata
1735
1884
  }) {
1736
- return operationsByTag.databases.cPUpdateCPDatabaseMetadata({
1885
+ return operationsByTag.databases.updateDatabaseMetadata({
1737
1886
  pathParams: { workspaceId: workspace, dbName: database },
1738
1887
  body: metadata,
1739
1888
  ...this.extraProps
1740
1889
  });
1741
1890
  }
1891
+ getDatabaseGithubSettings({
1892
+ workspace,
1893
+ database
1894
+ }) {
1895
+ return operationsByTag.databases.getDatabaseGithubSettings({
1896
+ pathParams: { workspaceId: workspace, dbName: database },
1897
+ ...this.extraProps
1898
+ });
1899
+ }
1900
+ updateDatabaseGithubSettings({
1901
+ workspace,
1902
+ database,
1903
+ settings
1904
+ }) {
1905
+ return operationsByTag.databases.updateDatabaseGithubSettings({
1906
+ pathParams: { workspaceId: workspace, dbName: database },
1907
+ body: settings,
1908
+ ...this.extraProps
1909
+ });
1910
+ }
1911
+ deleteDatabaseGithubSettings({
1912
+ workspace,
1913
+ database
1914
+ }) {
1915
+ return operationsByTag.databases.deleteDatabaseGithubSettings({
1916
+ pathParams: { workspaceId: workspace, dbName: database },
1917
+ ...this.extraProps
1918
+ });
1919
+ }
1742
1920
  listRegions({ workspace }) {
1743
1921
  return operationsByTag.databases.listRegions({
1744
1922
  pathParams: { workspaceId: workspace },
@@ -1757,13 +1935,6 @@ class XataApiPlugin {
1757
1935
  class XataPlugin {
1758
1936
  }
1759
1937
 
1760
- function generateUUID() {
1761
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
1762
- const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
1763
- return v.toString(16);
1764
- });
1765
- }
1766
-
1767
1938
  function cleanFilter(filter) {
1768
1939
  if (!filter)
1769
1940
  return void 0;
@@ -1803,11 +1974,11 @@ class Page {
1803
1974
  async previousPage(size, offset) {
1804
1975
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
1805
1976
  }
1806
- async firstPage(size, offset) {
1807
- return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
1977
+ async startPage(size, offset) {
1978
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, start: this.meta.page.cursor } });
1808
1979
  }
1809
- async lastPage(size, offset) {
1810
- return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
1980
+ async endPage(size, offset) {
1981
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, end: this.meta.page.cursor } });
1811
1982
  }
1812
1983
  hasNextPage() {
1813
1984
  return this.meta.page.more;
@@ -1819,7 +1990,7 @@ const PAGINATION_DEFAULT_SIZE = 20;
1819
1990
  const PAGINATION_MAX_OFFSET = 800;
1820
1991
  const PAGINATION_DEFAULT_OFFSET = 0;
1821
1992
  function isCursorPaginationOptions(options) {
1822
- return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
1993
+ return isDefined(options) && (isDefined(options.start) || isDefined(options.end) || isDefined(options.after) || isDefined(options.before));
1823
1994
  }
1824
1995
  const _RecordArray = class extends Array {
1825
1996
  constructor(...args) {
@@ -1840,6 +2011,12 @@ const _RecordArray = class extends Array {
1840
2011
  toArray() {
1841
2012
  return new Array(...this);
1842
2013
  }
2014
+ toSerializable() {
2015
+ return JSON.parse(this.toString());
2016
+ }
2017
+ toString() {
2018
+ return JSON.stringify(this.toArray());
2019
+ }
1843
2020
  map(callbackfn, thisArg) {
1844
2021
  return this.toArray().map(callbackfn, thisArg);
1845
2022
  }
@@ -1851,12 +2028,12 @@ const _RecordArray = class extends Array {
1851
2028
  const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1852
2029
  return new _RecordArray(newPage);
1853
2030
  }
1854
- async firstPage(size, offset) {
1855
- const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
2031
+ async startPage(size, offset) {
2032
+ const newPage = await __privateGet$6(this, _page).startPage(size, offset);
1856
2033
  return new _RecordArray(newPage);
1857
2034
  }
1858
- async lastPage(size, offset) {
1859
- const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
2035
+ async endPage(size, offset) {
2036
+ const newPage = await __privateGet$6(this, _page).endPage(size, offset);
1860
2037
  return new _RecordArray(newPage);
1861
2038
  }
1862
2039
  hasNextPage() {
@@ -1911,8 +2088,10 @@ const _Query = class {
1911
2088
  __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1912
2089
  __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1913
2090
  __privateGet$5(this, _data).columns = data.columns ?? parent?.columns;
2091
+ __privateGet$5(this, _data).consistency = data.consistency ?? parent?.consistency;
1914
2092
  __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1915
2093
  __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
2094
+ __privateGet$5(this, _data).fetchOptions = data.fetchOptions ?? parent?.fetchOptions;
1916
2095
  this.any = this.any.bind(this);
1917
2096
  this.all = this.all.bind(this);
1918
2097
  this.not = this.not.bind(this);
@@ -2040,15 +2219,15 @@ const _Query = class {
2040
2219
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
2041
2220
  }
2042
2221
  nextPage(size, offset) {
2043
- return this.firstPage(size, offset);
2222
+ return this.startPage(size, offset);
2044
2223
  }
2045
2224
  previousPage(size, offset) {
2046
- return this.firstPage(size, offset);
2225
+ return this.startPage(size, offset);
2047
2226
  }
2048
- firstPage(size, offset) {
2227
+ startPage(size, offset) {
2049
2228
  return this.getPaginated({ pagination: { size, offset } });
2050
2229
  }
2051
- lastPage(size, offset) {
2230
+ endPage(size, offset) {
2052
2231
  return this.getPaginated({ pagination: { size, offset, before: "end" } });
2053
2232
  }
2054
2233
  hasNextPage() {
@@ -2131,7 +2310,8 @@ var __privateMethod$2 = (obj, member, method) => {
2131
2310
  __accessCheck$4(obj, member, "access private method");
2132
2311
  return method;
2133
2312
  };
2134
- 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;
2313
+ 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;
2314
+ const BULK_OPERATION_MAX_SIZE = 1e3;
2135
2315
  class Repository extends Query {
2136
2316
  }
2137
2317
  class RestRepository extends Query {
@@ -2143,10 +2323,12 @@ class RestRepository extends Query {
2143
2323
  );
2144
2324
  __privateAdd$4(this, _insertRecordWithoutId);
2145
2325
  __privateAdd$4(this, _insertRecordWithId);
2146
- __privateAdd$4(this, _bulkInsertTableRecords);
2326
+ __privateAdd$4(this, _insertRecords);
2147
2327
  __privateAdd$4(this, _updateRecordWithID);
2328
+ __privateAdd$4(this, _updateRecords);
2148
2329
  __privateAdd$4(this, _upsertRecordWithID);
2149
2330
  __privateAdd$4(this, _deleteRecord);
2331
+ __privateAdd$4(this, _deleteRecords);
2150
2332
  __privateAdd$4(this, _setCacheQuery);
2151
2333
  __privateAdd$4(this, _getCacheQuery);
2152
2334
  __privateAdd$4(this, _getSchemaTables$1);
@@ -2180,20 +2362,22 @@ class RestRepository extends Query {
2180
2362
  if (Array.isArray(a)) {
2181
2363
  if (a.length === 0)
2182
2364
  return [];
2183
- const columns = isStringArray(b) ? b : void 0;
2184
- return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
2365
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: true });
2366
+ const columns = isStringArray(b) ? b : ["*"];
2367
+ const result = await this.read(ids, columns);
2368
+ return result;
2185
2369
  }
2186
2370
  if (isString(a) && isObject(b)) {
2187
2371
  if (a === "")
2188
2372
  throw new Error("The id can't be empty");
2189
2373
  const columns = isStringArray(c) ? c : void 0;
2190
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
2374
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
2191
2375
  }
2192
2376
  if (isObject(a) && isString(a.id)) {
2193
2377
  if (a.id === "")
2194
2378
  throw new Error("The id can't be empty");
2195
2379
  const columns = isStringArray(b) ? b : void 0;
2196
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
2380
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
2197
2381
  }
2198
2382
  if (isObject(a)) {
2199
2383
  const columns = isStringArray(b) ? b : void 0;
@@ -2268,19 +2452,29 @@ class RestRepository extends Query {
2268
2452
  if (Array.isArray(a)) {
2269
2453
  if (a.length === 0)
2270
2454
  return [];
2271
- if (a.length > 100) {
2272
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
2273
- }
2455
+ const existing = await this.read(a, ["id"]);
2456
+ const updates = a.filter((_item, index) => existing[index] !== null);
2457
+ await __privateMethod$2(this, _updateRecords, updateRecords_fn).call(this, updates, {
2458
+ ifVersion,
2459
+ upsert: false
2460
+ });
2274
2461
  const columns = isStringArray(b) ? b : ["*"];
2275
- return Promise.all(a.map((object) => this.update(object, columns)));
2276
- }
2277
- if (isString(a) && isObject(b)) {
2278
- const columns = isStringArray(c) ? c : void 0;
2279
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2462
+ const result = await this.read(a, columns);
2463
+ return result;
2280
2464
  }
2281
- if (isObject(a) && isString(a.id)) {
2282
- const columns = isStringArray(b) ? b : void 0;
2283
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
2465
+ try {
2466
+ if (isString(a) && isObject(b)) {
2467
+ const columns = isStringArray(c) ? c : void 0;
2468
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2469
+ }
2470
+ if (isObject(a) && isString(a.id)) {
2471
+ const columns = isStringArray(b) ? b : void 0;
2472
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
2473
+ }
2474
+ } catch (error) {
2475
+ if (error.status === 422)
2476
+ return null;
2477
+ throw error;
2284
2478
  }
2285
2479
  throw new Error("Invalid arguments for update method");
2286
2480
  });
@@ -2310,11 +2504,13 @@ class RestRepository extends Query {
2310
2504
  if (Array.isArray(a)) {
2311
2505
  if (a.length === 0)
2312
2506
  return [];
2313
- if (a.length > 100) {
2314
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
2315
- }
2507
+ await __privateMethod$2(this, _updateRecords, updateRecords_fn).call(this, a, {
2508
+ ifVersion,
2509
+ upsert: true
2510
+ });
2316
2511
  const columns = isStringArray(b) ? b : ["*"];
2317
- return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
2512
+ const result = await this.read(a, columns);
2513
+ return result;
2318
2514
  }
2319
2515
  if (isString(a) && isObject(b)) {
2320
2516
  const columns = isStringArray(c) ? c : void 0;
@@ -2333,8 +2529,10 @@ class RestRepository extends Query {
2333
2529
  if (Array.isArray(a)) {
2334
2530
  if (a.length === 0)
2335
2531
  return [];
2532
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: false });
2336
2533
  const columns = isStringArray(b) ? b : ["*"];
2337
- return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
2534
+ const result = await this.read(ids, columns);
2535
+ return result;
2338
2536
  }
2339
2537
  if (isString(a) && isObject(b)) {
2340
2538
  const columns = isStringArray(c) ? c : void 0;
@@ -2352,10 +2550,17 @@ class RestRepository extends Query {
2352
2550
  if (Array.isArray(a)) {
2353
2551
  if (a.length === 0)
2354
2552
  return [];
2355
- if (a.length > 100) {
2356
- console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
2357
- }
2358
- return Promise.all(a.map((id) => this.delete(id, b)));
2553
+ const ids = a.map((o) => {
2554
+ if (isString(o))
2555
+ return o;
2556
+ if (isString(o.id))
2557
+ return o.id;
2558
+ throw new Error("Invalid arguments for delete method");
2559
+ });
2560
+ const columns = isStringArray(b) ? b : ["*"];
2561
+ const result = await this.read(a, columns);
2562
+ await __privateMethod$2(this, _deleteRecords, deleteRecords_fn).call(this, ids);
2563
+ return result;
2359
2564
  }
2360
2565
  if (isString(a)) {
2361
2566
  return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
@@ -2400,7 +2605,9 @@ class RestRepository extends Query {
2400
2605
  prefix: options.prefix,
2401
2606
  highlight: options.highlight,
2402
2607
  filter: options.filter,
2403
- boosters: options.boosters
2608
+ boosters: options.boosters,
2609
+ page: options.page,
2610
+ target: options.target
2404
2611
  },
2405
2612
  ...fetchProps
2406
2613
  });
@@ -2442,8 +2649,10 @@ class RestRepository extends Query {
2442
2649
  filter: cleanFilter(data.filter),
2443
2650
  sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2444
2651
  page: data.pagination,
2445
- columns: data.columns ?? ["*"]
2652
+ columns: data.columns ?? ["*"],
2653
+ consistency: data.consistency
2446
2654
  },
2655
+ fetchOptions: data.fetchOptions,
2447
2656
  ...fetchProps
2448
2657
  });
2449
2658
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
@@ -2469,6 +2678,7 @@ class RestRepository extends Query {
2469
2678
  filter: cleanFilter(data.filter),
2470
2679
  sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2471
2680
  columns: data.columns,
2681
+ consistency: data.consistency,
2472
2682
  page: data.pagination?.size !== void 0 ? { size: data.pagination?.size } : void 0,
2473
2683
  summaries,
2474
2684
  summariesFilter
@@ -2522,31 +2732,40 @@ insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { crea
2522
2732
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2523
2733
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2524
2734
  };
2525
- _bulkInsertTableRecords = new WeakSet();
2526
- bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
2735
+ _insertRecords = new WeakSet();
2736
+ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2527
2737
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2528
- const records = objects.map((object) => transformObjectLinks(object));
2529
- const response = await bulkInsertTableRecords({
2530
- pathParams: {
2531
- workspace: "{workspaceId}",
2532
- dbBranchName: "{dbBranch}",
2533
- region: "{region}",
2534
- tableName: __privateGet$4(this, _table)
2535
- },
2536
- queryParams: { columns },
2537
- body: { records },
2538
- ...fetchProps
2539
- });
2540
- if (!isResponseWithRecords(response)) {
2541
- throw new Error("Request included columns but server didn't include them");
2738
+ const chunkedOperations = chunk(
2739
+ objects.map((object) => ({
2740
+ insert: { table: __privateGet$4(this, _table), record: transformObjectLinks(object), createOnly, ifVersion }
2741
+ })),
2742
+ BULK_OPERATION_MAX_SIZE
2743
+ );
2744
+ const ids = [];
2745
+ for (const operations of chunkedOperations) {
2746
+ const { results } = await branchTransaction({
2747
+ pathParams: {
2748
+ workspace: "{workspaceId}",
2749
+ dbBranchName: "{dbBranch}",
2750
+ region: "{region}"
2751
+ },
2752
+ body: { operations },
2753
+ ...fetchProps
2754
+ });
2755
+ for (const result of results) {
2756
+ if (result.operation === "insert") {
2757
+ ids.push(result.id);
2758
+ } else {
2759
+ ids.push(null);
2760
+ }
2761
+ }
2542
2762
  }
2543
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2544
- return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, columns));
2763
+ return ids;
2545
2764
  };
2546
2765
  _updateRecordWithID = new WeakSet();
2547
2766
  updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2548
2767
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2549
- const record = transformObjectLinks(object);
2768
+ const { id: _id, ...record } = transformObjectLinks(object);
2550
2769
  try {
2551
2770
  const response = await updateRecordWithID({
2552
2771
  pathParams: {
@@ -2569,6 +2788,36 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2569
2788
  throw e;
2570
2789
  }
2571
2790
  };
2791
+ _updateRecords = new WeakSet();
2792
+ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2793
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2794
+ const chunkedOperations = chunk(
2795
+ objects.map(({ id, ...object }) => ({
2796
+ update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields: transformObjectLinks(object) }
2797
+ })),
2798
+ BULK_OPERATION_MAX_SIZE
2799
+ );
2800
+ const ids = [];
2801
+ for (const operations of chunkedOperations) {
2802
+ const { results } = await branchTransaction({
2803
+ pathParams: {
2804
+ workspace: "{workspaceId}",
2805
+ dbBranchName: "{dbBranch}",
2806
+ region: "{region}"
2807
+ },
2808
+ body: { operations },
2809
+ ...fetchProps
2810
+ });
2811
+ for (const result of results) {
2812
+ if (result.operation === "update") {
2813
+ ids.push(result.id);
2814
+ } else {
2815
+ ids.push(null);
2816
+ }
2817
+ }
2818
+ }
2819
+ return ids;
2820
+ };
2572
2821
  _upsertRecordWithID = new WeakSet();
2573
2822
  upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2574
2823
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
@@ -2611,6 +2860,25 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2611
2860
  throw e;
2612
2861
  }
2613
2862
  };
2863
+ _deleteRecords = new WeakSet();
2864
+ deleteRecords_fn = async function(recordIds) {
2865
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2866
+ const chunkedOperations = chunk(
2867
+ recordIds.map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
2868
+ BULK_OPERATION_MAX_SIZE
2869
+ );
2870
+ for (const operations of chunkedOperations) {
2871
+ await branchTransaction({
2872
+ pathParams: {
2873
+ workspace: "{workspaceId}",
2874
+ dbBranchName: "{dbBranch}",
2875
+ region: "{region}"
2876
+ },
2877
+ body: { operations },
2878
+ ...fetchProps
2879
+ });
2880
+ }
2881
+ };
2614
2882
  _setCacheQuery = new WeakSet();
2615
2883
  setCacheQuery_fn = async function(query, meta, records) {
2616
2884
  await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
@@ -2647,23 +2915,23 @@ const transformObjectLinks = (object) => {
2647
2915
  }, {});
2648
2916
  };
2649
2917
  const initObject = (db, schemaTables, table, object, selectedColumns) => {
2650
- const result = {};
2918
+ const data = {};
2651
2919
  const { xata, ...rest } = object ?? {};
2652
- Object.assign(result, rest);
2920
+ Object.assign(data, rest);
2653
2921
  const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
2654
2922
  if (!columns)
2655
2923
  console.error(`Table ${table} not found in schema`);
2656
2924
  for (const column of columns ?? []) {
2657
2925
  if (!isValidColumn(selectedColumns, column))
2658
2926
  continue;
2659
- const value = result[column.name];
2927
+ const value = data[column.name];
2660
2928
  switch (column.type) {
2661
2929
  case "datetime": {
2662
- const date = value !== void 0 ? new Date(value) : void 0;
2663
- if (date && isNaN(date.getTime())) {
2930
+ const date = value !== void 0 ? new Date(value) : null;
2931
+ if (date !== null && isNaN(date.getTime())) {
2664
2932
  console.error(`Failed to parse date ${value} for field ${column.name}`);
2665
- } else if (date) {
2666
- result[column.name] = date;
2933
+ } else {
2934
+ data[column.name] = date;
2667
2935
  }
2668
2936
  break;
2669
2937
  }
@@ -2682,41 +2950,52 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
2682
2950
  }
2683
2951
  return acc;
2684
2952
  }, []);
2685
- result[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
2953
+ data[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
2686
2954
  } else {
2687
- result[column.name] = null;
2955
+ data[column.name] = null;
2688
2956
  }
2689
2957
  break;
2690
2958
  }
2691
2959
  default:
2692
- result[column.name] = value ?? null;
2960
+ data[column.name] = value ?? null;
2693
2961
  if (column.notNull === true && value === null) {
2694
2962
  console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
2695
2963
  }
2696
2964
  break;
2697
2965
  }
2698
2966
  }
2699
- result.read = function(columns2) {
2700
- return db[table].read(result["id"], columns2);
2967
+ const record = { ...data };
2968
+ record.read = function(columns2) {
2969
+ return db[table].read(record["id"], columns2);
2701
2970
  };
2702
- result.update = function(data, columns2) {
2703
- return db[table].update(result["id"], data, columns2);
2971
+ record.update = function(data2, b, c) {
2972
+ const columns2 = isStringArray(b) ? b : ["*"];
2973
+ const ifVersion = parseIfVersion(b, c);
2974
+ return db[table].update(record["id"], data2, columns2, { ifVersion });
2704
2975
  };
2705
- result.delete = function() {
2706
- return db[table].delete(result["id"]);
2976
+ record.replace = function(data2, b, c) {
2977
+ const columns2 = isStringArray(b) ? b : ["*"];
2978
+ const ifVersion = parseIfVersion(b, c);
2979
+ return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
2707
2980
  };
2708
- result.getMetadata = function() {
2981
+ record.delete = function() {
2982
+ return db[table].delete(record["id"]);
2983
+ };
2984
+ record.getMetadata = function() {
2709
2985
  return xata;
2710
2986
  };
2711
- for (const prop of ["read", "update", "delete", "getMetadata"]) {
2712
- Object.defineProperty(result, prop, { enumerable: false });
2987
+ record.toSerializable = function() {
2988
+ return JSON.parse(JSON.stringify(transformObjectLinks(data)));
2989
+ };
2990
+ record.toString = function() {
2991
+ return JSON.stringify(transformObjectLinks(data));
2992
+ };
2993
+ for (const prop of ["read", "update", "replace", "delete", "getMetadata", "toSerializable", "toString"]) {
2994
+ Object.defineProperty(record, prop, { enumerable: false });
2713
2995
  }
2714
- Object.freeze(result);
2715
- return result;
2996
+ Object.freeze(record);
2997
+ return record;
2716
2998
  };
2717
- function isResponseWithRecords(value) {
2718
- return isObject(value) && Array.isArray(value.records);
2719
- }
2720
2999
  function extractId(value) {
2721
3000
  if (isString(value))
2722
3001
  return value;
@@ -2926,10 +3205,10 @@ _schemaTables = new WeakMap();
2926
3205
  _search = new WeakSet();
2927
3206
  search_fn = async function(query, options, getFetchProps) {
2928
3207
  const fetchProps = await getFetchProps();
2929
- const { tables, fuzziness, highlight, prefix } = options ?? {};
3208
+ const { tables, fuzziness, highlight, prefix, page } = options ?? {};
2930
3209
  const { records } = await searchBranch({
2931
3210
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
2932
- body: { tables, query, fuzziness, prefix, highlight },
3211
+ body: { tables, query, fuzziness, prefix, highlight, page },
2933
3212
  ...fetchProps
2934
3213
  });
2935
3214
  return records;
@@ -2947,18 +3226,30 @@ getSchemaTables_fn = async function(getFetchProps) {
2947
3226
  return schema.tables;
2948
3227
  };
2949
3228
 
3229
+ class TransactionPlugin extends XataPlugin {
3230
+ build({ getFetchProps }) {
3231
+ return {
3232
+ run: async (operations) => {
3233
+ const fetchProps = await getFetchProps();
3234
+ const response = await branchTransaction({
3235
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3236
+ body: { operations },
3237
+ ...fetchProps
3238
+ });
3239
+ return response;
3240
+ }
3241
+ };
3242
+ }
3243
+ }
3244
+
2950
3245
  const isBranchStrategyBuilder = (strategy) => {
2951
3246
  return typeof strategy === "function";
2952
3247
  };
2953
3248
 
2954
3249
  async function getCurrentBranchName(options) {
2955
3250
  const { branch, envBranch } = getEnvironment();
2956
- if (branch) {
2957
- const details = await getDatabaseBranch(branch, options);
2958
- if (details)
2959
- return branch;
2960
- console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
2961
- }
3251
+ if (branch)
3252
+ return branch;
2962
3253
  const gitBranch = envBranch || await getGitBranch();
2963
3254
  return resolveXataBranch(gitBranch, options);
2964
3255
  }
@@ -2990,7 +3281,9 @@ async function resolveXataBranch(gitBranch, options) {
2990
3281
  workspacesApiUrl: `${protocol}//${host}`,
2991
3282
  pathParams: { dbName, workspace, region },
2992
3283
  queryParams: { gitBranch, fallbackBranch },
2993
- trace: defaultTrace
3284
+ trace: defaultTrace,
3285
+ clientName: options?.clientName,
3286
+ xataAgentExtra: options?.xataAgentExtra
2994
3287
  });
2995
3288
  return branch;
2996
3289
  }
@@ -3074,8 +3367,10 @@ const buildClient = (plugins) => {
3074
3367
  };
3075
3368
  const db = new SchemaPlugin(schemaTables).build(pluginOptions);
3076
3369
  const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
3370
+ const transactions = new TransactionPlugin().build(pluginOptions);
3077
3371
  this.db = db;
3078
3372
  this.search = search;
3373
+ this.transactions = transactions;
3079
3374
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
3080
3375
  if (namespace === void 0)
3081
3376
  continue;
@@ -3095,20 +3390,55 @@ const buildClient = (plugins) => {
3095
3390
  return { databaseURL, branch };
3096
3391
  }
3097
3392
  }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3393
+ const enableBrowser = options?.enableBrowser ?? getEnableBrowserVariable() ?? false;
3394
+ const isBrowser = typeof window !== "undefined" && typeof Deno === "undefined";
3395
+ if (isBrowser && !enableBrowser) {
3396
+ throw new Error(
3397
+ "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."
3398
+ );
3399
+ }
3098
3400
  const fetch = getFetchImplementation(options?.fetch);
3099
3401
  const databaseURL = options?.databaseURL || getDatabaseURL();
3100
3402
  const apiKey = options?.apiKey || getAPIKey();
3101
3403
  const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
3102
3404
  const trace = options?.trace ?? defaultTrace;
3103
- const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
3405
+ const clientName = options?.clientName;
3406
+ const xataAgentExtra = options?.xataAgentExtra;
3407
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({
3408
+ apiKey,
3409
+ databaseURL,
3410
+ fetchImpl: options?.fetch,
3411
+ clientName,
3412
+ xataAgentExtra
3413
+ });
3104
3414
  if (!apiKey) {
3105
3415
  throw new Error("Option apiKey is required");
3106
3416
  }
3107
3417
  if (!databaseURL) {
3108
3418
  throw new Error("Option databaseURL is required");
3109
3419
  }
3110
- return { fetch, databaseURL, apiKey, branch, cache, trace, clientID: generateUUID() };
3111
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace, clientID }) {
3420
+ return {
3421
+ fetch,
3422
+ databaseURL,
3423
+ apiKey,
3424
+ branch,
3425
+ cache,
3426
+ trace,
3427
+ clientID: generateUUID(),
3428
+ enableBrowser,
3429
+ clientName,
3430
+ xataAgentExtra
3431
+ };
3432
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
3433
+ fetch,
3434
+ apiKey,
3435
+ databaseURL,
3436
+ branch,
3437
+ trace,
3438
+ clientID,
3439
+ clientName,
3440
+ xataAgentExtra
3441
+ }) {
3112
3442
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
3113
3443
  if (!branchValue)
3114
3444
  throw new Error("Unable to resolve branch value");
@@ -3122,7 +3452,9 @@ const buildClient = (plugins) => {
3122
3452
  return databaseURL + newPath;
3123
3453
  },
3124
3454
  trace,
3125
- clientID
3455
+ clientID,
3456
+ clientName,
3457
+ xataAgentExtra
3126
3458
  };
3127
3459
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
3128
3460
  if (__privateGet(this, _branch))
@@ -3213,7 +3545,7 @@ const deserialize = (json) => {
3213
3545
  };
3214
3546
 
3215
3547
  function buildWorkerRunner(config) {
3216
- return function xataWorker(name, _worker) {
3548
+ return function xataWorker(name, worker) {
3217
3549
  return async (...args) => {
3218
3550
  const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
3219
3551
  const result = await fetch(url, {
@@ -3235,6 +3567,7 @@ class XataError extends Error {
3235
3567
  }
3236
3568
 
3237
3569
  exports.BaseClient = BaseClient;
3570
+ exports.FetcherError = FetcherError;
3238
3571
  exports.Operations = operationsByTag;
3239
3572
  exports.PAGINATION_DEFAULT_OFFSET = PAGINATION_DEFAULT_OFFSET;
3240
3573
  exports.PAGINATION_DEFAULT_SIZE = PAGINATION_DEFAULT_SIZE;
@@ -3258,14 +3591,10 @@ exports.addGitBranchesEntry = addGitBranchesEntry;
3258
3591
  exports.addTableColumn = addTableColumn;
3259
3592
  exports.aggregateTable = aggregateTable;
3260
3593
  exports.applyBranchSchemaEdit = applyBranchSchemaEdit;
3594
+ exports.branchTransaction = branchTransaction;
3261
3595
  exports.buildClient = buildClient;
3262
3596
  exports.buildWorkerRunner = buildWorkerRunner;
3263
3597
  exports.bulkInsertTableRecords = bulkInsertTableRecords;
3264
- exports.cPCreateDatabase = cPCreateDatabase;
3265
- exports.cPDeleteDatabase = cPDeleteDatabase;
3266
- exports.cPGetCPDatabaseMetadata = cPGetCPDatabaseMetadata;
3267
- exports.cPGetDatabaseList = cPGetDatabaseList;
3268
- exports.cPUpdateCPDatabaseMetadata = cPUpdateCPDatabaseMetadata;
3269
3598
  exports.cancelWorkspaceMemberInvite = cancelWorkspaceMemberInvite;
3270
3599
  exports.compareBranchSchemas = compareBranchSchemas;
3271
3600
  exports.compareBranchWithUserSchema = compareBranchWithUserSchema;
@@ -3280,6 +3609,7 @@ exports.createWorkspace = createWorkspace;
3280
3609
  exports.deleteBranch = deleteBranch;
3281
3610
  exports.deleteColumn = deleteColumn;
3282
3611
  exports.deleteDatabase = deleteDatabase;
3612
+ exports.deleteDatabaseGithubSettings = deleteDatabaseGithubSettings;
3283
3613
  exports.deleteRecord = deleteRecord;
3284
3614
  exports.deleteTable = deleteTable;
3285
3615
  exports.deleteUser = deleteUser;
@@ -3302,6 +3632,7 @@ exports.getBranchStats = getBranchStats;
3302
3632
  exports.getColumn = getColumn;
3303
3633
  exports.getCurrentBranchDetails = getCurrentBranchDetails;
3304
3634
  exports.getCurrentBranchName = getCurrentBranchName;
3635
+ exports.getDatabaseGithubSettings = getDatabaseGithubSettings;
3305
3636
  exports.getDatabaseList = getDatabaseList;
3306
3637
  exports.getDatabaseMetadata = getDatabaseMetadata;
3307
3638
  exports.getDatabaseURL = getDatabaseURL;
@@ -3366,6 +3697,7 @@ exports.summarizeTable = summarizeTable;
3366
3697
  exports.updateBranchMetadata = updateBranchMetadata;
3367
3698
  exports.updateBranchSchema = updateBranchSchema;
3368
3699
  exports.updateColumn = updateColumn;
3700
+ exports.updateDatabaseGithubSettings = updateDatabaseGithubSettings;
3369
3701
  exports.updateDatabaseMetadata = updateDatabaseMetadata;
3370
3702
  exports.updateMigrationRequest = updateMigrationRequest;
3371
3703
  exports.updateRecordWithID = updateRecordWithID;