@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.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
+ };
294
+
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
+ }
166
301
 
167
- const VERSION = "0.0.0-alpha.vfde8eac";
302
+ const VERSION = "0.22.1";
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,13 @@ async function fetch$1({
254
391
  trace,
255
392
  signal,
256
393
  clientID,
257
- sessionID
394
+ sessionID,
395
+ clientName,
396
+ xataAgentExtra,
397
+ fetchOptions = {}
258
398
  }) {
259
- return trace(
399
+ pool.setFetch(fetchImpl);
400
+ return await trace(
260
401
  `${method.toUpperCase()} ${path}`,
261
402
  async ({ setAttributes }) => {
262
403
  const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
@@ -266,23 +407,29 @@ async function fetch$1({
266
407
  [TraceAttributes.HTTP_URL]: url,
267
408
  [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
268
409
  });
269
- const response = await fetchImpl(url, {
410
+ const xataAgent = compact([
411
+ ["client", "TS_SDK"],
412
+ ["version", VERSION],
413
+ isDefined(clientName) ? ["service", clientName] : void 0,
414
+ ...Object.entries(xataAgentExtra ?? {})
415
+ ]).map(([key, value]) => `${key}=${value}`).join("; ");
416
+ const headers = {
417
+ "Accept-Encoding": "identity",
418
+ "Content-Type": "application/json",
419
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
420
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
421
+ "X-Xata-Agent": xataAgent,
422
+ ...customHeaders,
423
+ ...hostHeader(fullUrl),
424
+ Authorization: `Bearer ${apiKey}`
425
+ };
426
+ const response = await pool.request(url, {
427
+ ...fetchOptions,
270
428
  method: method.toUpperCase(),
271
429
  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
- },
430
+ headers,
281
431
  signal
282
432
  });
283
- if (response.status === 204) {
284
- return {};
285
- }
286
433
  const { host, protocol } = parseUrl(response.url);
287
434
  const requestId = response.headers?.get("x-request-id") ?? void 0;
288
435
  setAttributes({
@@ -292,6 +439,12 @@ async function fetch$1({
292
439
  [TraceAttributes.HTTP_HOST]: host,
293
440
  [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
294
441
  });
442
+ if (response.status === 204) {
443
+ return {};
444
+ }
445
+ if (response.status === 429) {
446
+ throw new FetcherError(response.status, "Rate limit exceeded", requestId);
447
+ }
295
448
  try {
296
449
  const jsonResponse = await response.json();
297
450
  if (response.ok) {
@@ -316,32 +469,12 @@ function parseUrl(url) {
316
469
 
317
470
  const dataPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "dataPlane" });
318
471
 
319
- const getDatabaseList = (variables, signal) => dataPlaneFetch({
320
- url: "/dbs",
321
- method: "get",
322
- ...variables,
323
- signal
324
- });
325
472
  const getBranchList = (variables, signal) => dataPlaneFetch({
326
473
  url: "/dbs/{dbName}",
327
474
  method: "get",
328
475
  ...variables,
329
476
  signal
330
477
  });
331
- const createDatabase = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}", method: "put", ...variables, signal });
332
- const deleteDatabase = (variables, signal) => dataPlaneFetch({
333
- url: "/dbs/{dbName}",
334
- method: "delete",
335
- ...variables,
336
- signal
337
- });
338
- const getDatabaseMetadata = (variables, signal) => dataPlaneFetch({
339
- url: "/dbs/{dbName}/metadata",
340
- method: "get",
341
- ...variables,
342
- signal
343
- });
344
- const updateDatabaseMetadata = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/metadata", method: "patch", ...variables, signal });
345
478
  const getBranchDetails = (variables, signal) => dataPlaneFetch({
346
479
  url: "/db/{dbBranchName}",
347
480
  method: "get",
@@ -446,6 +579,7 @@ const deleteColumn = (variables, signal) => dataPlaneFetch({
446
579
  ...variables,
447
580
  signal
448
581
  });
582
+ const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
449
583
  const insertRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
450
584
  const getRecord = (variables, signal) => dataPlaneFetch({
451
585
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
@@ -479,7 +613,6 @@ const searchTable = (variables, signal) => dataPlaneFetch({
479
613
  const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
480
614
  const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
481
615
  const operationsByTag$2 = {
482
- database: { getDatabaseList, createDatabase, deleteDatabase, getDatabaseMetadata, updateDatabaseMetadata },
483
616
  branch: {
484
617
  getBranchList,
485
618
  getBranchDetails,
@@ -527,6 +660,7 @@ const operationsByTag$2 = {
527
660
  deleteColumn
528
661
  },
529
662
  records: {
663
+ branchTransaction,
530
664
  insertRecord,
531
665
  getRecord,
532
666
  insertRecordWithID,
@@ -619,16 +753,24 @@ const updateWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ u
619
753
  const cancelWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "delete", ...variables, signal });
620
754
  const acceptWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept", method: "post", ...variables, signal });
621
755
  const resendWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}/resend", method: "post", ...variables, signal });
622
- const cPGetDatabaseList = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs", method: "get", ...variables, signal });
623
- const cPCreateDatabase = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "put", ...variables, signal });
624
- const cPDeleteDatabase = (variables, signal) => controlPlaneFetch({
756
+ const getDatabaseList = (variables, signal) => controlPlaneFetch({
757
+ url: "/workspaces/{workspaceId}/dbs",
758
+ method: "get",
759
+ ...variables,
760
+ signal
761
+ });
762
+ const createDatabase = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "put", ...variables, signal });
763
+ const deleteDatabase = (variables, signal) => controlPlaneFetch({
625
764
  url: "/workspaces/{workspaceId}/dbs/{dbName}",
626
765
  method: "delete",
627
766
  ...variables,
628
767
  signal
629
768
  });
630
- const cPGetCPDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "get", ...variables, signal });
631
- const cPUpdateCPDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "patch", ...variables, signal });
769
+ const getDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "get", ...variables, signal });
770
+ const updateDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "patch", ...variables, signal });
771
+ const getDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "get", ...variables, signal });
772
+ const updateDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "put", ...variables, signal });
773
+ const deleteDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "delete", ...variables, signal });
632
774
  const listRegions = (variables, signal) => controlPlaneFetch({
633
775
  url: "/workspaces/{workspaceId}/regions",
634
776
  method: "get",
@@ -656,11 +798,14 @@ const operationsByTag$1 = {
656
798
  resendWorkspaceMemberInvite
657
799
  },
658
800
  databases: {
659
- cPGetDatabaseList,
660
- cPCreateDatabase,
661
- cPDeleteDatabase,
662
- cPGetCPDatabaseMetadata,
663
- cPUpdateCPDatabaseMetadata,
801
+ getDatabaseList,
802
+ createDatabase,
803
+ deleteDatabase,
804
+ getDatabaseMetadata,
805
+ updateDatabaseMetadata,
806
+ getDatabaseGithubSettings,
807
+ updateDatabaseGithubSettings,
808
+ deleteDatabaseGithubSettings,
664
809
  listRegions
665
810
  }
666
811
  };
@@ -703,12 +848,13 @@ function parseProviderString(provider = "production") {
703
848
  function parseWorkspacesUrlParts(url) {
704
849
  if (!isString(url))
705
850
  return null;
706
- const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))?\.xata\.sh.*/;
707
- const regexStaging = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))?\.xatabase\.co.*/;
708
- const match = url.match(regex) || url.match(regexStaging);
851
+ const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/;
852
+ const regexStaging = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))\.xatabase\.co.*/;
853
+ const regexDev = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))\.xata\.tech.*/;
854
+ const match = url.match(regex) || url.match(regexStaging) || url.match(regexDev);
709
855
  if (!match)
