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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,7 +1,8 @@
1
1
  'use strict';
2
2
 
3
- const defaultTrace = async (_name, fn, _options) => {
3
+ const defaultTrace = async (name, fn, _options) => {
4
4
  return await fn({
5
+ name,
5
6
  setAttributes: () => {
6
7
  return;
7
8
  }
@@ -43,6 +44,18 @@ function isStringArray(value) {
43
44
  function isNumber(value) {
44
45
  return isDefined(value) && typeof value === "number";
45
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
+ }
46
59
  function toBase64(value) {
47
60
  try {
48
61
  return btoa(value);
@@ -62,10 +75,20 @@ function deepMerge(a, b) {
62
75
  }
63
76
  return result;
64
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
+ }
65
88
 
66
89
  function getEnvironment() {
67
90
  try {
68
- if (isObject(process) && isObject(process.env)) {
91
+ if (isDefined(process) && isDefined(process.env)) {
69
92
  return {
70
93
  apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
71
94
  databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
@@ -152,8 +175,6 @@ async function getGitBranch() {
152
175
  if (typeof require === "function") {
153
176
  return require(nodeModule).execSync(fullCmd, execOptions).trim();
154
177
  }
155
- const { execSync } = await import(nodeModule);
156
- return execSync(fullCmd, execOptions).toString().trim();
157
178
  } catch (err) {
158
179
  }
159
180
  try {
@@ -174,6 +195,29 @@ function getAPIKey() {
174
195
  }
175
196
  }
176
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;
177
221
  function getFetchImplementation(userFetch) {
178
222
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
179
223
  const fetchImpl = userFetch ?? globalFetch;
@@ -184,8 +228,81 @@ function getFetchImplementation(userFetch) {
184
228
  }
185
229
  return fetchImpl;
186
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
+ }
187
304
 
188
- const VERSION = "0.0.0-alpha.vff4bc47";
305
+ const VERSION = "0.21.6";
189
306
 
190
307
  class ErrorWithCause extends Error {
191
308
  constructor(message, options) {
@@ -196,7 +313,7 @@ class FetcherError extends ErrorWithCause {
196
313
  constructor(status, data, requestId) {
197
314
  super(getMessage(data));
198
315
  this.status = status;
199
- this.errors = isBulkError(data) ? data.errors : void 0;
316
+ this.errors = isBulkError(data) ? data.errors : [{ message: getMessage(data), status }];
200
317
  this.requestId = requestId;
201
318
  if (data instanceof Error) {
202
319
  this.stack = data.stack;
@@ -228,6 +345,7 @@ function getMessage(data) {
228
345
  }
229
346
  }
230
347
 
348
+ const pool = new ApiRequestPool();
231
349
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
232
350
  const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
233
351
  if (value === void 0 || value === null)
@@ -260,11 +378,12 @@ function hostHeader(url) {
260
378
  const { groups } = pattern.exec(url) ?? {};
261
379
  return groups?.host ? { Host: groups.host } : {};
262
380
  }
381
+ const defaultClientID = generateUUID();
263
382
  async function fetch$1({
264
383
  url: path,
265
384
  method,
266
385
  body,
267
- headers,
386
+ headers: customHeaders,
268
387
  pathParams,
269
388
  queryParams,
270
389
  fetchImpl,
@@ -276,9 +395,11 @@ async function fetch$1({
276
395
  signal,
277
396
  clientID,
278
397
  sessionID,
398
+ clientName,
279
399
  fetchOptions = {}
280
400
  }) {
281
- return trace(
401
+ pool.setFetch(fetchImpl);
402
+ return await trace(
282
403
  `${method.toUpperCase()} ${path}`,
283
404
  async ({ setAttributes }) => {
284
405
  const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
@@ -288,24 +409,28 @@ async function fetch$1({
288
409
  [TraceAttributes.HTTP_URL]: url,
289
410
  [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
290
411
  });
291
- const response = await fetchImpl(url, {
412
+ const xataAgent = compact([
413
+ ["client", "TS_SDK"],
414
+ ["version", VERSION],
415
+ isDefined(clientName) ? ["service", clientName] : void 0
416
+ ]).map(([key, value]) => `${key}=${value}`).join("; ");
417
+ const headers = {
418
+ "Accept-Encoding": "identity",
419
+ "Content-Type": "application/json",
420
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
421
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
422
+ "X-Xata-Agent": xataAgent,
423
+ ...customHeaders,
424
+ ...hostHeader(fullUrl),
425
+ Authorization: `Bearer ${apiKey}`
426
+ };
427
+ const response = await pool.request(url, {
292
428
  ...fetchOptions,
293
429
  method: method.toUpperCase(),
294
430
  body: body ? JSON.stringify(body) : void 0,
295
- headers: {
296
- "Content-Type": "application/json",
297
- "User-Agent": `Xata client-ts/${VERSION}`,
298
- "X-Xata-Client-ID": clientID ?? "",
299
- "X-Xata-Session-ID": sessionID ?? "",
300
- ...headers,
301
- ...hostHeader(fullUrl),
302
- Authorization: `Bearer ${apiKey}`
303
- },
431
+ headers,
304
432
  signal
305
433
  });
306
- if (response.status === 204) {
307
- return {};
308
- }
309
434
  const { host, protocol } = parseUrl(response.url);
310
435
  const requestId = response.headers?.get("x-request-id") ?? void 0;
311
436
  setAttributes({
@@ -315,6 +440,12 @@ async function fetch$1({
315
440
  [TraceAttributes.HTTP_HOST]: host,
316
441
  [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
317
442
  });
443
+ if (response.status === 204) {
444
+ return {};
445
+ }
446
+ if (response.status === 429) {
447
+ throw new FetcherError(response.status, "Rate limit exceeded", requestId);
448
+ }
318
449
  try {
319
450
  const jsonResponse = await response.json();
320
451
  if (response.ok) {
@@ -339,17 +470,12 @@ function parseUrl(url) {
339
470
 
340
471
  const dataPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "dataPlane" });
341
472
 
342
- const dEPRECATEDgetDatabaseList = (variables, signal) => dataPlaneFetch({ url: "/dbs", method: "get", ...variables, signal });
343
473
  const getBranchList = (variables, signal) => dataPlaneFetch({
344
474
  url: "/dbs/{dbName}",
345
475
  method: "get",
346
476
  ...variables,
347
477
  signal
348
478
  });
349
- const dEPRECATEDcreateDatabase = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}", method: "put", ...variables, signal });
350
- const dEPRECATEDdeleteDatabase = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}", method: "delete", ...variables, signal });
351
- const dEPRECATEDgetDatabaseMetadata = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/metadata", method: "get", ...variables, signal });
352
- const dEPRECATEDupdateDatabaseMetadata = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/metadata", method: "patch", ...variables, signal });
353
479
  const getBranchDetails = (variables, signal) => dataPlaneFetch({
354
480
  url: "/db/{dbBranchName}",
355
481
  method: "get",
@@ -488,13 +614,6 @@ const searchTable = (variables, signal) => dataPlaneFetch({
488
614
  const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
489
615
  const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
490
616
  const operationsByTag$2 = {
491
- database: {
492
- dEPRECATEDgetDatabaseList,
493
- dEPRECATEDcreateDatabase,
494
- dEPRECATEDdeleteDatabase,
495
- dEPRECATEDgetDatabaseMetadata,
496
- dEPRECATEDupdateDatabaseMetadata
497
- },
498
617
  branch: {
499
618
  getBranchList,
500
619
  getBranchDetails,
@@ -724,12 +843,12 @@ function parseProviderString(provider = "production") {
724
843
  function parseWorkspacesUrlParts(url) {
725
844
  if (!isString(url))
726
845
  return null;
727
- const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))?\.xata\.sh.*/;
728
- const regexStaging = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))?\.xatabase\.co.*/;
846
+ const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/;
847
+ const regexStaging = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))\.xatabase\.co.*/;
729
848
  const match = url.match(regex) || url.match(regexStaging);
730
849
  if (!match)
731
850
  return null;
732
- return { workspace: match[1], region: match[2] ?? "eu-west-1" };
851
+ return { workspace: match[1], region: match[2] };
733
852
  }
734
853
 
735
854
  var __accessCheck$7 = (obj, member, msg) => {
@@ -758,6 +877,7 @@ class XataApiClient {
758
877
  const provider = options.host ?? "production";
759
878
  const apiKey = options.apiKey ?? getAPIKey();
760
879
  const trace = options.trace ?? defaultTrace;
880
+ const clientID = generateUUID();
761
881
  if (!apiKey) {
762
882
  throw new Error("Could not resolve a valid apiKey");
763
883
  }
@@ -766,7 +886,9 @@ class XataApiClient {
766
886
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
767
887
  fetchImpl: getFetchImplementation(options.fetch),
768
888
  apiKey,
769
- trace
889
+ trace,
890
+ clientName: options.clientName,
891
+ clientID
770
892
  });
771
893
  }
772
894
  get user() {
@@ -1771,13 +1893,6 @@ class XataApiPlugin {
1771
1893
  class XataPlugin {
1772
1894
  }
1773
1895
 
1774
- function generateUUID() {
1775
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
1776
- const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
1777
- return v.toString(16);
1778
- });
1779
- }
1780
-
1781
1896
  function cleanFilter(filter) {
1782
1897
  if (!filter)
1783
1898
  return void 0;
@@ -1925,6 +2040,7 @@ const _Query = class {
1925
2040
  __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1926
2041
  __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1927
2042
  __privateGet$5(this, _data).columns = data.columns ?? parent?.columns;
2043
+ __privateGet$5(this, _data).consistency = data.consistency ?? parent?.consistency;
1928
2044
  __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1929
2045
  __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
1930
2046
  __privateGet$5(this, _data).fetchOptions = data.fetchOptions ?? parent?.fetchOptions;
@@ -2146,7 +2262,8 @@ var __privateMethod$2 = (obj, member, method) => {
2146
2262
  __accessCheck$4(obj, member, "access private method");
2147
2263
  return method;
2148
2264
  };
2149
- var _table, _getFetchProps, _db, _cache, _schemaTables$2, _trace, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_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;
2265
+ 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;
2266
+ const BULK_OPERATION_MAX_SIZE = 1e3;
2150
2267
  class Repository extends Query {
2151
2268
  }
2152
2269
  class RestRepository extends Query {
@@ -2158,7 +2275,7 @@ class RestRepository extends Query {
2158
2275
  );
2159
2276
  __privateAdd$4(this, _insertRecordWithoutId);
2160
2277
  __privateAdd$4(this, _insertRecordWithId);
2161
- __privateAdd$4(this, _bulkInsertTableRecords);
2278
+ __privateAdd$4(this, _insertRecords);
2162
2279
  __privateAdd$4(this, _updateRecordWithID);
2163
2280
  __privateAdd$4(this, _updateRecords);
2164
2281
  __privateAdd$4(this, _upsertRecordWithID);
@@ -2197,20 +2314,22 @@ class RestRepository extends Query {
2197
2314
  if (Array.isArray(a)) {
2198
2315
  if (a.length === 0)
2199
2316
  return [];
2200
- const columns = isStringArray(b) ? b : void 0;
2201
- return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
2317
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: true });
2318
+ const columns = isStringArray(b) ? b : ["*"];
2319
+ const result = await this.read(ids, columns);
2320
+ return result;
2202
2321
  }
2203
2322
  if (isString(a) && isObject(b)) {
2204
2323
  if (a === "")
2205
2324
  throw new Error("The id can't be empty");
2206
2325
  const columns = isStringArray(c) ? c : void 0;
2207
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
2326
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
2208
2327
  }
2209
2328
  if (isObject(a) && isString(a.id)) {
2210
2329
  if (a.id === "")
2211
2330
  throw new Error("The id can't be empty");
2212
2331
  const columns = isStringArray(b) ? b : void 0;
2213
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
2332
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
2214
2333
  }
2215
2334
  if (isObject(a)) {
2216
2335
  const columns = isStringArray(b) ? b : void 0;
@@ -2295,13 +2414,19 @@ class RestRepository extends Query {
2295
2414
  const result = await this.read(a, columns);
2296
2415
  return result;
2297
2416
  }
2298
- if (isString(a) && isObject(b)) {
2299
- const columns = isStringArray(c) ? c : void 0;
2300
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2301
- }
2302
- if (isObject(a) && isString(a.id)) {
2303
- const columns = isStringArray(b) ? b : void 0;
2304
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
2417
+ try {
2418
+ if (isString(a) && isObject(b)) {
2419
+ const columns = isStringArray(c) ? c : void 0;
2420
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2421
+ }
2422
+ if (isObject(a) && isString(a.id)) {
2423
+ const columns = isStringArray(b) ? b : void 0;
2424
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
2425
+ }
2426
+ } catch (error) {
2427
+ if (error.status === 422)
2428
+ return null;
2429
+ throw error;
2305
2430
  }
2306
2431
  throw new Error("Invalid arguments for update method");
2307
2432
  });
@@ -2356,8 +2481,10 @@ class RestRepository extends Query {
2356
2481
  if (Array.isArray(a)) {
2357
2482
  if (a.length === 0)
2358
2483
  return [];
2484
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: false });
2359
2485
  const columns = isStringArray(b) ? b : ["*"];
2360
- return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
2486
+ const result = await this.read(ids, columns);
2487
+ return result;
2361
2488
  }
2362
2489
  if (isString(a) && isObject(b)) {
2363
2490
  const columns = isStringArray(c) ? c : void 0;
@@ -2430,7 +2557,9 @@ class RestRepository extends Query {
2430
2557
  prefix: options.prefix,
2431
2558
  highlight: options.highlight,
2432
2559
  filter: options.filter,
2433
- boosters: options.boosters
2560
+ boosters: options.boosters,
2561
+ page: options.page,
2562
+ target: options.target
2434
2563
  },
2435
2564
  ...fetchProps
2436
2565
  });
@@ -2472,7 +2601,8 @@ class RestRepository extends Query {
2472
2601
  filter: cleanFilter(data.filter),
2473
2602
  sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2474
2603
  page: data.pagination,
2475
- columns: data.columns ?? ["*"]
2604
+ columns: data.columns ?? ["*"],
2605
+ consistency: data.consistency
2476
2606
  },
2477
2607
  fetchOptions: data.fetchOptions,
2478
2608
  ...fetchProps
@@ -2500,6 +2630,7 @@ class RestRepository extends Query {
2500
2630
  filter: cleanFilter(data.filter),
2501
2631
  sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2502
2632
  columns: data.columns,
2633
+ consistency: data.consistency,
2503
2634
  page: data.pagination?.size !== void 0 ? { size: data.pagination?.size } : void 0,
2504
2635
  summaries,
2505
2636
  summariesFilter
@@ -2553,31 +2684,40 @@ insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { crea
2553
2684
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2554
2685
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2555
2686
  };
2556
- _bulkInsertTableRecords = new WeakSet();
2557
- bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
2687
+ _insertRecords = new WeakSet();
2688
+ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2558
2689
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2559
- const records = objects.map((object) => transformObjectLinks(object));
2560
- const response = await bulkInsertTableRecords({
2561
- pathParams: {
2562
- workspace: "{workspaceId}",
2563
- dbBranchName: "{dbBranch}",
2564
- region: "{region}",
2565
- tableName: __privateGet$4(this, _table)
2566
- },
2567
- queryParams: { columns },
2568
- body: { records },
2569
- ...fetchProps
2570
- });
2571
- if (!isResponseWithRecords(response)) {
2572
- throw new Error("Request included columns but server didn't include them");
2690
+ const chunkedOperations = chunk(
2691
+ objects.map((object) => ({
2692
+ insert: { table: __privateGet$4(this, _table), record: transformObjectLinks(object), createOnly, ifVersion }
2693
+ })),
2694
+ BULK_OPERATION_MAX_SIZE
2695
+ );
2696
+ const ids = [];
2697
+ for (const operations of chunkedOperations) {
2698
+ const { results } = await branchTransaction({
2699
+ pathParams: {
2700
+ workspace: "{workspaceId}",
2701
+ dbBranchName: "{dbBranch}",
2702
+ region: "{region}"
2703
+ },
2704
+ body: { operations },
2705
+ ...fetchProps
2706
+ });
2707
+ for (const result of results) {
2708
+ if (result.operation === "insert") {
2709
+ ids.push(result.id);
2710
+ } else {
2711
+ ids.push(null);
2712
+ }
2713
+ }
2573
2714
  }
2574
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2575
- return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, columns));
2715
+ return ids;
2576
2716
  };
2577
2717
  _updateRecordWithID = new WeakSet();
2578
2718
  updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2579
2719
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2580
- const record = transformObjectLinks(object);
2720
+ const { id: _id, ...record } = transformObjectLinks(object);
2581
2721
  try {
2582
2722
  const response = await updateRecordWithID({
2583
2723
  pathParams: {
@@ -2597,24 +2737,38 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2597
2737
  if (isObject(e) && e.status === 404) {
2598
2738
  return null;
2599
2739
  }
2740
+ throw e;
2600
2741
  }
2601
2742
  };
2602
2743
  _updateRecords = new WeakSet();
2603
2744
  updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2604
2745
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2605
- const operations = objects.map(({ id, ...fields }) => ({
2606
- update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields }
2607
- }));
2608
- const { results } = await branchTransaction({
2609
- pathParams: {
2610
- workspace: "{workspaceId}",
2611
- dbBranchName: "{dbBranch}",
2612
- region: "{region}"
2613
- },
2614
- body: { operations },
2615
- ...fetchProps
2616
- });
2617
- return results;
2746
+ const chunkedOperations = chunk(
2747
+ objects.map(({ id, ...object }) => ({
2748
+ update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields: transformObjectLinks(object) }
2749
+ })),
2750
+ BULK_OPERATION_MAX_SIZE
2751
+ );
2752
+ const ids = [];
2753
+ for (const operations of chunkedOperations) {
2754
+ const { results } = await branchTransaction({
2755
+ pathParams: {
2756
+ workspace: "{workspaceId}",
2757
+ dbBranchName: "{dbBranch}",
2758
+ region: "{region}"
2759
+ },
2760
+ body: { operations },
2761
+ ...fetchProps
2762
+ });
2763
+ for (const result of results) {
2764
+ if (result.operation === "update") {
2765
+ ids.push(result.id);
2766
+ } else {
2767
+ ids.push(null);
2768
+ }
2769
+ }
2770
+ }
2771
+ return ids;
2618
2772
  };
2619
2773
  _upsertRecordWithID = new WeakSet();
2620
2774
  upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
@@ -2661,17 +2815,21 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2661
2815
  _deleteRecords = new WeakSet();
2662
2816
  deleteRecords_fn = async function(recordIds) {
2663
2817
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2664
- const operations = recordIds.map((id) => ({ delete: { table: __privateGet$4(this, _table), id } }));
2665
- const { results } = await branchTransaction({
2666
- pathParams: {
2667
- workspace: "{workspaceId}",
2668
- dbBranchName: "{dbBranch}",
2669
- region: "{region}"
2670
- },
2671
- body: { operations },
2672
- ...fetchProps
2673
- });
2674
- return results;
2818
+ const chunkedOperations = chunk(
2819
+ recordIds.map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
2820
+ BULK_OPERATION_MAX_SIZE
2821
+ );
2822
+ for (const operations of chunkedOperations) {
2823
+ await branchTransaction({
2824
+ pathParams: {
2825
+ workspace: "{workspaceId}",
2826
+ dbBranchName: "{dbBranch}",
2827
+ region: "{region}"
2828
+ },
2829
+ body: { operations },
2830
+ ...fetchProps
2831
+ });
2832
+ }
2675
2833
  };
2676
2834
  _setCacheQuery = new WeakSet();
2677
2835
  setCacheQuery_fn = async function(query, meta, records) {
@@ -2709,23 +2867,23 @@ const transformObjectLinks = (object) => {
2709
2867
  }, {});
2710
2868
  };
2711
2869
  const initObject = (db, schemaTables, table, object, selectedColumns) => {
2712
- const result = {};
2870
+ const data = {};
2713
2871
  const { xata, ...rest } = object ?? {};
2714
- Object.assign(result, rest);
2872
+ Object.assign(data, rest);
2715
2873
  const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
2716
2874
  if (!columns)
2717
2875
  console.error(`Table ${table} not found in schema`);
2718
2876
  for (const column of columns ?? []) {
2719
2877
  if (!isValidColumn(selectedColumns, column))
2720
2878
  continue;
2721
- const value = result[column.name];
2879
+ const value = data[column.name];
2722
2880
  switch (column.type) {
2723
2881
  case "datetime": {
2724
- const date = value !== void 0 ? new Date(value) : void 0;
2725
- if (date && isNaN(date.getTime())) {
2882
+ const date = value !== void 0 ? new Date(value) : null;
2883
+ if (date !== null && isNaN(date.getTime())) {
2726
2884
  console.error(`Failed to parse date ${value} for field ${column.name}`);
2727
- } else if (date) {
2728
- result[column.name] = date;
2885
+ } else {
2886
+ data[column.name] = date;
2729
2887
  }
2730
2888
  break;
2731
2889
  }
@@ -2744,48 +2902,46 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
2744
2902
  }
2745
2903
  return acc;
2746
2904
  }, []);
2747
- result[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
2905
+ data[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
2748
2906
  } else {
2749
- result[column.name] = null;
2907
+ data[column.name] = null;
2750
2908
  }
2751
2909
  break;
2752
2910
  }
2753
2911
  default:
2754
- result[column.name] = value ?? null;
2912
+ data[column.name] = value ?? null;
2755
2913
  if (column.notNull === true && value === null) {
2756
2914
  console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
2757
2915
  }
2758
2916
  break;
2759
2917
  }
2760
2918
  }
2761
- result.read = function(columns2) {
2762
- return db[table].read(result["id"], columns2);
2919
+ const record = { ...data };
2920
+ record.read = function(columns2) {
2921
+ return db[table].read(record["id"], columns2);
2763
2922
  };
2764
- result.update = function(data, b, c) {
2923
+ record.update = function(data2, b, c) {
2765
2924
  const columns2 = isStringArray(b) ? b : ["*"];
2766
2925
  const ifVersion = parseIfVersion(b, c);
2767
- return db[table].update(result["id"], data, columns2, { ifVersion });
2926
+ return db[table].update(record["id"], data2, columns2, { ifVersion });
2768
2927
  };
2769
- result.replace = function(data, b, c) {
2928
+ record.replace = function(data2, b, c) {
2770
2929
  const columns2 = isStringArray(b) ? b : ["*"];
2771
2930
  const ifVersion = parseIfVersion(b, c);
2772
- return db[table].createOrReplace(result["id"], data, columns2, { ifVersion });
2931
+ return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
2773
2932
  };
2774
- result.delete = function() {
2775
- return db[table].delete(result["id"]);
2933
+ record.delete = function() {
2934
+ return db[table].delete(record["id"]);
2776
2935
  };
2777
- result.getMetadata = function() {
2936
+ record.getMetadata = function() {
2778
2937
  return xata;
2779
2938
  };
2780
2939
  for (const prop of ["read", "update", "replace", "delete", "getMetadata"]) {
2781
- Object.defineProperty(result, prop, { enumerable: false });
2940
+ Object.defineProperty(record, prop, { enumerable: false });
2782
2941
  }
2783
- Object.freeze(result);
2784
- return result;
2942
+ Object.freeze(record);
2943
+ return record;
2785
2944
  };
2786
- function isResponseWithRecords(value) {
2787
- return isObject(value) && Array.isArray(value.records);
2788
- }
2789
2945
  function extractId(value) {
2790
2946
  if (isString(value))
2791
2947
  return value;
@@ -2995,10 +3151,10 @@ _schemaTables = new WeakMap();
2995
3151
  _search = new WeakSet();
2996
3152
  search_fn = async function(query, options, getFetchProps) {
2997
3153
  const fetchProps = await getFetchProps();
2998
- const { tables, fuzziness, highlight, prefix } = options ?? {};
3154
+ const { tables, fuzziness, highlight, prefix, page } = options ?? {};
2999
3155
  const { records } = await searchBranch({
3000
3156
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3001
- body: { tables, query, fuzziness, prefix, highlight },
3157
+ body: { tables, query, fuzziness, prefix, highlight, page },
3002
3158
  ...fetchProps
3003
3159
  });
3004
3160
  return records;
@@ -3016,18 +3172,30 @@ getSchemaTables_fn = async function(getFetchProps) {
3016
3172
  return schema.tables;
3017
3173
  };
3018
3174
 
3175
+ class TransactionPlugin extends XataPlugin {
3176
+ build({ getFetchProps }) {
3177
+ return {
3178
+ run: async (operations) => {
3179
+ const fetchProps = await getFetchProps();
3180
+ const response = await branchTransaction({
3181
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3182
+ body: { operations },
3183
+ ...fetchProps
3184
+ });
3185
+ return response;
3186
+ }
3187
+ };
3188
+ }
3189
+ }
3190
+
3019
3191
  const isBranchStrategyBuilder = (strategy) => {
3020
3192
  return typeof strategy === "function";
3021
3193
  };
3022
3194
 
3023
3195
  async function getCurrentBranchName(options) {
3024
3196
  const { branch, envBranch } = getEnvironment();
3025
- if (branch) {
3026
- const details = await getDatabaseBranch(branch, options);
3027
- if (details)
3028
- return branch;
3029
- console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
3030
- }
3197
+ if (branch)
3198
+ return branch;
3031
3199
  const gitBranch = envBranch || await getGitBranch();
3032
3200
  return resolveXataBranch(gitBranch, options);
3033
3201
  }
@@ -3059,7 +3227,8 @@ async function resolveXataBranch(gitBranch, options) {
3059
3227
  workspacesApiUrl: `${protocol}//${host}`,
3060
3228
  pathParams: { dbName, workspace, region },
3061
3229
  queryParams: { gitBranch, fallbackBranch },
3062
- trace: defaultTrace
3230
+ trace: defaultTrace,
3231
+ clientName: options?.clientName
3063
3232
  });
3064
3233
  return branch;
3065
3234
  }
@@ -3143,8 +3312,10 @@ const buildClient = (plugins) => {
3143
3312
  };
3144
3313
  const db = new SchemaPlugin(schemaTables).build(pluginOptions);
3145
3314
  const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
3315
+ const transactions = new TransactionPlugin().build(pluginOptions);
3146
3316
  this.db = db;
3147
3317
  this.search = search;
3318
+ this.transactions = transactions;
3148
3319
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
3149
3320
  if (namespace === void 0)
3150
3321
  continue;
@@ -3165,7 +3336,7 @@ const buildClient = (plugins) => {
3165
3336
  }
3166
3337
  }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3167
3338
  const enableBrowser = options?.enableBrowser ?? getEnableBrowserVariable() ?? false;
3168
- const isBrowser = typeof window !== "undefined";
3339
+ const isBrowser = typeof window !== "undefined" && typeof Deno === "undefined";
3169
3340
  if (isBrowser && !enableBrowser) {
3170
3341
  throw new Error(
3171
3342
  "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."
@@ -3176,15 +3347,29 @@ const buildClient = (plugins) => {
3176
3347
  const apiKey = options?.apiKey || getAPIKey();
3177
3348
  const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
3178
3349
  const trace = options?.trace ?? defaultTrace;
3179
- const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
3350
+ const clientName = options?.clientName;
3351
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({
3352
+ apiKey,
3353
+ databaseURL,
3354
+ fetchImpl: options?.fetch,
3355
+ clientName: options?.clientName
3356
+ });
3180
3357
  if (!apiKey) {
3181
3358
  throw new Error("Option apiKey is required");
3182
3359
  }
3183
3360
  if (!databaseURL) {
3184
3361
  throw new Error("Option databaseURL is required");
3185
3362
  }
3186
- return { fetch, databaseURL, apiKey, branch, cache, trace, clientID: generateUUID(), enableBrowser };
3187
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace, clientID }) {
3363
+ return { fetch, databaseURL, apiKey, branch, cache, trace, clientID: generateUUID(), enableBrowser, clientName };
3364
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
3365
+ fetch,
3366
+ apiKey,
3367
+ databaseURL,
3368
+ branch,
3369
+ trace,
3370
+ clientID,
3371
+ clientName
3372
+ }) {
3188
3373
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
3189
3374
  if (!branchValue)
3190
3375
  throw new Error("Unable to resolve branch value");
@@ -3198,7 +3383,8 @@ const buildClient = (plugins) => {
3198
3383
  return databaseURL + newPath;
3199
3384
  },
3200
3385
  trace,
3201
- clientID
3386
+ clientID,
3387
+ clientName
3202
3388
  };
3203
3389
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
3204
3390
  if (__privateGet(this, _branch))
@@ -3289,7 +3475,7 @@ const deserialize = (json) => {
3289
3475
  };
3290
3476
 
3291
3477
  function buildWorkerRunner(config) {
3292
- return function xataWorker(name, _worker) {
3478
+ return function xataWorker(name, worker) {
3293
3479
  return async (...args) => {
3294
3480
  const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
3295
3481
  const result = await fetch(url, {
@@ -3311,6 +3497,7 @@ class XataError extends Error {
3311
3497
  }
3312
3498
 
3313
3499
  exports.BaseClient = BaseClient;
3500
+ exports.FetcherError = FetcherError;
3314
3501
  exports.Operations = operationsByTag;
3315
3502
  exports.PAGINATION_DEFAULT_OFFSET = PAGINATION_DEFAULT_OFFSET;
3316
3503
  exports.PAGINATION_DEFAULT_SIZE = PAGINATION_DEFAULT_SIZE;
@@ -3349,11 +3536,6 @@ exports.createMigrationRequest = createMigrationRequest;
3349
3536
  exports.createTable = createTable;
3350
3537
  exports.createUserAPIKey = createUserAPIKey;
3351
3538
  exports.createWorkspace = createWorkspace;
3352
- exports.dEPRECATEDcreateDatabase = dEPRECATEDcreateDatabase;
3353
- exports.dEPRECATEDdeleteDatabase = dEPRECATEDdeleteDatabase;
3354
- exports.dEPRECATEDgetDatabaseList = dEPRECATEDgetDatabaseList;
3355
- exports.dEPRECATEDgetDatabaseMetadata = dEPRECATEDgetDatabaseMetadata;
3356
- exports.dEPRECATEDupdateDatabaseMetadata = dEPRECATEDupdateDatabaseMetadata;
3357
3539
  exports.deleteBranch = deleteBranch;
3358
3540
  exports.deleteColumn = deleteColumn;
3359
3541
  exports.deleteDatabase = deleteDatabase;