710
856
  return null;
711
- return { workspace: match[1], region: match[2] ?? "eu-west-1" };
857
+ return { workspace: match[1], region: match[2] };
712
858
  }
713
859
 
714
860
  var __accessCheck$7 = (obj, member, msg) => {
@@ -737,6 +883,7 @@ class XataApiClient {
737
883
  const provider = options.host ?? "production";
738
884
  const apiKey = options.apiKey ?? getAPIKey();
739
885
  const trace = options.trace ?? defaultTrace;
886
+ const clientID = generateUUID();
740
887
  if (!apiKey) {
741
888
  throw new Error("Could not resolve a valid apiKey");
742
889
  }
@@ -745,7 +892,10 @@ class XataApiClient {
745
892
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
746
893
  fetchImpl: getFetchImplementation(options.fetch),
747
894
  apiKey,
748
- trace
895
+ trace,
896
+ clientName: options.clientName,
897
+ xataAgentExtra: options.xataAgentExtra,
898
+ clientID
749
899
  });
750
900
  }
751
901
  get user() {
@@ -1347,6 +1497,19 @@ class RecordsApi {
1347
1497
  ...this.extraProps
1348
1498
  });
1349
1499
  }
1500
+ branchTransaction({
1501
+ workspace,
1502
+ region,
1503
+ database,
1504
+ branch,
1505
+ operations
1506
+ }) {
1507
+ return operationsByTag.records.branchTransaction({
1508
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1509
+ body: { operations },
1510
+ ...this.extraProps
1511
+ });
1512
+ }
1350
1513
  }
1351
1514
  class SearchAndFilterApi {
1352
1515
  constructor(extraProps) {
@@ -1361,11 +1524,12 @@ class SearchAndFilterApi {
1361
1524
  filter,
1362
1525
  sort,
1363
1526
  page,
1364
- columns
1527
+ columns,
1528
+ consistency
1365
1529
  }) {
1366
1530
  return operationsByTag.searchAndFilter.queryTable({
1367
1531
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1368
- body: { filter, sort, page, columns },
1532
+ body: { filter, sort, page, columns, consistency },
1369
1533
  ...this.extraProps
1370
1534
  });
1371
1535
  }
@@ -1417,11 +1581,12 @@ class SearchAndFilterApi {
1417
1581
  summaries,
1418
1582
  sort,
1419
1583
  summariesFilter,
1420
- page
1584
+ page,
1585
+ consistency
1421
1586
  }) {
1422
1587
  return operationsByTag.searchAndFilter.summarizeTable({
1423
1588
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1424
- body: { filter, columns, summaries, sort, summariesFilter, page },
1589
+ body: { filter, columns, summaries, sort, summariesFilter, page, consistency },
1425
1590
  ...this.extraProps
1426
1591
  });
1427
1592
  }
@@ -1605,11 +1770,13 @@ class MigrationsApi {
1605
1770
  region,
1606
1771
  database,
1607
1772
  branch,
1608
- schema
1773
+ schema,
1774
+ schemaOperations,
1775
+ branchOperations
1609
1776
  }) {
1610
1777
  return operationsByTag.migrations.compareBranchWithUserSchema({
1611
1778
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1612
- body: { schema },
1779
+ body: { schema, schemaOperations, branchOperations },
1613
1780
  ...this.extraProps
1614
1781
  });
1615
1782
  }
@@ -1619,11 +1786,12 @@ class MigrationsApi {
1619
1786
  database,
1620
1787
  branch,
1621
1788
  compare,
1622
- schema
1789
+ sourceBranchOperations,
1790
+ targetBranchOperations
1623
1791
  }) {
1624
1792
  return operationsByTag.migrations.compareBranchSchemas({
1625
1793
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, branchName: compare },
1626
- body: { schema },
1794
+ body: { sourceBranchOperations, targetBranchOperations },
1627
1795
  ...this.extraProps
1628
1796
  });
1629
1797
  }
@@ -1672,7 +1840,7 @@ class DatabaseApi {
1672
1840
  this.extraProps = extraProps;
1673
1841
  }
1674
1842
  getDatabaseList({ workspace }) {
1675
- return operationsByTag.databases.cPGetDatabaseList({
1843
+ return operationsByTag.databases.getDatabaseList({
1676
1844
  pathParams: { workspaceId: workspace },
1677
1845
  ...this.extraProps
1678
1846
  });
@@ -1682,7 +1850,7 @@ class DatabaseApi {
1682
1850
  database,
1683
1851
  data
1684
1852
  }) {
1685
- return operationsByTag.databases.cPCreateDatabase({
1853
+ return operationsByTag.databases.createDatabase({
1686
1854
  pathParams: { workspaceId: workspace, dbName: database },
1687
1855
  body: data,
1688
1856
  ...this.extraProps
@@ -1692,7 +1860,7 @@ class DatabaseApi {
1692
1860
  workspace,
1693
1861
  database
1694
1862
  }) {
1695
- return operationsByTag.databases.cPDeleteDatabase({
1863
+ return operationsByTag.databases.deleteDatabase({
1696
1864
  pathParams: { workspaceId: workspace, dbName: database },
1697
1865
  ...this.extraProps
1698
1866
  });
@@ -1701,7 +1869,7 @@ class DatabaseApi {
1701
1869
  workspace,
1702
1870
  database
1703
1871
  }) {
1704
- return operationsByTag.databases.cPGetCPDatabaseMetadata({
1872
+ return operationsByTag.databases.getDatabaseMetadata({
1705
1873
  pathParams: { workspaceId: workspace, dbName: database },
1706
1874
  ...this.extraProps
1707
1875
  });
@@ -1711,12 +1879,41 @@ class DatabaseApi {
1711
1879
  database,
1712
1880
  metadata
1713
1881
  }) {
1714
- return operationsByTag.databases.cPUpdateCPDatabaseMetadata({
1882
+ return operationsByTag.databases.updateDatabaseMetadata({
1715
1883
  pathParams: { workspaceId: workspace, dbName: database },
1716
1884
  body: metadata,
1717
1885
  ...this.extraProps
1718
1886
  });
1719
1887
  }
1888
+ getDatabaseGithubSettings({
1889
+ workspace,
1890
+ database
1891
+ }) {
1892
+ return operationsByTag.databases.getDatabaseGithubSettings({
1893
+ pathParams: { workspaceId: workspace, dbName: database },
1894
+ ...this.extraProps
1895
+ });
1896
+ }
1897
+ updateDatabaseGithubSettings({
1898
+ workspace,
1899
+ database,
1900
+ settings
1901
+ }) {
1902
+ return operationsByTag.databases.updateDatabaseGithubSettings({
1903
+ pathParams: { workspaceId: workspace, dbName: database },
1904
+ body: settings,
1905
+ ...this.extraProps
1906
+ });
1907
+ }
1908
+ deleteDatabaseGithubSettings({
1909
+ workspace,
1910
+ database
1911
+ }) {
1912
+ return operationsByTag.databases.deleteDatabaseGithubSettings({
1913
+ pathParams: { workspaceId: workspace, dbName: database },
1914
+ ...this.extraProps
1915
+ });
1916
+ }
1720
1917
  listRegions({ workspace }) {
1721
1918
  return operationsByTag.databases.listRegions({
1722
1919
  pathParams: { workspaceId: workspace },
@@ -1735,13 +1932,6 @@ class XataApiPlugin {
1735
1932
  class XataPlugin {
1736
1933
  }
1737
1934
 
1738
- function generateUUID() {
1739
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
1740
- const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
1741
- return v.toString(16);
1742
- });
1743
- }
1744
-
1745
1935
  function cleanFilter(filter) {
1746
1936
  if (!filter)
1747
1937
  return void 0;
@@ -1781,11 +1971,11 @@ class Page {
1781
1971
  async previousPage(size, offset) {
1782
1972
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
1783
1973
  }
1784
- async firstPage(size, offset) {
1785
- return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
1974
+ async startPage(size, offset) {
1975
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, start: this.meta.page.cursor } });
1786
1976
  }
1787
- async lastPage(size, offset) {
1788
- return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
1977
+ async endPage(size, offset) {
1978
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, end: this.meta.page.cursor } });
1789
1979
  }
1790
1980
  hasNextPage() {
1791
1981
  return this.meta.page.more;
@@ -1797,7 +1987,7 @@ const PAGINATION_DEFAULT_SIZE = 20;
1797
1987
  const PAGINATION_MAX_OFFSET = 800;
1798
1988
  const PAGINATION_DEFAULT_OFFSET = 0;
1799
1989
  function isCursorPaginationOptions(options) {
1800
- return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
1990
+ return isDefined(options) && (isDefined(options.start) || isDefined(options.end) || isDefined(options.after) || isDefined(options.before));
1801
1991
  }
1802
1992
  const _RecordArray = class extends Array {
1803
1993
  constructor(...args) {
@@ -1818,6 +2008,12 @@ const _RecordArray = class extends Array {
1818
2008
  toArray() {
1819
2009
  return new Array(...this);
1820
2010
  }
2011
+ toSerializable() {
2012
+ return JSON.parse(this.toString());
2013
+ }
2014
+ toString() {
2015
+ return JSON.stringify(this.toArray());
2016
+ }
1821
2017
  map(callbackfn, thisArg) {
1822
2018
  return this.toArray().map(callbackfn, thisArg);
1823
2019
  }
@@ -1829,12 +2025,12 @@ const _RecordArray = class extends Array {
1829
2025
  const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1830
2026
  return new _RecordArray(newPage);
1831
2027
  }
1832
- async firstPage(size, offset) {
1833
- const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
2028
+ async startPage(size, offset) {
2029
+ const newPage = await __privateGet$6(this, _page).startPage(size, offset);
1834
2030
  return new _RecordArray(newPage);
1835
2031
  }
1836
- async lastPage(size, offset) {
1837
- const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
2032
+ async endPage(size, offset) {
2033
+ const newPage = await __privateGet$6(this, _page).endPage(size, offset);
1838
2034
  return new _RecordArray(newPage);
1839
2035
  }
1840
2036
  hasNextPage() {
@@ -1889,8 +2085,10 @@ const _Query = class {
1889
2085
  __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1890
2086
  __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1891
2087
  __privateGet$5(this, _data).columns = data.columns ?? parent?.columns;
2088
+ __privateGet$5(this, _data).consistency = data.consistency ?? parent?.consistency;
1892
2089
  __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1893
2090
  __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
2091
+ __privateGet$5(this, _data).fetchOptions = data.fetchOptions ?? parent?.fetchOptions;
1894
2092
  this.any = this.any.bind(this);
1895
2093
  this.all = this.all.bind(this);
1896
2094
  this.not = this.not.bind(this);
@@ -2018,15 +2216,15 @@ const _Query = class {
2018
2216
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
2019
2217
  }
2020
2218
  nextPage(size, offset) {
2021
- return this.firstPage(size, offset);
2219
+ return this.startPage(size, offset);
2022
2220
  }
2023
2221
  previousPage(size, offset) {
2024
- return this.firstPage(size, offset);
2222
+ return this.startPage(size, offset);
2025
2223
  }
2026
- firstPage(size, offset) {
2224
+ startPage(size, offset) {
2027
2225
  return this.getPaginated({ pagination: { size, offset } });
2028
2226
  }
2029
- lastPage(size, offset) {
2227
+ endPage(size, offset) {
2030
2228
  return this.getPaginated({ pagination: { size, offset, before: "end" } });
2031
2229
  }
2032
2230
  hasNextPage() {
@@ -2109,7 +2307,8 @@ var __privateMethod$2 = (obj, member, method) => {
2109
2307
  __accessCheck$4(obj, member, "access private method");
2110
2308
  return method;
2111
2309
  };
2112
- 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;
2310
+ 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;
2311
+ const BULK_OPERATION_MAX_SIZE = 1e3;
2113
2312
  class Repository extends Query {
2114
2313
  }
2115
2314
  class RestRepository extends Query {
@@ -2121,10 +2320,12 @@ class RestRepository extends Query {
2121
2320
  );
2122
2321
  __privateAdd$4(this, _insertRecordWithoutId);
2123
2322
  __privateAdd$4(this, _insertRecordWithId);
2124
- __privateAdd$4(this, _bulkInsertTableRecords);
2323
+ __privateAdd$4(this, _insertRecords);
2125
2324
  __privateAdd$4(this, _updateRecordWithID);
2325
+ __privateAdd$4(this, _updateRecords);
2126
2326
  __privateAdd$4(this, _upsertRecordWithID);
2127
2327
  __privateAdd$4(this, _deleteRecord);
2328
+ __privateAdd$4(this, _deleteRecords);
2128
2329
  __privateAdd$4(this, _setCacheQuery);
2129
2330
  __privateAdd$4(this, _getCacheQuery);
2130
2331
  __privateAdd$4(this, _getSchemaTables$1);
@@ -2158,20 +2359,22 @@ class RestRepository extends Query {
2158
2359
  if (Array.isArray(a)) {
2159
2360
  if (a.length === 0)
2160
2361
  return [];
2161
- const columns = isStringArray(b) ? b : void 0;
2162
- return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
2362
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: true });
2363
+ const columns = isStringArray(b) ? b : ["*"];
2364
+ const result = await this.read(ids, columns);
2365
+ return result;
2163
2366
  }
2164
2367
  if (isString(a) && isObject(b)) {
2165
2368
  if (a === "")
2166
2369
  throw new Error("The id can't be empty");
2167
2370
  const columns = isStringArray(c) ? c : void 0;
2168
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
2371
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
2169
2372
  }
2170
2373
  if (isObject(a) && isString(a.id)) {
2171
2374
  if (a.id === "")
2172
2375
  throw new Error("The id can't be empty");
2173
2376
  const columns = isStringArray(b) ? b : void 0;
2174
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
2377
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
2175
2378
  }
2176
2379
  if (isObject(a)) {
2177
2380
  const columns = isStringArray(b) ? b : void 0;
@@ -2246,19 +2449,29 @@ class RestRepository extends Query {
2246
2449
  if (Array.isArray(a)) {
2247
2450
  if (a.length === 0)
2248
2451
  return [];
2249
- if (a.length > 100) {
2250
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
2251
- }
2452
+ const existing = await this.read(a, ["id"]);
2453
+ const updates = a.filter((_item, index) => existing[index] !== null);
2454
+ await __privateMethod$2(this, _updateRecords, updateRecords_fn).call(this, updates, {
2455
+ ifVersion,
2456
+ upsert: false
2457
+ });
2252
2458
  const columns = isStringArray(b) ? b : ["*"];
2253
- return Promise.all(a.map((object) => this.update(object, columns)));
2254
- }
2255
- if (isString(a) && isObject(b)) {
2256
- const columns = isStringArray(c) ? c : void 0;
2257
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2459
+ const result = await this.read(a, columns);
2460
+ return result;
2258
2461
  }
2259
- if (isObject(a) && isString(a.id)) {
2260
- const columns = isStringArray(b) ? b : void 0;
2261
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
2462
+ try {
2463
+ if (isString(a) && isObject(b)) {
2464
+ const columns = isStringArray(c) ? c : void 0;
2465
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2466
+ }
2467
+ if (isObject(a) && isString(a.id)) {
2468
+ const columns = isStringArray(b) ? b : void 0;
2469
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
2470
+ }
2471
+ } catch (error) {
2472
+ if (error.status === 422)
2473
+ return null;
2474
+ throw error;
2262
2475
  }
2263
2476
  throw new Error("Invalid arguments for update method");
2264
2477
  });
@@ -2288,11 +2501,13 @@ class RestRepository extends Query {
2288
2501
  if (Array.isArray(a)) {
2289
2502
  if (a.length === 0)
2290
2503
  return [];
2291
- if (a.length > 100) {
2292
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
2293
- }
2504
+ await __privateMethod$2(this, _updateRecords, updateRecords_fn).call(this, a, {
2505
+ ifVersion,
2506
+ upsert: true
2507
+ });
2294
2508
  const columns = isStringArray(b) ? b : ["*"];
2295
- return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
2509
+ const result = await this.read(a, columns);
2510
+ return result;
2296
2511
  }
2297
2512
  if (isString(a) && isObject(b)) {
2298
2513
  const columns = isStringArray(c) ? c : void 0;
@@ -2311,8 +2526,10 @@ class RestRepository extends Query {
2311
2526
  if (Array.isArray(a)) {
2312
2527
  if (a.length === 0)
2313
2528
  return [];
2529
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: false });
2314
2530
  const columns = isStringArray(b) ? b : ["*"];
2315
- return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
2531
+ const result = await this.read(ids, columns);
2532
+ return result;
2316
2533
  }
2317
2534
  if (isString(a) && isObject(b)) {
2318
2535
  const columns = isStringArray(c) ? c : void 0;
@@ -2330,10 +2547,17 @@ class RestRepository extends Query {
2330
2547
  if (Array.isArray(a)) {
2331
2548
  if (a.length === 0)
2332
2549
  return [];
2333
- if (a.length > 100) {
2334
- console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
2335
- }
2336
- return Promise.all(a.map((id) => this.delete(id, b)));
2550
+ const ids = a.map((o) => {
2551
+ if (isString(o))
2552
+ return o;
2553
+ if (isString(o.id))
2554
+ return o.id;
2555
+ throw new Error("Invalid arguments for delete method");
2556
+ });
2557
+ const columns = isStringArray(b) ? b : ["*"];
2558
+ const result = await this.read(a, columns);
2559
+ await __privateMethod$2(this, _deleteRecords, deleteRecords_fn).call(this, ids);
2560
+ return result;
2337
2561
  }
2338
2562
  if (isString(a)) {
2339
2563
  return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
@@ -2378,7 +2602,9 @@ class RestRepository extends Query {
2378
2602
  prefix: options.prefix,
2379
2603
  highlight: options.highlight,
2380
2604
  filter: options.filter,
2381
- boosters: options.boosters
2605
+ boosters: options.boosters,
2606
+ page: options.page,
2607
+ target: options.target
2382
2608
  },
2383
2609
  ...fetchProps
2384
2610
  });
@@ -2420,8 +2646,10 @@ class RestRepository extends Query {
2420
2646
  filter: cleanFilter(data.filter),
2421
2647
  sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2422
2648
  page: data.pagination,
2423
- columns: data.columns ?? ["*"]
2649
+ columns: data.columns ?? ["*"],
2650
+ consistency: data.consistency
2424
2651
  },
2652
+ fetchOptions: data.fetchOptions,
2425
2653
  ...fetchProps
2426
2654
  });
2427
2655
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
@@ -2447,6 +2675,7 @@ class RestRepository extends Query {
2447
2675
  filter: cleanFilter(data.filter),
2448
2676
  sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2449
2677
  columns: data.columns,
2678
+ consistency: data.consistency,
2450
2679
  page: data.pagination?.size !== void 0 ? { size: data.pagination?.size } : void 0,
2451
2680
  summaries,
2452
2681
  summariesFilter
@@ -2500,31 +2729,40 @@ insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { crea
2500
2729
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2501
2730
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2502
2731
  };
2503
- _bulkInsertTableRecords = new WeakSet();
2504
- bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
2732
+ _insertRecords = new WeakSet();
2733
+ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2505
2734
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2506
- const records = objects.map((object) => transformObjectLinks(object));
2507
- const response = await bulkInsertTableRecords({
2508
- pathParams: {
2509
- workspace: "{workspaceId}",
2510
- dbBranchName: "{dbBranch}",
2511
- region: "{region}",
2512
- tableName: __privateGet$4(this, _table)
2513
- },
2514
- queryParams: { columns },
2515
- body: { records },
2516
- ...fetchProps
2517
- });
2518
- if (!isResponseWithRecords(response)) {
2519
- throw new Error("Request included columns but server didn't include them");
2735
+ const chunkedOperations = chunk(
2736
+ objects.map((object) => ({
2737
+ insert: { table: __privateGet$4(this, _table), record: transformObjectLinks(object), createOnly, ifVersion }
2738
+ })),
2739
+ BULK_OPERATION_MAX_SIZE
2740
+ );
2741
+ const ids = [];
2742
+ for (const operations of chunkedOperations) {
2743
+ const { results } = await branchTransaction({
2744
+ pathParams: {
2745
+ workspace: "{workspaceId}",
2746
+ dbBranchName: "{dbBranch}",
2747
+ region: "{region}"
2748
+ },
2749
+ body: { operations },
2750
+ ...fetchProps
2751
+ });
2752
+ for (const result of results) {
2753
+ if (result.operation === "insert") {
2754
+ ids.push(result.id);
2755
+ } else {
2756
+ ids.push(null);
2757
+ }
2758
+ }
2520
2759
  }
2521
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2522
- return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, columns));
2760
+ return ids;
2523
2761
  };
2524
2762
  _updateRecordWithID = new WeakSet();
2525
2763
  updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2526
2764
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2527
- const record = transformObjectLinks(object);
2765
+ const { id: _id, ...record } = transformObjectLinks(object);
2528
2766
  try {
2529
2767
  const response = await updateRecordWithID({
2530
2768
  pathParams: {
@@ -2547,6 +2785,36 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2547
2785
  throw e;
2548
2786
  }
2549
2787
  };
2788
+ _updateRecords = new WeakSet();
2789
+ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2790
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2791
+ const chunkedOperations = chunk(
2792
+ objects.map(({ id, ...object }) => ({
2793
+ update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields: transformObjectLinks(object) }
2794
+ })),
2795
+ BULK_OPERATION_MAX_SIZE
2796
+ );
2797
+ const ids = [];
2798
+ for (const operations of chunkedOperations) {
2799
+ const { results } = await branchTransaction({
2800
+ pathParams: {
2801
+ workspace: "{workspaceId}",
2802
+ dbBranchName: "{dbBranch}",
2803
+ region: "{region}"
2804
+ },
2805
+ body: { operations },
2806
+ ...fetchProps
2807
+ });
2808
+ for (const result of results) {
2809
+ if (result.operation === "update") {
2810
+ ids.push(result.id);
2811
+ } else {
2812
+ ids.push(null);
2813
+ }
2814
+ }
2815
+ }
2816
+ return ids;
2817
+ };
2550
2818
  _upsertRecordWithID = new WeakSet();
2551
2819
  upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2552
2820
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
@@ -2589,6 +2857,25 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2589
2857
  throw e;
2590
2858
  }
2591
2859
  };
2860
+ _deleteRecords = new WeakSet();
2861
+ deleteRecords_fn = async function(recordIds) {
2862
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2863
+ const chunkedOperations = chunk(
2864
+ recordIds.map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
2865
+ BULK_OPERATION_MAX_SIZE
2866
+ );
2867
+ for (const operations of chunkedOperations) {
2868
+ await branchTransaction({
2869
+ pathParams: {
2870
+ workspace: "{workspaceId}",
2871
+ dbBranchName: "{dbBranch}",
2872
+ region: "{region}"
2873
+ },
2874
+ body: { operations },
2875
+ ...fetchProps
2876
+ });
2877
+ }
2878
+ };
2592
2879
  _setCacheQuery = new WeakSet();
2593
2880
  setCacheQuery_fn = async function(query, meta, records) {
2594
2881
  await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
@@ -2625,23 +2912,23 @@ const transformObjectLinks = (object) => {
2625
2912
  }, {});
2626
2913
  };
2627
2914
  const initObject = (db, schemaTables, table, object, selectedColumns) => {
2628
- const result = {};
2915
+ const data = {};
2629
2916
  const { xata, ...rest } = object ?? {};
2630
- Object.assign(result, rest);
2917
+ Object.assign(data, rest);
2631
2918
  const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
2632
2919
  if (!columns)
2633
2920
  console.error(`Table ${table} not found in schema`);
2634
2921
  for (const column of columns ?? []) {
2635
2922
  if (!isValidColumn(selectedColumns, column))
2636
2923
  continue;
2637
- const value = result[column.name];
2924
+ const value = data[column.name];
2638
2925
  switch (column.type) {
2639
2926
  case "datetime": {
2640
- const date = value !== void 0 ? new Date(value) : void 0;
2641
- if (date && isNaN(date.getTime())) {
2927
+ const date = value !== void 0 ? new Date(value) : null;
2928
+ if (date !== null && isNaN(date.getTime())) {
2642
2929
  console.error(`Failed to parse date ${value} for field ${column.name}`);
2643
- } else if (date) {
2644
- result[column.name] = date;
2930
+ } else {
2931
+ data[column.name] = date;
2645
2932
  }
2646
2933
  break;
2647
2934
  }
@@ -2660,41 +2947,52 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
2660
2947
  }
2661
2948
  return acc;
2662
2949
  }, []);
2663
- result[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
2950
+ data[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
2664
2951
  } else {
2665
- result[column.name] = null;
2952
+ data[column.name] = null;
2666
2953
  }
2667
2954
  break;
2668
2955
  }
2669
2956
  default:
2670
- result[column.name] = value ?? null;
2957
+ data[column.name] = value ?? null;
2671
2958
  if (column.notNull === true && value === null) {
2672
2959
  console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
2673
2960
  }
2674
2961
  break;
2675
2962
  }
2676
2963
  }
2677
- result.read = function(columns2) {
2678
- return db[table].read(result["id"], columns2);
2964
+ const record = { ...data };
2965
+ record.read = function(columns2) {
2966
+ return db[table].read(record["id"], columns2);
2967
+ };
2968
+ record.update = function(data2, b, c) {
2969
+ const columns2 = isStringArray(b) ? b : ["*"];
2970
+ const ifVersion = parseIfVersion(b, c);
2971
+ return db[table].update(record["id"], data2, columns2, { ifVersion });
2679
2972
  };
2680
- result.update = function(data, columns2) {
2681
- return db[table].update(result["id"], data, columns2);
2973
+ record.replace = function(data2, b, c) {
2974
+ const columns2 = isStringArray(b) ? b : ["*"];
2975
+ const ifVersion = parseIfVersion(b, c);
2976
+ return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
2682
2977
  };
2683
- result.delete = function() {
2684
- return db[table].delete(result["id"]);
2978
+ record.delete = function() {
2979
+ return db[table].delete(record["id"]);
2685
2980
  };
2686
- result.getMetadata = function() {
2981
+ record.getMetadata = function() {
2687
2982
  return xata;
2688
2983
  };
2689
- for (const prop of ["read", "update", "delete", "getMetadata"]) {
2690
- Object.defineProperty(result, prop, { enumerable: false });
2984
+ record.toSerializable = function() {
2985
+ return JSON.parse(JSON.stringify(transformObjectLinks(data)));
2986
+ };
2987
+ record.toString = function() {
2988
+ return JSON.stringify(transformObjectLinks(data));
2989
+ };
2990
+ for (const prop of ["read", "update", "replace", "delete", "getMetadata", "toSerializable", "toString"]) {
2991
+ Object.defineProperty(record, prop, { enumerable: false });
2691
2992
  }
2692
- Object.freeze(result);
2693
- return result;
2993
+ Object.freeze(record);
2994
+ return record;
2694
2995
  };
2695
- function isResponseWithRecords(value) {
2696
- return isObject(value) && Array.isArray(value.records);
2697
- }
2698
2996
  function extractId(value) {
2699
2997
  if (isString(value))
2700
2998
  return value;
@@ -2904,10 +3202,10 @@ _schemaTables = new WeakMap();
2904
3202
  _search = new WeakSet();
2905
3203
  search_fn = async function(query, options, getFetchProps) {
2906
3204
  const fetchProps = await getFetchProps();
2907
- const { tables, fuzziness, highlight, prefix } = options ?? {};
3205
+ const { tables, fuzziness, highlight, prefix, page } = options ?? {};
2908
3206
  const { records } = await searchBranch({
2909
3207
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
2910
- body: { tables, query, fuzziness, prefix, highlight },
3208
+ body: { tables, query, fuzziness, prefix, highlight, page },
2911
3209
  ...fetchProps
2912
3210
  });
2913
3211
  return records;
@@ -2925,18 +3223,30 @@ getSchemaTables_fn = async function(getFetchProps) {
2925
3223
  return schema.tables;
2926
3224
  };
2927
3225
 
3226
+ class TransactionPlugin extends XataPlugin {
3227
+ build({ getFetchProps }) {
3228
+ return {
3229
+ run: async (operations) => {
3230
+ const fetchProps = await getFetchProps();
3231
+ const response = await branchTransaction({
3232
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3233
+ body: { operations },
3234
+ ...fetchProps
3235
+ });
3236
+ return response;
3237
+ }
3238
+ };
3239
+ }
3240
+ }
3241
+
2928
3242
  const isBranchStrategyBuilder = (strategy) => {
2929
3243
  return typeof strategy === "function";
2930
3244
  };
2931
3245
 
2932
3246
  async function getCurrentBranchName(options) {
2933
3247
  const { branch, envBranch } = getEnvironment();
2934
- if (branch) {
2935
- const details = await getDatabaseBranch(branch, options);
2936
- if (details)
2937
- return branch;
2938
- console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
2939
- }
3248
+ if (branch)
3249
+ return branch;
2940
3250
  const gitBranch = envBranch || await getGitBranch();
2941
3251
  return resolveXataBranch(gitBranch, options);
2942
3252
  }
@@ -2968,7 +3278,9 @@ async function resolveXataBranch(gitBranch, options) {
2968
3278
  workspacesApiUrl: `${protocol}//${host}`,
2969
3279
  pathParams: { dbName, workspace, region },
2970
3280
  queryParams: { gitBranch, fallbackBranch },
2971
- trace: defaultTrace
3281
+ trace: defaultTrace,
3282
+ clientName: options?.clientName,
3283
+ xataAgentExtra: options?.xataAgentExtra
2972
3284
  });
2973
3285
  return branch;
2974
3286
  }
@@ -3052,8 +3364,10 @@ const buildClient = (plugins) => {
3052
3364
  };
3053
3365
  const db = new SchemaPlugin(schemaTables).build(pluginOptions);
3054
3366
  const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
3367
+ const transactions = new TransactionPlugin().build(pluginOptions);
3055
3368
  this.db = db;
3056
3369
  this.search = search;
3370
+ this.transactions = transactions;
3057
3371
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
3058
3372
  if (namespace === void 0)
3059
3373
  continue;
@@ -3073,20 +3387,55 @@ const buildClient = (plugins) => {
3073
3387
  return { databaseURL, branch };
3074
3388
  }
3075
3389
  }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3390
+ const enableBrowser = options?.enableBrowser ?? getEnableBrowserVariable() ?? false;
3391
+ const isBrowser = typeof window !== "undefined" && typeof Deno === "undefined";
3392
+ if (isBrowser && !enableBrowser) {
3393
+ throw new Error(
3394
+ "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."
3395
+ );
3396
+ }
3076
3397
  const fetch = getFetchImplementation(options?.fetch);
3077
3398
  const databaseURL = options?.databaseURL || getDatabaseURL();
3078
3399
  const apiKey = options?.apiKey || getAPIKey();
3079
3400
  const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
3080
3401
  const trace = options?.trace ?? defaultTrace;
3081
- const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
3402
+ const clientName = options?.clientName;
3403
+ const xataAgentExtra = options?.xataAgentExtra;
3404
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({
3405
+ apiKey,
3406
+ databaseURL,
3407
+ fetchImpl: options?.fetch,
3408
+ clientName,
3409
+ xataAgentExtra
3410
+ });
3082
3411
  if (!apiKey) {
3083
3412
  throw new Error("Option apiKey is required");
3084
3413
  }
3085
3414
  if (!databaseURL) {
3086
3415
  throw new Error("Option databaseURL is required");
3087
3416
  }
3088
- return { fetch, databaseURL, apiKey, branch, cache, trace, clientID: generateUUID() };
3089
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace, clientID }) {
3417
+ return {
3418
+ fetch,
3419
+ databaseURL,
3420
+ apiKey,
3421
+ branch,
3422
+ cache,
3423
+ trace,
3424
+ clientID: generateUUID(),
3425
+ enableBrowser,
3426
+ clientName,
3427
+ xataAgentExtra
3428
+ };
3429
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
3430
+ fetch,
3431
+ apiKey,
3432
+ databaseURL,
3433
+ branch,
3434
+ trace,
3435
+ clientID,
3436
+ clientName,
3437
+ xataAgentExtra
3438
+ }) {
3090
3439
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
3091
3440
  if (!branchValue)
3092
3441
  throw new Error("Unable to resolve branch value");
@@ -3100,7 +3449,9 @@ const buildClient = (plugins) => {
3100
3449
  return databaseURL + newPath;
3101
3450
  },
3102
3451
  trace,
3103
- clientID
3452
+ clientID,
3453
+ clientName,
3454
+ xataAgentExtra
3104
3455
  };
3105
3456
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
3106
3457
  if (__privateGet(this, _branch))
@@ -3191,7 +3542,7 @@ const deserialize = (json) => {
3191
3542
  };
3192
3543
 
3193
3544
  function buildWorkerRunner(config) {
3194
- return function xataWorker(name, _worker) {
3545
+ return function xataWorker(name, worker) {
3195
3546
  return async (...args) => {
3196
3547
  const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
3197
3548
  const result = await fetch(url, {
@@ -3212,5 +3563,5 @@ class XataError extends Error {
3212
3563
  }
3213
3564
  }
3214
3565
 
3215
- 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, cPCreateDatabase, cPDeleteDatabase, cPGetCPDatabaseMetadata, cPGetDatabaseList, cPUpdateCPDatabaseMetadata, 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 };
3566
+ export { BaseClient, FetcherError, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, Serializer, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, aggregateTable, applyBranchSchemaEdit, branchTransaction, buildClient, buildWorkerRunner, bulkInsertTableRecords, cancelWorkspaceMemberInvite, compareBranchSchemas, compareBranchWithUserSchema, compareMigrationRequest, contains, createBranch, createDatabase, createMigrationRequest, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteDatabaseGithubSettings, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, deserialize, endsWith, equals, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchSchemaHistory, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseGithubSettings, getDatabaseList, getDatabaseMetadata, getDatabaseURL, getGitBranchesMapping, getHostUrl, getMigrationRequest, getMigrationRequestIsMerged, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, greaterEquals, greaterThan, greaterThanEquals, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isHostProviderAlias, isHostProviderBuilder, isIdentifiable, isNot, isXataRecord, le, lessEquals, lessThan, lessThanEquals, listMigrationRequestsCommits, listRegions, lt, lte, mergeMigrationRequest, notExists, operationsByTag, parseProviderString, parseWorkspacesUrlParts, pattern, previewBranchSchemaEdit, queryMigrationRequests, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, serialize, setTableSchema, startsWith, summarizeTable, updateBranchMetadata, updateBranchSchema, updateColumn, updateDatabaseGithubSettings, updateDatabaseMetadata, updateMigrationRequest, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID };
3216
3567
  //# sourceMappingURL=index.mjs.map