@xata.io/client 0.0.0-alpha.ve8aa5fb → 0.0.0-alpha.ve8d38ea

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
  }
@@ -19,7 +20,8 @@ const TraceAttributes = {
19
20
  HTTP_METHOD: "http.method",
20
21
  HTTP_URL: "http.url",
21
22
  HTTP_ROUTE: "http.route",
22
- HTTP_TARGET: "http.target"
23
+ HTTP_TARGET: "http.target",
24
+ CLOUDFLARE_RAY_ID: "cf.ray"
23
25
  };
24
26
 
25
27
  function notEmpty(value) {
@@ -28,8 +30,18 @@ function notEmpty(value) {
28
30
  function compact(arr) {
29
31
  return arr.filter(notEmpty);
30
32
  }
33
+ function compactObject(obj) {
34
+ return Object.fromEntries(Object.entries(obj).filter(([, value]) => notEmpty(value)));
35
+ }
36
+ function isBlob(value) {
37
+ try {
38
+ return value instanceof Blob;
39
+ } catch (error) {
40
+ return false;
41
+ }
42
+ }
31
43
  function isObject(value) {
32
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
44
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date) && !isBlob(value);
33
45
  }
34
46
  function isDefined(value) {
35
47
  return value !== null && value !== void 0;
@@ -43,6 +55,18 @@ function isStringArray(value) {
43
55
  function isNumber(value) {
44
56
  return isDefined(value) && typeof value === "number";
45
57
  }
58
+ function parseNumber(value) {
59
+ if (isNumber(value)) {
60
+ return value;
61
+ }
62
+ if (isString(value)) {
63
+ const parsed = Number(value);
64
+ if (!Number.isNaN(parsed)) {
65
+ return parsed;
66
+ }
67
+ }
68
+ return void 0;
69
+ }
46
70
  function toBase64(value) {
47
71
  try {
48
72
  return btoa(value);
@@ -62,16 +86,49 @@ function deepMerge(a, b) {
62
86
  }
63
87
  return result;
64
88
  }
89
+ function chunk(array, chunkSize) {
90
+ const result = [];
91
+ for (let i = 0; i < array.length; i += chunkSize) {
92
+ result.push(array.slice(i, i + chunkSize));
93
+ }
94
+ return result;
95
+ }
96
+ async function timeout(ms) {
97
+ return new Promise((resolve) => setTimeout(resolve, ms));
98
+ }
99
+ function timeoutWithCancel(ms) {
100
+ let timeoutId;
101
+ const promise = new Promise((resolve) => {
102
+ timeoutId = setTimeout(() => {
103
+ resolve();
104
+ }, ms);
105
+ });
106
+ return {
107
+ cancel: () => clearTimeout(timeoutId),
108
+ promise
109
+ };
110
+ }
111
+ function promiseMap(inputValues, mapper) {
112
+ const reducer = (acc$, inputValue) => acc$.then(
113
+ (acc) => mapper(inputValue).then((result) => {
114
+ acc.push(result);
115
+ return acc;
116
+ })
117
+ );
118
+ return inputValues.reduce(reducer, Promise.resolve([]));
119
+ }
65
120
 
66
121
  function getEnvironment() {
67
122
  try {
68
- if (isObject(process) && isObject(process.env)) {
123
+ if (isDefined(process) && isDefined(process.env)) {
69
124
  return {
70
125
  apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
71
126
  databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
72
127
  branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
73
- envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
74
- fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
128
+ deployPreview: process.env.XATA_PREVIEW,
129
+ deployPreviewBranch: process.env.XATA_PREVIEW_BRANCH,
130
+ vercelGitCommitRef: process.env.VERCEL_GIT_COMMIT_REF,
131
+ vercelGitRepoOwner: process.env.VERCEL_GIT_REPO_OWNER
75
132
  };
76
133
  }
77
134
  } catch (err) {
@@ -82,8 +139,10 @@ function getEnvironment() {
82
139
  apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
83
140
  databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
84
141
  branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
85
- envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
86
- fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
142
+ deployPreview: Deno.env.get("XATA_PREVIEW"),
143
+ deployPreviewBranch: Deno.env.get("XATA_PREVIEW_BRANCH"),
144
+ vercelGitCommitRef: Deno.env.get("VERCEL_GIT_COMMIT_REF"),
145
+ vercelGitRepoOwner: Deno.env.get("VERCEL_GIT_REPO_OWNER")
87
146
  };
88
147
  }
89
148
  } catch (err) {
@@ -92,8 +151,10 @@ function getEnvironment() {
92
151
  apiKey: getGlobalApiKey(),
93
152
  databaseURL: getGlobalDatabaseURL(),
94
153
  branch: getGlobalBranch(),
95
- envBranch: void 0,
96
- fallbackBranch: getGlobalFallbackBranch()
154
+ deployPreview: void 0,
155
+ deployPreviewBranch: void 0,
156
+ vercelGitCommitRef: void 0,
157
+ vercelGitRepoOwner: void 0
97
158
  };
98
159
  }
99
160
  function getEnableBrowserVariable() {
@@ -136,56 +197,338 @@ function getGlobalBranch() {
136
197
  return void 0;
137
198
  }
138
199
  }
139
- function getGlobalFallbackBranch() {
200
+ function getDatabaseURL() {
140
201
  try {
141
- return XATA_FALLBACK_BRANCH;
202
+ const { databaseURL } = getEnvironment();
203
+ return databaseURL;
142
204
  } catch (err) {
143
205
  return void 0;
144
206
  }
145
207
  }
146
- async function getGitBranch() {
147
- const cmd = ["git", "branch", "--show-current"];
148
- const fullCmd = cmd.join(" ");
149
- const nodeModule = ["child", "process"].join("_");
150
- const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
208
+ function getAPIKey() {
151
209
  try {
152
- if (typeof require === "function") {
153
- return require(nodeModule).execSync(fullCmd, execOptions).trim();
154
- }
155
- const { execSync } = await import(nodeModule);
156
- return execSync(fullCmd, execOptions).toString().trim();
210
+ const { apiKey } = getEnvironment();
211
+ return apiKey;
157
212
  } catch (err) {
213
+ return void 0;
158
214
  }
215
+ }
216
+ function getBranch() {
159
217
  try {
160
- if (isObject(Deno)) {
161
- const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
162
- return new TextDecoder().decode(await process2.output()).trim();
163
- }
218
+ const { branch } = getEnvironment();
219
+ return branch;
164
220
  } catch (err) {
221
+ return void 0;
165
222
  }
166
223
  }
167
-
168
- function getAPIKey() {
224
+ function buildPreviewBranchName({ org, branch }) {
225
+ return `preview-${org}-${branch}`;
226
+ }
227
+ function getPreviewBranch() {
169
228
  try {
170
- const { apiKey } = getEnvironment();
171
- return apiKey;
229
+ const { deployPreview, deployPreviewBranch, vercelGitCommitRef, vercelGitRepoOwner } = getEnvironment();
230
+ if (deployPreviewBranch)
231
+ return deployPreviewBranch;
232
+ switch (deployPreview) {
233
+ case "vercel": {
234
+ if (!vercelGitCommitRef || !vercelGitRepoOwner) {
235
+ console.warn("XATA_PREVIEW=vercel but VERCEL_GIT_COMMIT_REF or VERCEL_GIT_REPO_OWNER is not valid");
236
+ return void 0;
237
+ }
238
+ return buildPreviewBranchName({ org: vercelGitRepoOwner, branch: vercelGitCommitRef });
239
+ }
240
+ }
241
+ return void 0;
172
242
  } catch (err) {
173
243
  return void 0;
174
244
  }
175
245
  }
176
246
 
247
+ var __accessCheck$8 = (obj, member, msg) => {
248
+ if (!member.has(obj))
249
+ throw TypeError("Cannot " + msg);
250
+ };
251
+ var __privateGet$8 = (obj, member, getter) => {
252
+ __accessCheck$8(obj, member, "read from private field");
253
+ return getter ? getter.call(obj) : member.get(obj);
254
+ };
255
+ var __privateAdd$8 = (obj, member, value) => {
256
+ if (member.has(obj))
257
+ throw TypeError("Cannot add the same private member more than once");
258
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
259
+ };
260
+ var __privateSet$8 = (obj, member, value, setter) => {
261
+ __accessCheck$8(obj, member, "write to private field");
262
+ setter ? setter.call(obj, value) : member.set(obj, value);
263
+ return value;
264
+ };
265
+ var __privateMethod$4 = (obj, member, method) => {
266
+ __accessCheck$8(obj, member, "access private method");
267
+ return method;
268
+ };
269
+ var _fetch, _queue, _concurrency, _enqueue, enqueue_fn;
270
+ const REQUEST_TIMEOUT = 5 * 60 * 1e3;
177
271
  function getFetchImplementation(userFetch) {
178
272
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
179
- const fetchImpl = userFetch ?? globalFetch;
273
+ const globalThisFetch = typeof globalThis !== "undefined" ? globalThis.fetch : void 0;
274
+ const fetchImpl = userFetch ?? globalFetch ?? globalThisFetch;
180
275
  if (!fetchImpl) {
181
- throw new Error(
182
- `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
183
- );
276
+ throw new Error(`Couldn't find a global \`fetch\`. Pass a fetch implementation explicitly.`);
184
277
  }
185
278
  return fetchImpl;
186
279
  }
280
+ class ApiRequestPool {
281
+ constructor(concurrency = 10) {
282
+ __privateAdd$8(this, _enqueue);
283
+ __privateAdd$8(this, _fetch, void 0);
284
+ __privateAdd$8(this, _queue, void 0);
285
+ __privateAdd$8(this, _concurrency, void 0);
286
+ __privateSet$8(this, _queue, []);
287
+ __privateSet$8(this, _concurrency, concurrency);
288
+ this.running = 0;
289
+ this.started = 0;
290
+ }
291
+ setFetch(fetch2) {
292
+ __privateSet$8(this, _fetch, fetch2);
293
+ }
294
+ getFetch() {
295
+ if (!__privateGet$8(this, _fetch)) {
296
+ throw new Error("Fetch not set");
297
+ }
298
+ return __privateGet$8(this, _fetch);
299
+ }
300
+ request(url, options) {
301
+ const start = /* @__PURE__ */ new Date();
302
+ const fetchImpl = this.getFetch();
303
+ const runRequest = async (stalled = false) => {
304
+ const { promise, cancel } = timeoutWithCancel(REQUEST_TIMEOUT);
305
+ const response = await Promise.race([fetchImpl(url, options), promise.then(() => null)]).finally(cancel);
306
+ if (!response) {
307
+ throw new Error("Request timed out");
308
+ }
309
+ if (response.status === 429) {
310
+ const rateLimitReset = parseNumber(response.headers?.get("x-ratelimit-reset")) ?? 1;
311
+ await timeout(rateLimitReset * 1e3);
312
+ return await runRequest(true);
313
+ }
314
+ if (stalled) {
315
+ const stalledTime = (/* @__PURE__ */ new Date()).getTime() - start.getTime();
316
+ console.warn(`A request to Xata hit branch rate limits, was retried and stalled for ${stalledTime}ms`);
317
+ }
318
+ return response;
319
+ };
320
+ return __privateMethod$4(this, _enqueue, enqueue_fn).call(this, async () => {
321
+ return await runRequest();
322
+ });
323
+ }
324
+ }
325
+ _fetch = new WeakMap();
326
+ _queue = new WeakMap();
327
+ _concurrency = new WeakMap();
328
+ _enqueue = new WeakSet();
329
+ enqueue_fn = function(task) {
330
+ const promise = new Promise((resolve) => __privateGet$8(this, _queue).push(resolve)).finally(() => {
331
+ this.started--;
332
+ this.running++;
333
+ }).then(() => task()).finally(() => {
334
+ this.running--;
335
+ const next = __privateGet$8(this, _queue).shift();
336
+ if (next !== void 0) {
337
+ this.started++;
338
+ next();
339
+ }
340
+ });
341
+ if (this.running + this.started < __privateGet$8(this, _concurrency)) {
342
+ const next = __privateGet$8(this, _queue).shift();
343
+ if (next !== void 0) {
344
+ this.started++;
345
+ next();
346
+ }
347
+ }
348
+ return promise;
349
+ };
350
+
351
+ function generateUUID() {
352
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
353
+ const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
354
+ return v.toString(16);
355
+ });
356
+ }
357
+
358
+ async function getBytes(stream, onChunk) {
359
+ const reader = stream.getReader();
360
+ let result;
361
+ while (!(result = await reader.read()).done) {
362
+ onChunk(result.value);
363
+ }
364
+ }
365
+ function getLines(onLine) {
366
+ let buffer;
367
+ let position;
368
+ let fieldLength;
369
+ let discardTrailingNewline = false;
370
+ return function onChunk(arr) {
371
+ if (buffer === void 0) {
372
+ buffer = arr;
373
+ position = 0;
374
+ fieldLength = -1;
375
+ } else {
376
+ buffer = concat(buffer, arr);
377
+ }
378
+ const bufLength = buffer.length;
379
+ let lineStart = 0;
380
+ while (position < bufLength) {
381
+ if (discardTrailingNewline) {
382
+ if (buffer[position] === 10 /* NewLine */) {
383
+ lineStart = ++position;
384
+ }
385
+ discardTrailingNewline = false;
386
+ }
387
+ let lineEnd = -1;
388
+ for (; position < bufLength && lineEnd === -1; ++position) {
389
+ switch (buffer[position]) {
390
+ case 58 /* Colon */:
391
+ if (fieldLength === -1) {
392
+ fieldLength = position - lineStart;
393
+ }
394
+ break;
395
+ case 13 /* CarriageReturn */:
396
+ discardTrailingNewline = true;
397
+ case 10 /* NewLine */:
398
+ lineEnd = position;
399
+ break;
400
+ }
401
+ }
402
+ if (lineEnd === -1) {
403
+ break;
404
+ }
405
+ onLine(buffer.subarray(lineStart, lineEnd), fieldLength);
406
+ lineStart = position;
407
+ fieldLength = -1;
408
+ }
409
+ if (lineStart === bufLength) {
410
+ buffer = void 0;
411
+ } else if (lineStart !== 0) {
412
+ buffer = buffer.subarray(lineStart);
413
+ position -= lineStart;
414
+ }
415
+ };
416
+ }
417
+ function getMessages(onId, onRetry, onMessage) {
418
+ let message = newMessage();
419
+ const decoder = new TextDecoder();
420
+ return function onLine(line, fieldLength) {
421
+ if (line.length === 0) {
422
+ onMessage?.(message);
423
+ message = newMessage();
424
+ } else if (fieldLength > 0) {
425
+ const field = decoder.decode(line.subarray(0, fieldLength));
426
+ const valueOffset = fieldLength + (line[fieldLength + 1] === 32 /* Space */ ? 2 : 1);
427
+ const value = decoder.decode(line.subarray(valueOffset));
428
+ switch (field) {
429
+ case "data":
430
+ message.data = message.data ? message.data + "\n" + value : value;
431
+ break;
432
+ case "event":
433
+ message.event = value;
434
+ break;
435
+ case "id":
436
+ onId(message.id = value);
437
+ break;
438
+ case "retry":
439
+ const retry = parseInt(value, 10);
440
+ if (!isNaN(retry)) {
441
+ onRetry(message.retry = retry);
442
+ }
443
+ break;
444
+ }
445
+ }
446
+ };
447
+ }
448
+ function concat(a, b) {
449
+ const res = new Uint8Array(a.length + b.length);
450
+ res.set(a);
451
+ res.set(b, a.length);
452
+ return res;
453
+ }
454
+ function newMessage() {
455
+ return {
456
+ data: "",
457
+ event: "",
458
+ id: "",
459
+ retry: void 0
460
+ };
461
+ }
462
+ const EventStreamContentType = "text/event-stream";
463
+ const LastEventId = "last-event-id";
464
+ function fetchEventSource(input, {
465
+ signal: inputSignal,
466
+ headers: inputHeaders,
467
+ onopen: inputOnOpen,
468
+ onmessage,
469
+ onclose,
470
+ onerror,
471
+ fetch: inputFetch,
472
+ ...rest
473
+ }) {
474
+ return new Promise((resolve, reject) => {
475
+ const headers = { ...inputHeaders };
476
+ if (!headers.accept) {
477
+ headers.accept = EventStreamContentType;
478
+ }
479
+ let curRequestController;
480
+ function dispose() {
481
+ curRequestController.abort();
482
+ }
483
+ inputSignal?.addEventListener("abort", () => {
484
+ dispose();
485
+ resolve();
486
+ });
487
+ const fetchImpl = inputFetch ?? fetch;
488
+ const onopen = inputOnOpen ?? defaultOnOpen;
489
+ async function create() {
490
+ curRequestController = new AbortController();
491
+ try {
492
+ const response = await fetchImpl(input, {
493
+ ...rest,
494
+ headers,
495
+ signal: curRequestController.signal
496
+ });
497
+ await onopen(response);
498
+ await getBytes(
499
+ response.body,
500
+ getLines(
501
+ getMessages(
502
+ (id) => {
503
+ if (id) {
504
+ headers[LastEventId] = id;
505
+ } else {
506
+ delete headers[LastEventId];
507
+ }
508
+ },
509
+ (_retry) => {
510
+ },
511
+ onmessage
512
+ )
513
+ )
514
+ );
515
+ onclose?.();
516
+ dispose();
517
+ resolve();
518
+ } catch (err) {
519
+ }
520
+ }
521
+ create();
522
+ });
523
+ }
524
+ function defaultOnOpen(response) {
525
+ const contentType = response.headers?.get("content-type");
526
+ if (!contentType?.startsWith(EventStreamContentType)) {
527
+ throw new Error(`Expected content-type to be ${EventStreamContentType}, Actual: ${contentType}`);
528
+ }
529
+ }
187
530
 
188
- const VERSION = "0.0.0-alpha.ve8aa5fb";
531
+ const VERSION = "0.26.9";
189
532
 
190
533
  class ErrorWithCause extends Error {
191
534
  constructor(message, options) {
@@ -196,7 +539,7 @@ class FetcherError extends ErrorWithCause {
196
539
  constructor(status, data, requestId) {
197
540
  super(getMessage(data));
198
541
  this.status = status;
199
- this.errors = isBulkError(data) ? data.errors : void 0;
542
+ this.errors = isBulkError(data) ? data.errors : [{ message: getMessage(data), status }];
200
543
  this.requestId = requestId;
201
544
  if (data instanceof Error) {
202
545
  this.stack = data.stack;
@@ -228,6 +571,7 @@ function getMessage(data) {
228
571
  }
229
572
  }
230
573
 
574
+ const pool = new ApiRequestPool();
231
575
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
232
576
  const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
233
577
  if (value === void 0 || value === null)
@@ -260,14 +604,27 @@ function hostHeader(url) {
260
604
  const { groups } = pattern.exec(url) ?? {};
261
605
  return groups?.host ? { Host: groups.host } : {};
262
606
  }
607
+ async function parseBody(body, headers) {
608
+ if (!isDefined(body))
609
+ return void 0;
610
+ if (isBlob(body) || typeof body.text === "function") {
611
+ return body;
612
+ }
613
+ const { "Content-Type": contentType } = headers ?? {};
614
+ if (String(contentType).toLowerCase() === "application/json" && isObject(body)) {
615
+ return JSON.stringify(body);
616
+ }
617
+ return body;
618
+ }
619
+ const defaultClientID = generateUUID();
263
620
  async function fetch$1({
264
621
  url: path,
265
622
  method,
266
623
  body,
267
- headers,
624
+ headers: customHeaders,
268
625
  pathParams,
269
626
  queryParams,
270
- fetchImpl,
627
+ fetch: fetch2,
271
628
  apiKey,
272
629
  endpoint,
273
630
  apiUrl,
@@ -276,9 +633,13 @@ async function fetch$1({
276
633
  signal,
277
634
  clientID,
278
635
  sessionID,
279
- fetchOptions = {}
636
+ clientName,
637
+ xataAgentExtra,
638
+ fetchOptions = {},
639
+ rawResponse = false
280
640
  }) {
281
- return trace(
641
+ pool.setFetch(fetch2);
642
+ return await trace(
282
643
  `${method.toUpperCase()} ${path}`,
283
644
  async ({ setAttributes }) => {
284
645
  const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
@@ -288,24 +649,29 @@ async function fetch$1({
288
649
  [TraceAttributes.HTTP_URL]: url,
289
650
  [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
290
651
  });
291
- const response = await fetchImpl(url, {
652
+ const xataAgent = compact([
653
+ ["client", "TS_SDK"],
654
+ ["version", VERSION],
655
+ isDefined(clientName) ? ["service", clientName] : void 0,
656
+ ...Object.entries(xataAgentExtra ?? {})
657
+ ]).map(([key, value]) => `${key}=${value}`).join("; ");
658
+ const headers = compactObject({
659
+ "Accept-Encoding": "identity",
660
+ "Content-Type": "application/json",
661
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
662
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
663
+ "X-Xata-Agent": xataAgent,
664
+ ...customHeaders,
665
+ ...hostHeader(fullUrl),
666
+ Authorization: `Bearer ${apiKey}`
667
+ });
668
+ const response = await pool.request(url, {
292
669
  ...fetchOptions,
293
670
  method: method.toUpperCase(),
294
- 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
- },
671
+ body: await parseBody(body, headers),
672
+ headers,
304
673
  signal
305
674
  });
306
- if (response.status === 204) {
307
- return {};
308
- }
309
675
  const { host, protocol } = parseUrl(response.url);
310
676
  const requestId = response.headers?.get("x-request-id") ?? void 0;
311
677
  setAttributes({
@@ -313,10 +679,20 @@ async function fetch$1({
313
679
  [TraceAttributes.HTTP_REQUEST_ID]: requestId,
314
680
  [TraceAttributes.HTTP_STATUS_CODE]: response.status,
315
681
  [TraceAttributes.HTTP_HOST]: host,
316
- [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
682
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", ""),
683
+ [TraceAttributes.CLOUDFLARE_RAY_ID]: response.headers?.get("cf-ray") ?? void 0
317
684
  });
685
+ const message = response.headers?.get("x-xata-message");
686
+ if (message)
687
+ console.warn(message);
688
+ if (response.status === 204) {
689
+ return {};
690
+ }
691
+ if (response.status === 429) {
692
+ throw new FetcherError(response.status, "Rate limit exceeded", requestId);
693
+ }
318
694
  try {
319
- const jsonResponse = await response.json();
695
+ const jsonResponse = rawResponse ? await response.blob() : await response.json();
320
696
  if (response.ok) {
321
697
  return jsonResponse;
322
698
  }
@@ -328,6 +704,59 @@ async function fetch$1({
328
704
  { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
329
705
  );
330
706
  }
707
+ function fetchSSERequest({
708
+ url: path,
709
+ method,
710
+ body,
711
+ headers: customHeaders,
712
+ pathParams,
713
+ queryParams,
714
+ fetch: fetch2,
715
+ apiKey,
716
+ endpoint,
717
+ apiUrl,
718
+ workspacesApiUrl,
719
+ onMessage,
720
+ onError,
721
+ onClose,
722
+ signal,
723
+ clientID,
724
+ sessionID,
725
+ clientName,
726
+ xataAgentExtra
727
+ }) {
728
+ const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
729
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
730
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
731
+ void fetchEventSource(url, {
732
+ method,
733
+ body: JSON.stringify(body),
734
+ fetch: fetch2,
735
+ signal,
736
+ headers: {
737
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
738
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
739
+ "X-Xata-Agent": compact([
740
+ ["client", "TS_SDK"],
741
+ ["version", VERSION],
742
+ isDefined(clientName) ? ["service", clientName] : void 0,
743
+ ...Object.entries(xataAgentExtra ?? {})
744
+ ]).map(([key, value]) => `${key}=${value}`).join("; "),
745
+ ...customHeaders,
746
+ Authorization: `Bearer ${apiKey}`,
747
+ "Content-Type": "application/json"
748
+ },
749
+ onmessage(ev) {
750
+ onMessage?.(JSON.parse(ev.data));
751
+ },
752
+ onerror(ev) {
753
+ onError?.(JSON.parse(ev.data));
754
+ },
755
+ onclose() {
756
+ onClose?.();
757
+ }
758
+ });
759
+ }
331
760
  function parseUrl(url) {
332
761
  try {
333
762
  const { host, protocol } = new URL(url);
@@ -339,17 +768,12 @@ function parseUrl(url) {
339
768
 
340
769
  const dataPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "dataPlane" });
341
770
 
342
- const dEPRECATEDgetDatabaseList = (variables, signal) => dataPlaneFetch({ url: "/dbs", method: "get", ...variables, signal });
343
771
  const getBranchList = (variables, signal) => dataPlaneFetch({
344
772
  url: "/dbs/{dbName}",
345
773
  method: "get",
346
774
  ...variables,
347
775
  signal
348
776
  });
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
777
  const getBranchDetails = (variables, signal) => dataPlaneFetch({
354
778
  url: "/db/{dbBranchName}",
355
779
  method: "get",
@@ -363,6 +787,18 @@ const deleteBranch = (variables, signal) => dataPlaneFetch({
363
787
  ...variables,
364
788
  signal
365
789
  });
790
+ const getSchema = (variables, signal) => dataPlaneFetch({
791
+ url: "/db/{dbBranchName}/schema",
792
+ method: "get",
793
+ ...variables,
794
+ signal
795
+ });
796
+ const copyBranch = (variables, signal) => dataPlaneFetch({
797
+ url: "/db/{dbBranchName}/copy",
798
+ method: "post",
799
+ ...variables,
800
+ signal
801
+ });
366
802
  const updateBranchMetadata = (variables, signal) => dataPlaneFetch({
367
803
  url: "/db/{dbBranchName}/metadata",
368
804
  method: "put",
@@ -388,7 +824,6 @@ const resolveBranch = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName
388
824
  const getBranchMigrationHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables, signal });
389
825
  const getBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables, signal });
390
826
  const executeBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables, signal });
391
- const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
392
827
  const queryMigrationRequests = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/query", method: "post", ...variables, signal });
393
828
  const createMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations", method: "post", ...variables, signal });
394
829
  const getMigrationRequest = (variables, signal) => dataPlaneFetch({
@@ -413,6 +848,7 @@ const compareBranchSchemas = (variables, signal) => dataPlaneFetch({ url: "/db/{
413
848
  const updateBranchSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/update", method: "post", ...variables, signal });
414
849
  const previewBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables, signal });
415
850
  const applyBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables, signal });
851
+ const pushBranchMigrations = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/push", method: "post", ...variables, signal });
416
852
  const createTable = (variables, signal) => dataPlaneFetch({
417
853
  url: "/db/{dbBranchName}/tables/{tableName}",
418
854
  method: "put",
@@ -455,7 +891,44 @@ const deleteColumn = (variables, signal) => dataPlaneFetch({
455
891
  ...variables,
456
892
  signal
457
893
  });
894
+ const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
458
895
  const insertRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
896
+ const getFileItem = (variables, signal) => dataPlaneFetch({
897
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
898
+ method: "get",
899
+ ...variables,
900
+ signal
901
+ });
902
+ const putFileItem = (variables, signal) => dataPlaneFetch({
903
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
904
+ method: "put",
905
+ ...variables,
906
+ signal
907
+ });
908
+ const deleteFileItem = (variables, signal) => dataPlaneFetch({
909
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
910
+ method: "delete",
911
+ ...variables,
912
+ signal
913
+ });
914
+ const getFile = (variables, signal) => dataPlaneFetch({
915
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
916
+ method: "get",
917
+ ...variables,
918
+ signal
919
+ });
920
+ const putFile = (variables, signal) => dataPlaneFetch({
921
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
922
+ method: "put",
923
+ ...variables,
924
+ signal
925
+ });
926
+ const deleteFile = (variables, signal) => dataPlaneFetch({
927
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
928
+ method: "delete",
929
+ ...variables,
930
+ signal
931
+ });
459
932
  const getRecord = (variables, signal) => dataPlaneFetch({
460
933
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
461
934
  method: "get",
@@ -485,21 +958,35 @@ const searchTable = (variables, signal) => dataPlaneFetch({
485
958
  ...variables,
486
959
  signal
487
960
  });
961
+ const vectorSearchTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/vectorSearch", method: "post", ...variables, signal });
962
+ const askTable = (variables, signal) => dataPlaneFetch({
963
+ url: "/db/{dbBranchName}/tables/{tableName}/ask",
964
+ method: "post",
965
+ ...variables,
966
+ signal
967
+ });
968
+ const askTableSession = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}", method: "post", ...variables, signal });
488
969
  const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
489
970
  const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
971
+ const fileAccess = (variables, signal) => dataPlaneFetch({
972
+ url: "/file/{fileId}",
973
+ method: "get",
974
+ ...variables,
975
+ signal
976
+ });
977
+ const sqlQuery = (variables, signal) => dataPlaneFetch({
978
+ url: "/db/{dbBranchName}/sql",
979
+ method: "post",
980
+ ...variables,
981
+ signal
982
+ });
490
983
  const operationsByTag$2 = {
491
- database: {
492
- dEPRECATEDgetDatabaseList,
493
- dEPRECATEDcreateDatabase,
494
- dEPRECATEDdeleteDatabase,
495
- dEPRECATEDgetDatabaseMetadata,
496
- dEPRECATEDupdateDatabaseMetadata
497
- },
498
984
  branch: {
499
985
  getBranchList,
500
986
  getBranchDetails,
501
987
  createBranch,
502
988
  deleteBranch,
989
+ copyBranch,
503
990
  updateBranchMetadata,
504
991
  getBranchMetadata,
505
992
  getBranchStats,
@@ -509,6 +996,7 @@ const operationsByTag$2 = {
509
996
  resolveBranch
510
997
  },
511
998
  migrations: {
999
+ getSchema,
512
1000
  getBranchMigrationHistory,
513
1001
  getBranchMigrationPlan,
514
1002
  executeBranchMigrationPlan,
@@ -517,17 +1005,8 @@ const operationsByTag$2 = {
517
1005
  compareBranchSchemas,
518
1006
  updateBranchSchema,
519
1007
  previewBranchSchemaEdit,
520
- applyBranchSchemaEdit
521
- },
522
- records: {
523
- branchTransaction,
524
- insertRecord,
525
- getRecord,
526
- insertRecordWithID,
527
- updateRecordWithID,
528
- upsertRecordWithID,
529
- deleteRecord,
530
- bulkInsertTableRecords
1008
+ applyBranchSchemaEdit,
1009
+ pushBranchMigrations
531
1010
  },
532
1011
  migrationRequests: {
533
1012
  queryMigrationRequests,
@@ -551,11 +1030,34 @@ const operationsByTag$2 = {
551
1030
  updateColumn,
552
1031
  deleteColumn
553
1032
  },
554
- searchAndFilter: { queryTable, searchBranch, searchTable, summarizeTable, aggregateTable }
1033
+ records: {
1034
+ branchTransaction,
1035
+ insertRecord,
1036
+ getRecord,
1037
+ insertRecordWithID,
1038
+ updateRecordWithID,
1039
+ upsertRecordWithID,
1040
+ deleteRecord,
1041
+ bulkInsertTableRecords
1042
+ },
1043
+ files: { getFileItem, putFileItem, deleteFileItem, getFile, putFile, deleteFile, fileAccess },
1044
+ searchAndFilter: {
1045
+ queryTable,
1046
+ searchBranch,
1047
+ searchTable,
1048
+ vectorSearchTable,
1049
+ askTable,
1050
+ askTableSession,
1051
+ summarizeTable,
1052
+ aggregateTable
1053
+ },
1054
+ sql: { sqlQuery }
555
1055
  };
556
1056
 
557
1057
  const controlPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "controlPlane" });
558
1058
 
1059
+ const getAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "get", ...variables, signal });
1060
+ const grantAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "post", ...variables, signal });
559
1061
  const getUser = (variables, signal) => controlPlaneFetch({
560
1062
  url: "/user",
561
1063
  method: "get",
@@ -592,6 +1094,31 @@ const deleteUserAPIKey = (variables, signal) => controlPlaneFetch({
592
1094
  ...variables,
593
1095
  signal
594
1096
  });
1097
+ const getUserOAuthClients = (variables, signal) => controlPlaneFetch({
1098
+ url: "/user/oauth/clients",
1099
+ method: "get",
1100
+ ...variables,
1101
+ signal
1102
+ });
1103
+ const deleteUserOAuthClient = (variables, signal) => controlPlaneFetch({
1104
+ url: "/user/oauth/clients/{clientId}",
1105
+ method: "delete",
1106
+ ...variables,
1107
+ signal
1108
+ });
1109
+ const getUserOAuthAccessTokens = (variables, signal) => controlPlaneFetch({
1110
+ url: "/user/oauth/tokens",
1111
+ method: "get",
1112
+ ...variables,
1113
+ signal
1114
+ });
1115
+ const deleteOAuthAccessToken = (variables, signal) => controlPlaneFetch({
1116
+ url: "/user/oauth/tokens/{token}",
1117
+ method: "delete",
1118
+ ...variables,
1119
+ signal
1120
+ });
1121
+ const updateOAuthAccessToken = (variables, signal) => controlPlaneFetch({ url: "/user/oauth/tokens/{token}", method: "patch", ...variables, signal });
595
1122
  const getWorkspacesList = (variables, signal) => controlPlaneFetch({
596
1123
  url: "/workspaces",
597
1124
  method: "get",
@@ -635,6 +1162,20 @@ const updateWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ u
635
1162
  const cancelWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "delete", ...variables, signal });
636
1163
  const acceptWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept", method: "post", ...variables, signal });
637
1164
  const resendWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}/resend", method: "post", ...variables, signal });
1165
+ const listClusters = (variables, signal) => controlPlaneFetch({
1166
+ url: "/workspaces/{workspaceId}/clusters",
1167
+ method: "get",
1168
+ ...variables,
1169
+ signal
1170
+ });
1171
+ const createCluster = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/clusters", method: "post", ...variables, signal });
1172
+ const getCluster = (variables, signal) => controlPlaneFetch({
1173
+ url: "/workspaces/{workspaceId}/clusters/{clusterId}",
1174
+ method: "get",
1175
+ ...variables,
1176
+ signal
1177
+ });
1178
+ const updateCluster = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/clusters/{clusterId}", method: "patch", ...variables, signal });
638
1179
  const getDatabaseList = (variables, signal) => controlPlaneFetch({
639
1180
  url: "/workspaces/{workspaceId}/dbs",
640
1181
  method: "get",
@@ -650,6 +1191,10 @@ const deleteDatabase = (variables, signal) => controlPlaneFetch({
650
1191
  });
651
1192
  const getDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "get", ...variables, signal });
652
1193
  const updateDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "patch", ...variables, signal });
1194
+ const renameDatabase = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/rename", method: "post", ...variables, signal });
1195
+ const getDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "get", ...variables, signal });
1196
+ const updateDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "put", ...variables, signal });
1197
+ const deleteDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "delete", ...variables, signal });
653
1198
  const listRegions = (variables, signal) => controlPlaneFetch({
654
1199
  url: "/workspaces/{workspaceId}/regions",
655
1200
  method: "get",
@@ -657,6 +1202,15 @@ const listRegions = (variables, signal) => controlPlaneFetch({
657
1202
  signal
658
1203
  });
659
1204
  const operationsByTag$1 = {
1205
+ oAuth: {
1206
+ getAuthorizationCode,
1207
+ grantAuthorizationCode,
1208
+ getUserOAuthClients,
1209
+ deleteUserOAuthClient,
1210
+ getUserOAuthAccessTokens,
1211
+ deleteOAuthAccessToken,
1212
+ updateOAuthAccessToken
1213
+ },
660
1214
  users: { getUser, updateUser, deleteUser },
661
1215
  authentication: { getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
662
1216
  workspaces: {
@@ -676,12 +1230,17 @@ const operationsByTag$1 = {
676
1230
  acceptWorkspaceMemberInvite,
677
1231
  resendWorkspaceMemberInvite
678
1232
  },
1233
+ xbcontrolOther: { listClusters, createCluster, getCluster, updateCluster },
679
1234
  databases: {
680
1235
  getDatabaseList,
681
1236
  createDatabase,
682
1237
  deleteDatabase,
683
1238
  getDatabaseMetadata,
684
1239
  updateDatabaseMetadata,
1240
+ renameDatabase,
1241
+ getDatabaseGithubSettings,
1242
+ updateDatabaseGithubSettings,
1243
+ deleteDatabaseGithubSettings,
685
1244
  listRegions
686
1245
  }
687
1246
  };
@@ -702,8 +1261,12 @@ const providers = {
702
1261
  workspaces: "https://{workspaceId}.{region}.xata.sh"
703
1262
  },
704
1263
  staging: {
705
- main: "https://staging.xatabase.co",
706
- workspaces: "https://{workspaceId}.staging.{region}.xatabase.co"
1264
+ main: "https://api.staging-xata.dev",
1265
+ workspaces: "https://{workspaceId}.{region}.staging-xata.dev"
1266
+ },
1267
+ dev: {
1268
+ main: "https://api.dev-xata.dev",
1269
+ workspaces: "https://{workspaceId}.{region}.dev-xata.dev"
707
1270
  }
708
1271
  };
709
1272
  function isHostProviderAlias(alias) {
@@ -721,15 +1284,22 @@ function parseProviderString(provider = "production") {
721
1284
  return null;
722
1285
  return { main, workspaces };
723
1286
  }
1287
+ function buildProviderString(provider) {
1288
+ if (isHostProviderAlias(provider))
1289
+ return provider;
1290
+ return `${provider.main},${provider.workspaces}`;
1291
+ }
724
1292
  function parseWorkspacesUrlParts(url) {
725
1293
  if (!isString(url))
726
1294
  return null;
727
- const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))?\.xata\.sh.*/;
728
- const regexStaging = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))?\.xatabase\.co.*/;
729
- const match = url.match(regex) || url.match(regexStaging);
1295
+ const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/;
1296
+ const regexDev = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.dev-xata\.dev.*/;
1297
+ const regexStaging = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.staging-xata\.dev.*/;
1298
+ const regexProdTesting = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.tech.*/;
1299
+ const match = url.match(regex) || url.match(regexDev) || url.match(regexStaging) || url.match(regexProdTesting);
730
1300
  if (!match)
731
1301
  return null;
732
- return { workspace: match[1], region: match[2] ?? "eu-west-1" };
1302
+ return { workspace: match[1], region: match[2] };
733
1303
  }
734
1304
 
735
1305
  var __accessCheck$7 = (obj, member, msg) => {
@@ -758,15 +1328,19 @@ class XataApiClient {
758
1328
  const provider = options.host ?? "production";
759
1329
  const apiKey = options.apiKey ?? getAPIKey();
760
1330
  const trace = options.trace ?? defaultTrace;
1331
+ const clientID = generateUUID();
761
1332
  if (!apiKey) {
762
1333
  throw new Error("Could not resolve a valid apiKey");
763
1334
  }
764
1335
  __privateSet$7(this, _extraProps, {
765
1336
  apiUrl: getHostUrl(provider, "main"),
766
1337
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
767
- fetchImpl: getFetchImplementation(options.fetch),
1338
+ fetch: getFetchImplementation(options.fetch),
768
1339
  apiKey,
769
- trace
1340
+ trace,
1341
+ clientName: options.clientName,
1342
+ xataAgentExtra: options.xataAgentExtra,
1343
+ clientID
770
1344
  });
771
1345
  }
772
1346
  get user() {
@@ -819,6 +1393,11 @@ class XataApiClient {
819
1393
  __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
820
1394
  return __privateGet$7(this, _namespaces).records;
821
1395
  }
1396
+ get files() {
1397
+ if (!__privateGet$7(this, _namespaces).files)
1398
+ __privateGet$7(this, _namespaces).files = new FilesApi(__privateGet$7(this, _extraProps));
1399
+ return __privateGet$7(this, _namespaces).files;
1400
+ }
822
1401
  get searchAndFilter() {
823
1402
  if (!__privateGet$7(this, _namespaces).searchAndFilter)
824
1403
  __privateGet$7(this, _namespaces).searchAndFilter = new SearchAndFilterApi(__privateGet$7(this, _extraProps));
@@ -1027,6 +1606,20 @@ class BranchApi {
1027
1606
  ...this.extraProps
1028
1607
  });
1029
1608
  }
1609
+ copyBranch({
1610
+ workspace,
1611
+ region,
1612
+ database,
1613
+ branch,
1614
+ destinationBranch,
1615
+ limit
1616
+ }) {
1617
+ return operationsByTag.branch.copyBranch({
1618
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1619
+ body: { destinationBranch, limit },
1620
+ ...this.extraProps
1621
+ });
1622
+ }
1030
1623
  updateBranchMetadata({
1031
1624
  workspace,
1032
1625
  region,
@@ -1368,6 +1961,177 @@ class RecordsApi {
1368
1961
  ...this.extraProps
1369
1962
  });
1370
1963
  }
1964
+ branchTransaction({
1965
+ workspace,
1966
+ region,
1967
+ database,
1968
+ branch,
1969
+ operations
1970
+ }) {
1971
+ return operationsByTag.records.branchTransaction({
1972
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1973
+ body: { operations },
1974
+ ...this.extraProps
1975
+ });
1976
+ }
1977
+ }
1978
+ class FilesApi {
1979
+ constructor(extraProps) {
1980
+ this.extraProps = extraProps;
1981
+ }
1982
+ getFileItem({
1983
+ workspace,
1984
+ region,
1985
+ database,
1986
+ branch,
1987
+ table,
1988
+ record,
1989
+ column,
1990
+ fileId
1991
+ }) {
1992
+ return operationsByTag.files.getFileItem({
1993
+ pathParams: {
1994
+ workspace,
1995
+ region,
1996
+ dbBranchName: `${database}:${branch}`,
1997
+ tableName: table,
1998
+ recordId: record,
1999
+ columnName: column,
2000
+ fileId
2001
+ },
2002
+ ...this.extraProps
2003
+ });
2004
+ }
2005
+ putFileItem({
2006
+ workspace,
2007
+ region,
2008
+ database,
2009
+ branch,
2010
+ table,
2011
+ record,
2012
+ column,
2013
+ fileId,
2014
+ file
2015
+ }) {
2016
+ return operationsByTag.files.putFileItem({
2017
+ pathParams: {
2018
+ workspace,
2019
+ region,
2020
+ dbBranchName: `${database}:${branch}`,
2021
+ tableName: table,
2022
+ recordId: record,
2023
+ columnName: column,
2024
+ fileId
2025
+ },
2026
+ // @ts-ignore
2027
+ body: file,
2028
+ ...this.extraProps
2029
+ });
2030
+ }
2031
+ deleteFileItem({
2032
+ workspace,
2033
+ region,
2034
+ database,
2035
+ branch,
2036
+ table,
2037
+ record,
2038
+ column,
2039
+ fileId
2040
+ }) {
2041
+ return operationsByTag.files.deleteFileItem({
2042
+ pathParams: {
2043
+ workspace,
2044
+ region,
2045
+ dbBranchName: `${database}:${branch}`,
2046
+ tableName: table,
2047
+ recordId: record,
2048
+ columnName: column,
2049
+ fileId
2050
+ },
2051
+ ...this.extraProps
2052
+ });
2053
+ }
2054
+ getFile({
2055
+ workspace,
2056
+ region,
2057
+ database,
2058
+ branch,
2059
+ table,
2060
+ record,
2061
+ column
2062
+ }) {
2063
+ return operationsByTag.files.getFile({
2064
+ pathParams: {
2065
+ workspace,
2066
+ region,
2067
+ dbBranchName: `${database}:${branch}`,
2068
+ tableName: table,
2069
+ recordId: record,
2070
+ columnName: column
2071
+ },
2072
+ ...this.extraProps
2073
+ });
2074
+ }
2075
+ putFile({
2076
+ workspace,
2077
+ region,
2078
+ database,
2079
+ branch,
2080
+ table,
2081
+ record,
2082
+ column,
2083
+ file
2084
+ }) {
2085
+ return operationsByTag.files.putFile({
2086
+ pathParams: {
2087
+ workspace,
2088
+ region,
2089
+ dbBranchName: `${database}:${branch}`,
2090
+ tableName: table,
2091
+ recordId: record,
2092
+ columnName: column
2093
+ },
2094
+ body: file,
2095
+ ...this.extraProps
2096
+ });
2097
+ }
2098
+ deleteFile({
2099
+ workspace,
2100
+ region,
2101
+ database,
2102
+ branch,
2103
+ table,
2104
+ record,
2105
+ column
2106
+ }) {
2107
+ return operationsByTag.files.deleteFile({
2108
+ pathParams: {
2109
+ workspace,
2110
+ region,
2111
+ dbBranchName: `${database}:${branch}`,
2112
+ tableName: table,
2113
+ recordId: record,
2114
+ columnName: column
2115
+ },
2116
+ ...this.extraProps
2117
+ });
2118
+ }
2119
+ fileAccess({
2120
+ workspace,
2121
+ region,
2122
+ fileId,
2123
+ verify
2124
+ }) {
2125
+ return operationsByTag.files.fileAccess({
2126
+ pathParams: {
2127
+ workspace,
2128
+ region,
2129
+ fileId
2130
+ },
2131
+ queryParams: { verify },
2132
+ ...this.extraProps
2133
+ });
2134
+ }
1371
2135
  }
1372
2136
  class SearchAndFilterApi {
1373
2137
  constructor(extraProps) {
@@ -1428,6 +2192,53 @@ class SearchAndFilterApi {
1428
2192
  ...this.extraProps
1429
2193
  });
1430
2194
  }
2195
+ vectorSearchTable({
2196
+ workspace,
2197
+ region,
2198
+ database,
2199
+ branch,
2200
+ table,
2201
+ queryVector,
2202
+ column,
2203
+ similarityFunction,
2204
+ size,
2205
+ filter
2206
+ }) {
2207
+ return operationsByTag.searchAndFilter.vectorSearchTable({
2208
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2209
+ body: { queryVector, column, similarityFunction, size, filter },
2210
+ ...this.extraProps
2211
+ });
2212
+ }
2213
+ askTable({
2214
+ workspace,
2215
+ region,
2216
+ database,
2217
+ branch,
2218
+ table,
2219
+ options
2220
+ }) {
2221
+ return operationsByTag.searchAndFilter.askTable({
2222
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2223
+ body: { ...options },
2224
+ ...this.extraProps
2225
+ });
2226
+ }
2227
+ askTableSession({
2228
+ workspace,
2229
+ region,
2230
+ database,
2231
+ branch,
2232
+ table,
2233
+ sessionId,
2234
+ message
2235
+ }) {
2236
+ return operationsByTag.searchAndFilter.askTableSession({
2237
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, sessionId },
2238
+ body: { message },
2239
+ ...this.extraProps
2240
+ });
2241
+ }
1431
2242
  summarizeTable({
1432
2243
  workspace,
1433
2244
  region,
@@ -1628,11 +2439,13 @@ class MigrationsApi {
1628
2439
  region,
1629
2440
  database,
1630
2441
  branch,
1631
- schema
2442
+ schema,
2443
+ schemaOperations,
2444
+ branchOperations
1632
2445
  }) {
1633
2446
  return operationsByTag.migrations.compareBranchWithUserSchema({
1634
2447
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1635
- body: { schema },
2448
+ body: { schema, schemaOperations, branchOperations },
1636
2449
  ...this.extraProps
1637
2450
  });
1638
2451
  }
@@ -1642,11 +2455,12 @@ class MigrationsApi {
1642
2455
  database,
1643
2456
  branch,
1644
2457
  compare,
1645
- schema
2458
+ sourceBranchOperations,
2459
+ targetBranchOperations
1646
2460
  }) {
1647
2461
  return operationsByTag.migrations.compareBranchSchemas({
1648
2462
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, branchName: compare },
1649
- body: { schema },
2463
+ body: { sourceBranchOperations, targetBranchOperations },
1650
2464
  ...this.extraProps
1651
2465
  });
1652
2466
  }
@@ -1689,6 +2503,19 @@ class MigrationsApi {
1689
2503
  ...this.extraProps
1690
2504
  });
1691
2505
  }
2506
+ pushBranchMigrations({
2507
+ workspace,
2508
+ region,
2509
+ database,
2510
+ branch,
2511
+ migrations
2512
+ }) {
2513
+ return operationsByTag.migrations.pushBranchMigrations({
2514
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2515
+ body: { migrations },
2516
+ ...this.extraProps
2517
+ });
2518
+ }
1692
2519
  }
1693
2520
  class DatabaseApi {
1694
2521
  constructor(extraProps) {
@@ -1703,11 +2530,13 @@ class DatabaseApi {
1703
2530
  createDatabase({
1704
2531
  workspace,
1705
2532
  database,
1706
- data
2533
+ data,
2534
+ headers
1707
2535
  }) {
1708
2536
  return operationsByTag.databases.createDatabase({
1709
2537
  pathParams: { workspaceId: workspace, dbName: database },
1710
2538
  body: data,
2539
+ headers,
1711
2540
  ...this.extraProps
1712
2541
  });
1713
2542
  }
@@ -1740,6 +2569,46 @@ class DatabaseApi {
1740
2569
  ...this.extraProps
1741
2570
  });
1742
2571
  }
2572
+ renameDatabase({
2573
+ workspace,
2574
+ database,
2575
+ newName
2576
+ }) {
2577
+ return operationsByTag.databases.renameDatabase({
2578
+ pathParams: { workspaceId: workspace, dbName: database },
2579
+ body: { newName },
2580
+ ...this.extraProps
2581
+ });
2582
+ }
2583
+ getDatabaseGithubSettings({
2584
+ workspace,
2585
+ database
2586
+ }) {
2587
+ return operationsByTag.databases.getDatabaseGithubSettings({
2588
+ pathParams: { workspaceId: workspace, dbName: database },
2589
+ ...this.extraProps
2590
+ });
2591
+ }
2592
+ updateDatabaseGithubSettings({
2593
+ workspace,
2594
+ database,
2595
+ settings
2596
+ }) {
2597
+ return operationsByTag.databases.updateDatabaseGithubSettings({
2598
+ pathParams: { workspaceId: workspace, dbName: database },
2599
+ body: settings,
2600
+ ...this.extraProps
2601
+ });
2602
+ }
2603
+ deleteDatabaseGithubSettings({
2604
+ workspace,
2605
+ database
2606
+ }) {
2607
+ return operationsByTag.databases.deleteDatabaseGithubSettings({
2608
+ pathParams: { workspaceId: workspace, dbName: database },
2609
+ ...this.extraProps
2610
+ });
2611
+ }
1743
2612
  listRegions({ workspace }) {
1744
2613
  return operationsByTag.databases.listRegions({
1745
2614
  pathParams: { workspaceId: workspace },
@@ -1749,27 +2618,200 @@ class DatabaseApi {
1749
2618
  }
1750
2619
 
1751
2620
  class XataApiPlugin {
1752
- async build(options) {
1753
- const { fetchImpl, apiKey } = await options.getFetchProps();
1754
- return new XataApiClient({ fetch: fetchImpl, apiKey });
2621
+ build(options) {
2622
+ return new XataApiClient(options);
1755
2623
  }
1756
2624
  }
1757
2625
 
1758
2626
  class XataPlugin {
1759
2627
  }
1760
2628
 
1761
- function generateUUID() {
1762
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
1763
- const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
1764
- return v.toString(16);
1765
- });
2629
+ function buildTransformString(transformations) {
2630
+ return transformations.flatMap(
2631
+ (t) => Object.entries(t).map(([key, value]) => {
2632
+ if (key === "trim") {
2633
+ const { left = 0, top = 0, right = 0, bottom = 0 } = value;
2634
+ return `${key}=${[top, right, bottom, left].join(";")}`;
2635
+ }
2636
+ if (key === "gravity" && typeof value === "object") {
2637
+ const { x = 0.5, y = 0.5 } = value;
2638
+ return `${key}=${[x, y].join("x")}`;
2639
+ }
2640
+ return `${key}=${value}`;
2641
+ })
2642
+ ).join(",");
2643
+ }
2644
+ function transformImage(url, ...transformations) {
2645
+ if (!isDefined(url))
2646
+ return void 0;
2647
+ const newTransformations = buildTransformString(transformations);
2648
+ const { hostname, pathname, search } = new URL(url);
2649
+ const pathParts = pathname.split("/");
2650
+ const transformIndex = pathParts.findIndex((part) => part === "transform");
2651
+ const removedItems = transformIndex >= 0 ? pathParts.splice(transformIndex, 2) : [];
2652
+ const transform = `/transform/${[removedItems[1], newTransformations].filter(isDefined).join(",")}`;
2653
+ const path = pathParts.join("/");
2654
+ return `https://${hostname}${transform}${path}${search}`;
1766
2655
  }
1767
2656
 
2657
+ class XataFile {
2658
+ constructor(file) {
2659
+ this.id = file.id;
2660
+ this.name = file.name || "";
2661
+ this.mediaType = file.mediaType || "application/octet-stream";
2662
+ this.base64Content = file.base64Content;
2663
+ this.enablePublicUrl = file.enablePublicUrl ?? false;
2664
+ this.signedUrlTimeout = file.signedUrlTimeout ?? 300;
2665
+ this.size = file.size ?? 0;
2666
+ this.version = file.version ?? 1;
2667
+ this.url = file.url || "";
2668
+ this.signedUrl = file.signedUrl;
2669
+ this.attributes = file.attributes || {};
2670
+ }
2671
+ static fromBuffer(buffer, options = {}) {
2672
+ const base64Content = buffer.toString("base64");
2673
+ return new XataFile({ ...options, base64Content });
2674
+ }
2675
+ toBuffer() {
2676
+ if (!this.base64Content) {
2677
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2678
+ }
2679
+ return Buffer.from(this.base64Content, "base64");
2680
+ }
2681
+ static fromArrayBuffer(arrayBuffer, options = {}) {
2682
+ const uint8Array = new Uint8Array(arrayBuffer);
2683
+ return this.fromUint8Array(uint8Array, options);
2684
+ }
2685
+ toArrayBuffer() {
2686
+ if (!this.base64Content) {
2687
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2688
+ }
2689
+ const binary = atob(this.base64Content);
2690
+ return new ArrayBuffer(binary.length);
2691
+ }
2692
+ static fromUint8Array(uint8Array, options = {}) {
2693
+ let binary = "";
2694
+ for (let i = 0; i < uint8Array.byteLength; i++) {
2695
+ binary += String.fromCharCode(uint8Array[i]);
2696
+ }
2697
+ const base64Content = btoa(binary);
2698
+ return new XataFile({ ...options, base64Content });
2699
+ }
2700
+ toUint8Array() {
2701
+ if (!this.base64Content) {
2702
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2703
+ }
2704
+ const binary = atob(this.base64Content);
2705
+ const uint8Array = new Uint8Array(binary.length);
2706
+ for (let i = 0; i < binary.length; i++) {
2707
+ uint8Array[i] = binary.charCodeAt(i);
2708
+ }
2709
+ return uint8Array;
2710
+ }
2711
+ static async fromBlob(file, options = {}) {
2712
+ const name = options.name ?? file.name;
2713
+ const mediaType = file.type;
2714
+ const arrayBuffer = await file.arrayBuffer();
2715
+ return this.fromArrayBuffer(arrayBuffer, { ...options, name, mediaType });
2716
+ }
2717
+ toBlob() {
2718
+ if (!this.base64Content) {
2719
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2720
+ }
2721
+ const binary = atob(this.base64Content);
2722
+ const uint8Array = new Uint8Array(binary.length);
2723
+ for (let i = 0; i < binary.length; i++) {
2724
+ uint8Array[i] = binary.charCodeAt(i);
2725
+ }
2726
+ return new Blob([uint8Array], { type: this.mediaType });
2727
+ }
2728
+ static fromString(string, options = {}) {
2729
+ const base64Content = btoa(string);
2730
+ return new XataFile({ ...options, base64Content });
2731
+ }
2732
+ toString() {
2733
+ if (!this.base64Content) {
2734
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2735
+ }
2736
+ return atob(this.base64Content);
2737
+ }
2738
+ static fromBase64(base64Content, options = {}) {
2739
+ return new XataFile({ ...options, base64Content });
2740
+ }
2741
+ toBase64() {
2742
+ if (!this.base64Content) {
2743
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2744
+ }
2745
+ return this.base64Content;
2746
+ }
2747
+ transform(...options) {
2748
+ return {
2749
+ url: transformImage(this.url, ...options),
2750
+ signedUrl: transformImage(this.signedUrl, ...options),
2751
+ metadataUrl: transformImage(this.url, ...options, { format: "json" }),
2752
+ metadataSignedUrl: transformImage(this.signedUrl, ...options, { format: "json" })
2753
+ };
2754
+ }
2755
+ }
2756
+ const parseInputFileEntry = async (entry) => {
2757
+ if (!isDefined(entry))
2758
+ return null;
2759
+ const { id, name, mediaType, base64Content, enablePublicUrl, signedUrlTimeout } = await entry;
2760
+ return compactObject({
2761
+ id,
2762
+ // Name cannot be an empty string in our API
2763
+ name: name ? name : void 0,
2764
+ mediaType,
2765
+ base64Content,
2766
+ enablePublicUrl,
2767
+ signedUrlTimeout
2768
+ });
2769
+ };
2770
+
1768
2771
  function cleanFilter(filter) {
1769
- if (!filter)
2772
+ if (!isDefined(filter))
1770
2773
  return void 0;
1771
- const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
1772
- return values.length > 0 ? filter : void 0;
2774
+ if (!isObject(filter))
2775
+ return filter;
2776
+ const values = Object.fromEntries(
2777
+ Object.entries(filter).reduce((acc, [key, value]) => {
2778
+ if (!isDefined(value))
2779
+ return acc;
2780
+ if (Array.isArray(value)) {
2781
+ const clean = value.map((item) => cleanFilter(item)).filter((item) => isDefined(item));
2782
+ if (clean.length === 0)
2783
+ return acc;
2784
+ return [...acc, [key, clean]];
2785
+ }
2786
+ if (isObject(value)) {
2787
+ const clean = cleanFilter(value);
2788
+ if (!isDefined(clean))
2789
+ return acc;
2790
+ return [...acc, [key, clean]];
2791
+ }
2792
+ return [...acc, [key, value]];
2793
+ }, [])
2794
+ );
2795
+ return Object.keys(values).length > 0 ? values : void 0;
2796
+ }
2797
+
2798
+ function stringifyJson(value) {
2799
+ if (!isDefined(value))
2800
+ return value;
2801
+ if (isString(value))
2802
+ return value;
2803
+ try {
2804
+ return JSON.stringify(value);
2805
+ } catch (e) {
2806
+ return value;
2807
+ }
2808
+ }
2809
+ function parseJson(value) {
2810
+ try {
2811
+ return JSON.parse(value);
2812
+ } catch (e) {
2813
+ return value;
2814
+ }
1773
2815
  }
1774
2816
 
1775
2817
  var __accessCheck$6 = (obj, member, msg) => {
@@ -1798,31 +2840,59 @@ class Page {
1798
2840
  this.meta = meta;
1799
2841
  this.records = new RecordArray(this, records);
1800
2842
  }
2843
+ /**
2844
+ * Retrieves the next page of results.
2845
+ * @param size Maximum number of results to be retrieved.
2846
+ * @param offset Number of results to skip when retrieving the results.
2847
+ * @returns The next page or results.
2848
+ */
1801
2849
  async nextPage(size, offset) {
1802
2850
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
1803
2851
  }
2852
+ /**
2853
+ * Retrieves the previous page of results.
2854
+ * @param size Maximum number of results to be retrieved.
2855
+ * @param offset Number of results to skip when retrieving the results.
2856
+ * @returns The previous page or results.
2857
+ */
1804
2858
  async previousPage(size, offset) {
1805
2859
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
1806
2860
  }
2861
+ /**
2862
+ * Retrieves the start page of results.
2863
+ * @param size Maximum number of results to be retrieved.
2864
+ * @param offset Number of results to skip when retrieving the results.
2865
+ * @returns The start page or results.
2866
+ */
1807
2867
  async startPage(size, offset) {
1808
2868
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, start: this.meta.page.cursor } });
1809
2869
  }
2870
+ /**
2871
+ * Retrieves the end page of results.
2872
+ * @param size Maximum number of results to be retrieved.
2873
+ * @param offset Number of results to skip when retrieving the results.
2874
+ * @returns The end page or results.
2875
+ */
1810
2876
  async endPage(size, offset) {
1811
2877
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, end: this.meta.page.cursor } });
1812
2878
  }
2879
+ /**
2880
+ * Shortcut method to check if there will be additional results if the next page of results is retrieved.
2881
+ * @returns Whether or not there will be additional results in the next page of results.
2882
+ */
1813
2883
  hasNextPage() {
1814
2884
  return this.meta.page.more;
1815
2885
  }
1816
2886
  }
1817
2887
  _query = new WeakMap();
1818
- const PAGINATION_MAX_SIZE = 200;
2888
+ const PAGINATION_MAX_SIZE = 1e3;
1819
2889
  const PAGINATION_DEFAULT_SIZE = 20;
1820
- const PAGINATION_MAX_OFFSET = 800;
2890
+ const PAGINATION_MAX_OFFSET = 49e3;
1821
2891
  const PAGINATION_DEFAULT_OFFSET = 0;
1822
2892
  function isCursorPaginationOptions(options) {
1823
2893
  return isDefined(options) && (isDefined(options.start) || isDefined(options.end) || isDefined(options.after) || isDefined(options.before));
1824
2894
  }
1825
- const _RecordArray = class extends Array {
2895
+ const _RecordArray = class _RecordArray extends Array {
1826
2896
  constructor(...args) {
1827
2897
  super(..._RecordArray.parseConstructorParams(...args));
1828
2898
  __privateAdd$6(this, _page, void 0);
@@ -1841,31 +2911,60 @@ const _RecordArray = class extends Array {
1841
2911
  toArray() {
1842
2912
  return new Array(...this);
1843
2913
  }
2914
+ toSerializable() {
2915
+ return JSON.parse(this.toString());
2916
+ }
2917
+ toString() {
2918
+ return JSON.stringify(this.toArray());
2919
+ }
1844
2920
  map(callbackfn, thisArg) {
1845
2921
  return this.toArray().map(callbackfn, thisArg);
1846
2922
  }
2923
+ /**
2924
+ * Retrieve next page of records
2925
+ *
2926
+ * @returns A new array of objects
2927
+ */
1847
2928
  async nextPage(size, offset) {
1848
2929
  const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1849
2930
  return new _RecordArray(newPage);
1850
2931
  }
2932
+ /**
2933
+ * Retrieve previous page of records
2934
+ *
2935
+ * @returns A new array of objects
2936
+ */
1851
2937
  async previousPage(size, offset) {
1852
2938
  const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1853
2939
  return new _RecordArray(newPage);
1854
2940
  }
2941
+ /**
2942
+ * Retrieve start page of records
2943
+ *
2944
+ * @returns A new array of objects
2945
+ */
1855
2946
  async startPage(size, offset) {
1856
2947
  const newPage = await __privateGet$6(this, _page).startPage(size, offset);
1857
2948
  return new _RecordArray(newPage);
1858
2949
  }
2950
+ /**
2951
+ * Retrieve end page of records
2952
+ *
2953
+ * @returns A new array of objects
2954
+ */
1859
2955
  async endPage(size, offset) {
1860
2956
  const newPage = await __privateGet$6(this, _page).endPage(size, offset);
1861
2957
  return new _RecordArray(newPage);
1862
2958
  }
2959
+ /**
2960
+ * @returns Boolean indicating if there is a next page
2961
+ */
1863
2962
  hasNextPage() {
1864
2963
  return __privateGet$6(this, _page).meta.page.more;
1865
2964
  }
1866
2965
  };
1867
- let RecordArray = _RecordArray;
1868
2966
  _page = new WeakMap();
2967
+ let RecordArray = _RecordArray;
1869
2968
 
1870
2969
  var __accessCheck$5 = (obj, member, msg) => {
1871
2970
  if (!member.has(obj))
@@ -1890,13 +2989,14 @@ var __privateMethod$3 = (obj, member, method) => {
1890
2989
  return method;
1891
2990
  };
1892
2991
  var _table$1, _repository, _data, _cleanFilterConstraint, cleanFilterConstraint_fn;
1893
- const _Query = class {
2992
+ const _Query = class _Query {
1894
2993
  constructor(repository, table, data, rawParent) {
1895
2994
  __privateAdd$5(this, _cleanFilterConstraint);
1896
2995
  __privateAdd$5(this, _table$1, void 0);
1897
2996
  __privateAdd$5(this, _repository, void 0);
1898
2997
  __privateAdd$5(this, _data, { filter: {} });
1899
- this.meta = { page: { cursor: "start", more: true } };
2998
+ // Implements pagination
2999
+ this.meta = { page: { cursor: "start", more: true, size: PAGINATION_DEFAULT_SIZE } };
1900
3000
  this.records = new RecordArray(this, []);
1901
3001
  __privateSet$5(this, _table$1, table);
1902
3002
  if (repository) {
@@ -1912,6 +3012,7 @@ const _Query = class {
1912
3012
  __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1913
3013
  __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1914
3014
  __privateGet$5(this, _data).columns = data.columns ?? parent?.columns;
3015
+ __privateGet$5(this, _data).consistency = data.consistency ?? parent?.consistency;
1915
3016
  __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1916
3017
  __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
1917
3018
  __privateGet$5(this, _data).fetchOptions = data.fetchOptions ?? parent?.fetchOptions;
@@ -1932,18 +3033,38 @@ const _Query = class {
1932
3033
  const key = JSON.stringify({ columns, filter, sort, pagination });
1933
3034
  return toBase64(key);
1934
3035
  }
3036
+ /**
3037
+ * Builds a new query object representing a logical OR between the given subqueries.
3038
+ * @param queries An array of subqueries.
3039
+ * @returns A new Query object.
3040
+ */
1935
3041
  any(...queries) {
1936
3042
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
1937
3043
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
1938
3044
  }
3045
+ /**
3046
+ * Builds a new query object representing a logical AND between the given subqueries.
3047
+ * @param queries An array of subqueries.
3048
+ * @returns A new Query object.
3049
+ */
1939
3050
  all(...queries) {
1940
3051
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
1941
3052
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1942
3053
  }
3054
+ /**
3055
+ * Builds a new query object representing a logical OR negating each subquery. In pseudo-code: !q1 OR !q2
3056
+ * @param queries An array of subqueries.
3057
+ * @returns A new Query object.
3058
+ */
1943
3059
  not(...queries) {
1944
3060
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
1945
3061
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
1946
3062
  }
3063
+ /**
3064
+ * Builds a new query object representing a logical AND negating each subquery. In pseudo-code: !q1 AND !q2
3065
+ * @param queries An array of subqueries.
3066
+ * @returns A new Query object.
3067
+ */
1947
3068
  none(...queries) {
1948
3069
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
1949
3070
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
@@ -1966,6 +3087,11 @@ const _Query = class {
1966
3087
  const sort = [...originalSort, { column, direction }];
1967
3088
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
1968
3089
  }
3090
+ /**
3091
+ * Builds a new query specifying the set of columns to be returned in the query response.
3092
+ * @param columns Array of column names to be returned by the query.
3093
+ * @returns A new Query object.
3094
+ */
1969
3095
  select(columns) {
1970
3096
  return new _Query(
1971
3097
  __privateGet$5(this, _repository),
@@ -1978,6 +3104,12 @@ const _Query = class {
1978
3104
  const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
1979
3105
  return __privateGet$5(this, _repository).query(query);
1980
3106
  }
3107
+ /**
3108
+ * Get results in an iterator
3109
+ *
3110
+ * @async
3111
+ * @returns Async interable of results
3112
+ */
1981
3113
  async *[Symbol.asyncIterator]() {
1982
3114
  for await (const [record] of this.getIterator({ batchSize: 1 })) {
1983
3115
  yield record;
@@ -2038,26 +3170,53 @@ const _Query = class {
2038
3170
  );
2039
3171
  return __privateGet$5(this, _repository).summarizeTable(query, summaries, summariesFilter);
2040
3172
  }
3173
+ /**
3174
+ * Builds a new query object adding a cache TTL in milliseconds.
3175
+ * @param ttl The cache TTL in milliseconds.
3176
+ * @returns A new Query object.
3177
+ */
2041
3178
  cache(ttl) {
2042
3179
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
2043
3180
  }
3181
+ /**
3182
+ * Retrieve next page of records
3183
+ *
3184
+ * @returns A new page object.
3185
+ */
2044
3186
  nextPage(size, offset) {
2045
3187
  return this.startPage(size, offset);
2046
3188
  }
3189
+ /**
3190
+ * Retrieve previous page of records
3191
+ *
3192
+ * @returns A new page object
3193
+ */
2047
3194
  previousPage(size, offset) {
2048
3195
  return this.startPage(size, offset);
2049
3196
  }
3197
+ /**
3198
+ * Retrieve start page of records
3199
+ *
3200
+ * @returns A new page object
3201
+ */
2050
3202
  startPage(size, offset) {
2051
3203
  return this.getPaginated({ pagination: { size, offset } });
2052
3204
  }
3205
+ /**
3206
+ * Retrieve last page of records
3207
+ *
3208
+ * @returns A new page object
3209
+ */
2053
3210
  endPage(size, offset) {
2054
3211
  return this.getPaginated({ pagination: { size, offset, before: "end" } });
2055
3212
  }
3213
+ /**
3214
+ * @returns Boolean indicating if there is a next page
3215
+ */
2056
3216
  hasNextPage() {
2057
3217
  return this.meta.page.more;
2058
3218
  }
2059
3219
  };
2060
- let Query = _Query;
2061
3220
  _table$1 = new WeakMap();
2062
3221
  _repository = new WeakMap();
2063
3222
  _data = new WeakMap();
@@ -2072,6 +3231,7 @@ cleanFilterConstraint_fn = function(column, value) {
2072
3231
  }
2073
3232
  return value;
2074
3233
  };
3234
+ let Query = _Query;
2075
3235
  function cleanParent(data, parent) {
2076
3236
  if (isCursorPaginationOptions(data.pagination)) {
2077
3237
  return { ...parent, sort: void 0, filter: void 0 };
@@ -2079,6 +3239,22 @@ function cleanParent(data, parent) {
2079
3239
  return parent;
2080
3240
  }
2081
3241
 
3242
+ const RecordColumnTypes = [
3243
+ "bool",
3244
+ "int",
3245
+ "float",
3246
+ "string",
3247
+ "text",
3248
+ "email",
3249
+ "multiple",
3250
+ "link",
3251
+ "object",
3252
+ "datetime",
3253
+ "vector",
3254
+ "file[]",
3255
+ "file",
3256
+ "json"
3257
+ ];
2082
3258
  function isIdentifiable(x) {
2083
3259
  return isObject(x) && isString(x?.id);
2084
3260
  }
@@ -2088,11 +3264,33 @@ function isXataRecord(x) {
2088
3264
  return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
2089
3265
  }
2090
3266
 
3267
+ function isValidExpandedColumn(column) {
3268
+ return isObject(column) && isString(column.name);
3269
+ }
3270
+ function isValidSelectableColumns(columns) {
3271
+ if (!Array.isArray(columns)) {
3272
+ return false;
3273
+ }
3274
+ return columns.every((column) => {
3275
+ if (typeof column === "string") {
3276
+ return true;
3277
+ }
3278
+ if (typeof column === "object") {
3279
+ return isValidExpandedColumn(column);
3280
+ }
3281
+ return false;
3282
+ });
3283
+ }
3284
+
2091
3285
  function isSortFilterString(value) {
2092
3286
  return isString(value);
2093
3287
  }
2094
3288
  function isSortFilterBase(filter) {
2095
- return isObject(filter) && Object.values(filter).every((value) => value === "asc" || value === "desc");
3289
+ return isObject(filter) && Object.entries(filter).every(([key, value]) => {
3290
+ if (key === "*")
3291
+ return value === "random";
3292
+ return value === "asc" || value === "desc";
3293
+ });
2096
3294
  }
2097
3295
  function isSortFilterObject(filter) {
2098
3296
  return isObject(filter) && !isSortFilterBase(filter) && filter.column !== void 0;
@@ -2133,7 +3331,8 @@ var __privateMethod$2 = (obj, member, method) => {
2133
3331
  __accessCheck$4(obj, member, "access private method");
2134
3332
  return method;
2135
3333
  };
2136
- 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;
3334
+ 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, _transformObjectToApi, transformObjectToApi_fn;
3335
+ const BULK_OPERATION_MAX_SIZE = 1e3;
2137
3336
  class Repository extends Query {
2138
3337
  }
2139
3338
  class RestRepository extends Query {
@@ -2145,13 +3344,16 @@ class RestRepository extends Query {
2145
3344
  );
2146
3345
  __privateAdd$4(this, _insertRecordWithoutId);
2147
3346
  __privateAdd$4(this, _insertRecordWithId);
2148
- __privateAdd$4(this, _bulkInsertTableRecords);
3347
+ __privateAdd$4(this, _insertRecords);
2149
3348
  __privateAdd$4(this, _updateRecordWithID);
3349
+ __privateAdd$4(this, _updateRecords);
2150
3350
  __privateAdd$4(this, _upsertRecordWithID);
2151
3351
  __privateAdd$4(this, _deleteRecord);
3352
+ __privateAdd$4(this, _deleteRecords);
2152
3353
  __privateAdd$4(this, _setCacheQuery);
2153
3354
  __privateAdd$4(this, _getCacheQuery);
2154
3355
  __privateAdd$4(this, _getSchemaTables$1);
3356
+ __privateAdd$4(this, _transformObjectToApi);
2155
3357
  __privateAdd$4(this, _table, void 0);
2156
3358
  __privateAdd$4(this, _getFetchProps, void 0);
2157
3359
  __privateAdd$4(this, _db, void 0);
@@ -2162,10 +3364,7 @@ class RestRepository extends Query {
2162
3364
  __privateSet$4(this, _db, options.db);
2163
3365
  __privateSet$4(this, _cache, options.pluginOptions.cache);
2164
3366
  __privateSet$4(this, _schemaTables$2, options.schemaTables);
2165
- __privateSet$4(this, _getFetchProps, async () => {
2166
- const props = await options.pluginOptions.getFetchProps();
2167
- return { ...props, sessionID: generateUUID() };
2168
- });
3367
+ __privateSet$4(this, _getFetchProps, () => ({ ...options.pluginOptions, sessionID: generateUUID() }));
2169
3368
  const trace = options.pluginOptions.trace ?? defaultTrace;
2170
3369
  __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
2171
3370
  return trace(name, fn, {
@@ -2182,23 +3381,25 @@ class RestRepository extends Query {
2182
3381
  if (Array.isArray(a)) {
2183
3382
  if (a.length === 0)
2184
3383
  return [];
2185
- const columns = isStringArray(b) ? b : void 0;
2186
- return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
3384
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: true });
3385
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3386
+ const result = await this.read(ids, columns);
3387
+ return result;
2187
3388
  }
2188
3389
  if (isString(a) && isObject(b)) {
2189
3390
  if (a === "")
2190
3391
  throw new Error("The id can't be empty");
2191
- const columns = isStringArray(c) ? c : void 0;
2192
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
3392
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3393
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
2193
3394
  }
2194
3395
  if (isObject(a) && isString(a.id)) {
2195
3396
  if (a.id === "")
2196
3397
  throw new Error("The id can't be empty");
2197
- const columns = isStringArray(b) ? b : void 0;
2198
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
3398
+ const columns = isValidSelectableColumns(b) ? b : void 0;
3399
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
2199
3400
  }
2200
3401
  if (isObject(a)) {
2201
- const columns = isStringArray(b) ? b : void 0;
3402
+ const columns = isValidSelectableColumns(b) ? b : void 0;
2202
3403
  return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
2203
3404
  }
2204
3405
  throw new Error("Invalid arguments for create method");
@@ -2206,7 +3407,7 @@ class RestRepository extends Query {
2206
3407
  }
2207
3408
  async read(a, b) {
2208
3409
  return __privateGet$4(this, _trace).call(this, "read", async () => {
2209
- const columns = isStringArray(b) ? b : ["*"];
3410
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2210
3411
  if (Array.isArray(a)) {
2211
3412
  if (a.length === 0)
2212
3413
  return [];
@@ -2220,7 +3421,6 @@ class RestRepository extends Query {
2220
3421
  }
2221
3422
  const id = extractId(a);
2222
3423
  if (id) {
2223
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2224
3424
  try {
2225
3425
  const response = await getRecord({
2226
3426
  pathParams: {
@@ -2231,10 +3431,16 @@ class RestRepository extends Query {
2231
3431
  recordId: id
2232
3432
  },
2233
3433
  queryParams: { columns },
2234
- ...fetchProps
3434
+ ...__privateGet$4(this, _getFetchProps).call(this)
2235
3435
  });
2236
3436
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2237
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
3437
+ return initObject(
3438
+ __privateGet$4(this, _db),
3439
+ schemaTables,
3440
+ __privateGet$4(this, _table),
3441
+ response,
3442
+ columns
3443
+ );
2238
3444
  } catch (e) {
2239
3445
  if (isObject(e) && e.status === 404) {
2240
3446
  return null;
@@ -2270,19 +3476,29 @@ class RestRepository extends Query {
2270
3476
  if (Array.isArray(a)) {
2271
3477
  if (a.length === 0)
2272
3478
  return [];
2273
- if (a.length > 100) {
2274
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
2275
- }
2276
- const columns = isStringArray(b) ? b : ["*"];
2277
- return Promise.all(a.map((object) => this.update(object, columns)));
2278
- }
2279
- if (isString(a) && isObject(b)) {
2280
- const columns = isStringArray(c) ? c : void 0;
2281
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3479
+ const existing = await this.read(a, ["id"]);
3480
+ const updates = a.filter((_item, index) => existing[index] !== null);
3481
+ await __privateMethod$2(this, _updateRecords, updateRecords_fn).call(this, updates, {
3482
+ ifVersion,
3483
+ upsert: false
3484
+ });
3485
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3486
+ const result = await this.read(a, columns);
3487
+ return result;
2282
3488
  }
2283
- if (isObject(a) && isString(a.id)) {
2284
- const columns = isStringArray(b) ? b : void 0;
2285
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3489
+ try {
3490
+ if (isString(a) && isObject(b)) {
3491
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3492
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3493
+ }
3494
+ if (isObject(a) && isString(a.id)) {
3495
+ const columns = isValidSelectableColumns(b) ? b : void 0;
3496
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3497
+ }
3498
+ } catch (error) {
3499
+ if (error.status === 422)
3500
+ return null;
3501
+ throw error;
2286
3502
  }
2287
3503
  throw new Error("Invalid arguments for update method");
2288
3504
  });
@@ -2312,19 +3528,31 @@ class RestRepository extends Query {
2312
3528
  if (Array.isArray(a)) {
2313
3529
  if (a.length === 0)
2314
3530
  return [];
2315
- if (a.length > 100) {
2316
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
2317
- }
2318
- const columns = isStringArray(b) ? b : ["*"];
2319
- return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
3531
+ await __privateMethod$2(this, _updateRecords, updateRecords_fn).call(this, a, {
3532
+ ifVersion,
3533
+ upsert: true
3534
+ });
3535
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3536
+ const result = await this.read(a, columns);
3537
+ return result;
2320
3538
  }
2321
3539
  if (isString(a) && isObject(b)) {
2322
- const columns = isStringArray(c) ? c : void 0;
2323
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3540
+ if (a === "")
3541
+ throw new Error("The id can't be empty");
3542
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3543
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2324
3544
  }
2325
3545
  if (isObject(a) && isString(a.id)) {
2326
- const columns = isStringArray(c) ? c : void 0;
2327
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3546
+ if (a.id === "")
3547
+ throw new Error("The id can't be empty");
3548
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3549
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3550
+ }
3551
+ if (!isDefined(a) && isObject(b)) {
3552
+ return await this.create(b, c);
3553
+ }
3554
+ if (isObject(a) && !isDefined(a.id)) {
3555
+ return await this.create(a, b);
2328
3556
  }
2329
3557
  throw new Error("Invalid arguments for createOrUpdate method");
2330
3558
  });
@@ -2335,16 +3563,28 @@ class RestRepository extends Query {
2335
3563
  if (Array.isArray(a)) {
2336
3564
  if (a.length === 0)
2337
3565
  return [];
2338
- const columns = isStringArray(b) ? b : ["*"];
2339
- return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
3566
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: false });
3567
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3568
+ const result = await this.read(ids, columns);
3569
+ return result;
2340
3570
  }
2341
3571
  if (isString(a) && isObject(b)) {
2342
- const columns = isStringArray(c) ? c : void 0;
2343
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
3572
+ if (a === "")
3573
+ throw new Error("The id can't be empty");
3574
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3575
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
2344
3576
  }
2345
3577
  if (isObject(a) && isString(a.id)) {
2346
- const columns = isStringArray(c) ? c : void 0;
2347
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3578
+ if (a.id === "")
3579
+ throw new Error("The id can't be empty");
3580
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3581
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3582
+ }
3583
+ if (!isDefined(a) && isObject(b)) {
3584
+ return await this.create(b, c);
3585
+ }
3586
+ if (isObject(a) && !isDefined(a.id)) {
3587
+ return await this.create(a, b);
2348
3588
  }
2349
3589
  throw new Error("Invalid arguments for createOrReplace method");
2350
3590
  });
@@ -2354,10 +3594,17 @@ class RestRepository extends Query {
2354
3594
  if (Array.isArray(a)) {
2355
3595
  if (a.length === 0)
2356
3596
  return [];
2357
- if (a.length > 100) {
2358
- console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
2359
- }
2360
- return Promise.all(a.map((id) => this.delete(id, b)));
3597
+ const ids = a.map((o) => {
3598
+ if (isString(o))
3599
+ return o;
3600
+ if (isString(o.id))
3601
+ return o.id;
3602
+ throw new Error("Invalid arguments for delete method");
3603
+ });
3604
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3605
+ const result = await this.read(a, columns);
3606
+ await __privateMethod$2(this, _deleteRecords, deleteRecords_fn).call(this, ids);
3607
+ return result;
2361
3608
  }
2362
3609
  if (isString(a)) {
2363
3610
  return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
@@ -2388,7 +3635,6 @@ class RestRepository extends Query {
2388
3635
  }
2389
3636
  async search(query, options = {}) {
2390
3637
  return __privateGet$4(this, _trace).call(this, "search", async () => {
2391
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2392
3638
  const { records } = await searchTable({
2393
3639
  pathParams: {
2394
3640
  workspace: "{workspaceId}",
@@ -2402,9 +3648,33 @@ class RestRepository extends Query {
2402
3648
  prefix: options.prefix,
2403
3649
  highlight: options.highlight,
2404
3650
  filter: options.filter,
2405
- boosters: options.boosters
3651
+ boosters: options.boosters,
3652
+ page: options.page,
3653
+ target: options.target
3654
+ },
3655
+ ...__privateGet$4(this, _getFetchProps).call(this)
3656
+ });
3657
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3658
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
3659
+ });
3660
+ }
3661
+ async vectorSearch(column, query, options) {
3662
+ return __privateGet$4(this, _trace).call(this, "vectorSearch", async () => {
3663
+ const { records } = await vectorSearchTable({
3664
+ pathParams: {
3665
+ workspace: "{workspaceId}",
3666
+ dbBranchName: "{dbBranch}",
3667
+ region: "{region}",
3668
+ tableName: __privateGet$4(this, _table)
3669
+ },
3670
+ body: {
3671
+ column,
3672
+ queryVector: query,
3673
+ similarityFunction: options?.similarityFunction,
3674
+ size: options?.size,
3675
+ filter: options?.filter
2406
3676
  },
2407
- ...fetchProps
3677
+ ...__privateGet$4(this, _getFetchProps).call(this)
2408
3678
  });
2409
3679
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2410
3680
  return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
@@ -2412,7 +3682,6 @@ class RestRepository extends Query {
2412
3682
  }
2413
3683
  async aggregate(aggs, filter) {
2414
3684
  return __privateGet$4(this, _trace).call(this, "aggregate", async () => {
2415
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2416
3685
  const result = await aggregateTable({
2417
3686
  pathParams: {
2418
3687
  workspace: "{workspaceId}",
@@ -2421,7 +3690,7 @@ class RestRepository extends Query {
2421
3690
  tableName: __privateGet$4(this, _table)
2422
3691
  },
2423
3692
  body: { aggs, filter },
2424
- ...fetchProps
3693
+ ...__privateGet$4(this, _getFetchProps).call(this)
2425
3694
  });
2426
3695
  return result;
2427
3696
  });
@@ -2432,7 +3701,6 @@ class RestRepository extends Query {
2432
3701
  if (cacheQuery)
2433
3702
  return new Page(query, cacheQuery.meta, cacheQuery.records);
2434
3703
  const data = query.getQueryOptions();
2435
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2436
3704
  const { meta, records: objects } = await queryTable({
2437
3705
  pathParams: {
2438
3706
  workspace: "{workspaceId}",
@@ -2444,14 +3712,21 @@ class RestRepository extends Query {
2444
3712
  filter: cleanFilter(data.filter),
2445
3713
  sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2446
3714
  page: data.pagination,
2447
- columns: data.columns ?? ["*"]
3715
+ columns: data.columns ?? ["*"],
3716
+ consistency: data.consistency
2448
3717
  },
2449
3718
  fetchOptions: data.fetchOptions,
2450
- ...fetchProps
3719
+ ...__privateGet$4(this, _getFetchProps).call(this)
2451
3720
  });
2452
3721
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2453
3722
  const records = objects.map(
2454
- (record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record, data.columns ?? ["*"])
3723
+ (record) => initObject(
3724
+ __privateGet$4(this, _db),
3725
+ schemaTables,
3726
+ __privateGet$4(this, _table),
3727
+ record,
3728
+ data.columns ?? ["*"]
3729
+ )
2455
3730
  );
2456
3731
  await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
2457
3732
  return new Page(query, meta, records);
@@ -2460,7 +3735,6 @@ class RestRepository extends Query {
2460
3735
  async summarizeTable(query, summaries, summariesFilter) {
2461
3736
  return __privateGet$4(this, _trace).call(this, "summarize", async () => {
2462
3737
  const data = query.getQueryOptions();
2463
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2464
3738
  const result = await summarizeTable({
2465
3739
  pathParams: {
2466
3740
  workspace: "{workspaceId}",
@@ -2472,15 +3746,55 @@ class RestRepository extends Query {
2472
3746
  filter: cleanFilter(data.filter),
2473
3747
  sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2474
3748
  columns: data.columns,
3749
+ consistency: data.consistency,
2475
3750
  page: data.pagination?.size !== void 0 ? { size: data.pagination?.size } : void 0,
2476
3751
  summaries,
2477
3752
  summariesFilter
2478
3753
  },
2479
- ...fetchProps
3754
+ ...__privateGet$4(this, _getFetchProps).call(this)
2480
3755
  });
2481
- return result;
3756
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3757
+ return {
3758
+ ...result,
3759
+ summaries: result.summaries.map(
3760
+ (summary) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), summary, data.columns ?? [])
3761
+ )
3762
+ };
2482
3763
  });
2483
3764
  }
3765
+ ask(question, options) {
3766
+ const questionParam = options?.sessionId ? { message: question } : { question };
3767
+ const params = {
3768
+ pathParams: {
3769
+ workspace: "{workspaceId}",
3770
+ dbBranchName: "{dbBranch}",
3771
+ region: "{region}",
3772
+ tableName: __privateGet$4(this, _table),
3773
+ sessionId: options?.sessionId
3774
+ },
3775
+ body: {
3776
+ ...questionParam,
3777
+ rules: options?.rules,
3778
+ searchType: options?.searchType,
3779
+ search: options?.searchType === "keyword" ? options?.search : void 0,
3780
+ vectorSearch: options?.searchType === "vector" ? options?.vectorSearch : void 0
3781
+ },
3782
+ ...__privateGet$4(this, _getFetchProps).call(this)
3783
+ };
3784
+ if (options?.onMessage) {
3785
+ fetchSSERequest({
3786
+ endpoint: "dataPlane",
3787
+ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}",
3788
+ method: "POST",
3789
+ onMessage: (message) => {
3790
+ options.onMessage?.({ answer: message.text, records: message.records });
3791
+ },
3792
+ ...params
3793
+ });
3794
+ } else {
3795
+ return askTableSession(params);
3796
+ }
3797
+ }
2484
3798
  }
2485
3799
  _table = new WeakMap();
2486
3800
  _getFetchProps = new WeakMap();
@@ -2490,8 +3804,7 @@ _schemaTables$2 = new WeakMap();
2490
3804
  _trace = new WeakMap();
2491
3805
  _insertRecordWithoutId = new WeakSet();
2492
3806
  insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
2493
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2494
- const record = transformObjectLinks(object);
3807
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2495
3808
  const response = await insertRecord({
2496
3809
  pathParams: {
2497
3810
  workspace: "{workspaceId}",
@@ -2501,15 +3814,16 @@ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
2501
3814
  },
2502
3815
  queryParams: { columns },
2503
3816
  body: record,
2504
- ...fetchProps
3817
+ ...__privateGet$4(this, _getFetchProps).call(this)
2505
3818
  });
2506
3819
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2507
3820
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2508
3821
  };
2509
3822
  _insertRecordWithId = new WeakSet();
2510
3823
  insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { createOnly, ifVersion }) {
2511
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2512
- const record = transformObjectLinks(object);
3824
+ if (!recordId)
3825
+ return null;
3826
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2513
3827
  const response = await insertRecordWithID({
2514
3828
  pathParams: {
2515
3829
  workspace: "{workspaceId}",
@@ -2520,36 +3834,44 @@ insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { crea
2520
3834
  },
2521
3835
  body: record,
2522
3836
  queryParams: { createOnly, columns, ifVersion },
2523
- ...fetchProps
3837
+ ...__privateGet$4(this, _getFetchProps).call(this)
2524
3838
  });
2525
3839
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2526
3840
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2527
3841
  };
2528
- _bulkInsertTableRecords = new WeakSet();
2529
- bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
2530
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2531
- const records = objects.map((object) => transformObjectLinks(object));
2532
- const response = await bulkInsertTableRecords({
2533
- pathParams: {
2534
- workspace: "{workspaceId}",
2535
- dbBranchName: "{dbBranch}",
2536
- region: "{region}",
2537
- tableName: __privateGet$4(this, _table)
2538
- },
2539
- queryParams: { columns },
2540
- body: { records },
2541
- ...fetchProps
3842
+ _insertRecords = new WeakSet();
3843
+ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
3844
+ const operations = await promiseMap(objects, async (object) => {
3845
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3846
+ return { insert: { table: __privateGet$4(this, _table), record, createOnly, ifVersion } };
2542
3847
  });
2543
- if (!isResponseWithRecords(response)) {
2544
- throw new Error("Request included columns but server didn't include them");
3848
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
3849
+ const ids = [];
3850
+ for (const operations2 of chunkedOperations) {
3851
+ const { results } = await branchTransaction({
3852
+ pathParams: {
3853
+ workspace: "{workspaceId}",
3854
+ dbBranchName: "{dbBranch}",
3855
+ region: "{region}"
3856
+ },
3857
+ body: { operations: operations2 },
3858
+ ...__privateGet$4(this, _getFetchProps).call(this)
3859
+ });
3860
+ for (const result of results) {
3861
+ if (result.operation === "insert") {
3862
+ ids.push(result.id);
3863
+ } else {
3864
+ ids.push(null);
3865
+ }
3866
+ }
2545
3867
  }
2546
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2547
- return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, columns));
3868
+ return ids;
2548
3869
  };
2549
3870
  _updateRecordWithID = new WeakSet();
2550
3871
  updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2551
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2552
- const { id: _id, ...record } = transformObjectLinks(object);
3872
+ if (!recordId)
3873
+ return null;
3874
+ const { id: _id, ...record } = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2553
3875
  try {
2554
3876
  const response = await updateRecordWithID({
2555
3877
  pathParams: {
@@ -2561,7 +3883,7 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2561
3883
  },
2562
3884
  queryParams: { columns, ifVersion },
2563
3885
  body: record,
2564
- ...fetchProps
3886
+ ...__privateGet$4(this, _getFetchProps).call(this)
2565
3887
  });
2566
3888
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2567
3889
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2572,9 +3894,38 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2572
3894
  throw e;
2573
3895
  }
2574
3896
  };
3897
+ _updateRecords = new WeakSet();
3898
+ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
3899
+ const operations = await promiseMap(objects, async ({ id, ...object }) => {
3900
+ const fields = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3901
+ return { update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields } };
3902
+ });
3903
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
3904
+ const ids = [];
3905
+ for (const operations2 of chunkedOperations) {
3906
+ const { results } = await branchTransaction({
3907
+ pathParams: {
3908
+ workspace: "{workspaceId}",
3909
+ dbBranchName: "{dbBranch}",
3910
+ region: "{region}"
3911
+ },
3912
+ body: { operations: operations2 },
3913
+ ...__privateGet$4(this, _getFetchProps).call(this)
3914
+ });
3915
+ for (const result of results) {
3916
+ if (result.operation === "update") {
3917
+ ids.push(result.id);
3918
+ } else {
3919
+ ids.push(null);
3920
+ }
3921
+ }
3922
+ }
3923
+ return ids;
3924
+ };
2575
3925
  _upsertRecordWithID = new WeakSet();
2576
3926
  upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2577
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
3927
+ if (!recordId)
3928
+ return null;
2578
3929
  const response = await upsertRecordWithID({
2579
3930
  pathParams: {
2580
3931
  workspace: "{workspaceId}",
@@ -2585,14 +3936,15 @@ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2585
3936
  },
2586
3937
  queryParams: { columns, ifVersion },
2587
3938
  body: object,
2588
- ...fetchProps
3939
+ ...__privateGet$4(this, _getFetchProps).call(this)
2589
3940
  });
2590
3941
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2591
3942
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2592
3943
  };
2593
3944
  _deleteRecord = new WeakSet();
2594
3945
  deleteRecord_fn = async function(recordId, columns = ["*"]) {
2595
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
3946
+ if (!recordId)
3947
+ return null;
2596
3948
  try {
2597
3949
  const response = await deleteRecord({
2598
3950
  pathParams: {
@@ -2603,7 +3955,7 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2603
3955
  recordId
2604
3956
  },
2605
3957
  queryParams: { columns },
2606
- ...fetchProps
3958
+ ...__privateGet$4(this, _getFetchProps).call(this)
2607
3959
  });
2608
3960
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2609
3961
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2614,17 +3966,36 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2614
3966
  throw e;
2615
3967
  }
2616
3968
  };
3969
+ _deleteRecords = new WeakSet();
3970
+ deleteRecords_fn = async function(recordIds) {
3971
+ const chunkedOperations = chunk(
3972
+ compact(recordIds).map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
3973
+ BULK_OPERATION_MAX_SIZE
3974
+ );
3975
+ for (const operations of chunkedOperations) {
3976
+ await branchTransaction({
3977
+ pathParams: {
3978
+ workspace: "{workspaceId}",
3979
+ dbBranchName: "{dbBranch}",
3980
+ region: "{region}"
3981
+ },
3982
+ body: { operations },
3983
+ ...__privateGet$4(this, _getFetchProps).call(this)
3984
+ });
3985
+ }
3986
+ };
2617
3987
  _setCacheQuery = new WeakSet();
2618
3988
  setCacheQuery_fn = async function(query, meta, records) {
2619
- await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
3989
+ await __privateGet$4(this, _cache)?.set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: /* @__PURE__ */ new Date(), meta, records });
2620
3990
  };
2621
3991
  _getCacheQuery = new WeakSet();
2622
3992
  getCacheQuery_fn = async function(query) {
2623
3993
  const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
2624
- const result = await __privateGet$4(this, _cache).get(key);
3994
+ const result = await __privateGet$4(this, _cache)?.get(key);
2625
3995
  if (!result)
2626
3996
  return null;
2627
- const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
3997
+ const defaultTTL = __privateGet$4(this, _cache)?.defaultQueryTTL ?? -1;
3998
+ const { cache: ttl = defaultTTL } = query.getQueryOptions();
2628
3999
  if (ttl < 0)
2629
4000
  return null;
2630
4001
  const hasExpired = result.date.getTime() + ttl < Date.now();
@@ -2634,39 +4005,66 @@ _getSchemaTables$1 = new WeakSet();
2634
4005
  getSchemaTables_fn$1 = async function() {
2635
4006
  if (__privateGet$4(this, _schemaTables$2))
2636
4007
  return __privateGet$4(this, _schemaTables$2);
2637
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2638
4008
  const { schema } = await getBranchDetails({
2639
4009
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
2640
- ...fetchProps
4010
+ ...__privateGet$4(this, _getFetchProps).call(this)
2641
4011
  });
2642
4012
  __privateSet$4(this, _schemaTables$2, schema.tables);
2643
4013
  return schema.tables;
2644
4014
  };
2645
- const transformObjectLinks = (object) => {
2646
- return Object.entries(object).reduce((acc, [key, value]) => {
4015
+ _transformObjectToApi = new WeakSet();
4016
+ transformObjectToApi_fn = async function(object) {
4017
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
4018
+ const schema = schemaTables.find((table) => table.name === __privateGet$4(this, _table));
4019
+ if (!schema)
4020
+ throw new Error(`Table ${__privateGet$4(this, _table)} not found in schema`);
4021
+ const result = {};
4022
+ for (const [key, value] of Object.entries(object)) {
2647
4023
  if (key === "xata")
2648
- return acc;
2649
- return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
2650
- }, {});
4024
+ continue;
4025
+ const type = schema.columns.find((column) => column.name === key)?.type;
4026
+ switch (type) {
4027
+ case "link": {
4028
+ result[key] = isIdentifiable(value) ? value.id : value;
4029
+ break;
4030
+ }
4031
+ case "datetime": {
4032
+ result[key] = value instanceof Date ? value.toISOString() : value;
4033
+ break;
4034
+ }
4035
+ case `file`:
4036
+ result[key] = await parseInputFileEntry(value);
4037
+ break;
4038
+ case "file[]":
4039
+ result[key] = await promiseMap(value, (item) => parseInputFileEntry(item));
4040
+ break;
4041
+ case "json":
4042
+ result[key] = stringifyJson(value);
4043
+ break;
4044
+ default:
4045
+ result[key] = value;
4046
+ }
4047
+ }
4048
+ return result;
2651
4049
  };
2652
4050
  const initObject = (db, schemaTables, table, object, selectedColumns) => {
2653
- const result = {};
4051
+ const data = {};
2654
4052
  const { xata, ...rest } = object ?? {};
2655
- Object.assign(result, rest);
4053
+ Object.assign(data, rest);
2656
4054
  const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
2657
4055
  if (!columns)
2658
4056
  console.error(`Table ${table} not found in schema`);
2659
4057
  for (const column of columns ?? []) {
2660
4058
  if (!isValidColumn(selectedColumns, column))
2661
4059
  continue;
2662
- const value = result[column.name];
4060
+ const value = data[column.name];
2663
4061
  switch (column.type) {
2664
4062
  case "datetime": {
2665
- const date = value !== void 0 ? new Date(value) : void 0;
2666
- if (date && isNaN(date.getTime())) {
4063
+ const date = value !== void 0 ? new Date(value) : null;
4064
+ if (date !== null && isNaN(date.getTime())) {
2667
4065
  console.error(`Failed to parse date ${value} for field ${column.name}`);
2668
- } else if (date) {
2669
- result[column.name] = date;
4066
+ } else {
4067
+ data[column.name] = date;
2670
4068
  }
2671
4069
  break;
2672
4070
  }
@@ -2679,54 +4077,77 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
2679
4077
  if (item === column.name) {
2680
4078
  return [...acc, "*"];
2681
4079
  }
2682
- if (item.startsWith(`${column.name}.`)) {
4080
+ if (isString(item) && item.startsWith(`${column.name}.`)) {
2683
4081
  const [, ...path] = item.split(".");
2684
4082
  return [...acc, path.join(".")];
2685
4083
  }
2686
4084
  return acc;
2687
4085
  }, []);
2688
- result[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
4086
+ data[column.name] = initObject(
4087
+ db,
4088
+ schemaTables,
4089
+ linkTable,
4090
+ value,
4091
+ selectedLinkColumns
4092
+ );
2689
4093
  } else {
2690
- result[column.name] = null;
4094
+ data[column.name] = null;
2691
4095
  }
2692
4096
  break;
2693
4097
  }
4098
+ case "file":
4099
+ data[column.name] = isDefined(value) ? new XataFile(value) : null;
4100
+ break;
4101
+ case "file[]":
4102
+ data[column.name] = value?.map((item) => new XataFile(item)) ?? null;
4103
+ break;
4104
+ case "json":
4105
+ data[column.name] = parseJson(value);
4106
+ break;
2694
4107
  default:
2695
- result[column.name] = value ?? null;
4108
+ data[column.name] = value ?? null;
2696
4109
  if (column.notNull === true && value === null) {
2697
4110
  console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
2698
4111
  }
2699
4112
  break;
2700
4113
  }
2701
4114
  }
2702
- result.read = function(columns2) {
2703
- return db[table].read(result["id"], columns2);
4115
+ const record = { ...data };
4116
+ const metadata = xata !== void 0 ? { ...xata, createdAt: new Date(xata.createdAt), updatedAt: new Date(xata.updatedAt) } : void 0;
4117
+ record.read = function(columns2) {
4118
+ return db[table].read(record["id"], columns2);
2704
4119
  };
2705
- result.update = function(data, b, c) {
2706
- const columns2 = isStringArray(b) ? b : ["*"];
4120
+ record.update = function(data2, b, c) {
4121
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
2707
4122
  const ifVersion = parseIfVersion(b, c);
2708
- return db[table].update(result["id"], data, columns2, { ifVersion });
4123
+ return db[table].update(record["id"], data2, columns2, { ifVersion });
2709
4124
  };
2710
- result.replace = function(data, b, c) {
2711
- const columns2 = isStringArray(b) ? b : ["*"];
4125
+ record.replace = function(data2, b, c) {
4126
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
2712
4127
  const ifVersion = parseIfVersion(b, c);
2713
- return db[table].createOrReplace(result["id"], data, columns2, { ifVersion });
4128
+ return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
4129
+ };
4130
+ record.delete = function() {
4131
+ return db[table].delete(record["id"]);
2714
4132
  };
2715
- result.delete = function() {
2716
- return db[table].delete(result["id"]);
4133
+ if (metadata !== void 0) {
4134
+ record.xata = Object.freeze(metadata);
4135
+ }
4136
+ record.getMetadata = function() {
4137
+ return record.xata;
4138
+ };
4139
+ record.toSerializable = function() {
4140
+ return JSON.parse(JSON.stringify(record));
2717
4141
  };
2718
- result.getMetadata = function() {
2719
- return xata;
4142
+ record.toString = function() {
4143
+ return JSON.stringify(record);
2720
4144
  };
2721
- for (const prop of ["read", "update", "replace", "delete", "getMetadata"]) {
2722
- Object.defineProperty(result, prop, { enumerable: false });
4145
+ for (const prop of ["read", "update", "replace", "delete", "getMetadata", "toSerializable", "toString"]) {
4146
+ Object.defineProperty(record, prop, { enumerable: false });
2723
4147
  }
2724
- Object.freeze(result);
2725
- return result;
4148
+ Object.freeze(record);
4149
+ return record;
2726
4150
  };
2727
- function isResponseWithRecords(value) {
2728
- return isObject(value) && Array.isArray(value.records);
2729
- }
2730
4151
  function extractId(value) {
2731
4152
  if (isString(value))
2732
4153
  return value;
@@ -2737,11 +4158,7 @@ function extractId(value) {
2737
4158
  function isValidColumn(columns, column) {
2738
4159
  if (columns.includes("*"))
2739
4160
  return true;
2740
- if (column.type === "link") {
2741
- const linkColumns = columns.filter((item) => item.startsWith(column.name));
2742
- return linkColumns.length > 0;
2743
- }
2744
- return columns.includes(column.name);
4161
+ return columns.filter((item) => isString(item) && item.startsWith(column.name)).length > 0;
2745
4162
  }
2746
4163
  function parseIfVersion(...args) {
2747
4164
  for (const arg of args) {
@@ -2818,10 +4235,12 @@ const notExists = (column) => ({ $notExists: column });
2818
4235
  const startsWith = (value) => ({ $startsWith: value });
2819
4236
  const endsWith = (value) => ({ $endsWith: value });
2820
4237
  const pattern = (value) => ({ $pattern: value });
4238
+ const iPattern = (value) => ({ $iPattern: value });
2821
4239
  const is = (value) => ({ $is: value });
2822
4240
  const equals = is;
2823
4241
  const isNot = (value) => ({ $isNot: value });
2824
4242
  const contains = (value) => ({ $contains: value });
4243
+ const iContains = (value) => ({ $iContains: value });
2825
4244
  const includes = (value) => ({ $includes: value });
2826
4245
  const includesAll = (value) => ({ $includesAll: value });
2827
4246
  const includesNone = (value) => ({ $includesNone: value });
@@ -2847,13 +4266,13 @@ var __privateSet$2 = (obj, member, value, setter) => {
2847
4266
  };
2848
4267
  var _tables, _schemaTables$1;
2849
4268
  class SchemaPlugin extends XataPlugin {
2850
- constructor(schemaTables) {
4269
+ constructor() {
2851
4270
  super();
2852
4271
  __privateAdd$2(this, _tables, {});
2853
4272
  __privateAdd$2(this, _schemaTables$1, void 0);
2854
- __privateSet$2(this, _schemaTables$1, schemaTables);
2855
4273
  }
2856
4274
  build(pluginOptions) {
4275
+ __privateSet$2(this, _schemaTables$1, pluginOptions.tables);
2857
4276
  const db = new Proxy(
2858
4277
  {},
2859
4278
  {
@@ -2877,6 +4296,80 @@ class SchemaPlugin extends XataPlugin {
2877
4296
  _tables = new WeakMap();
2878
4297
  _schemaTables$1 = new WeakMap();
2879
4298
 
4299
+ class FilesPlugin extends XataPlugin {
4300
+ build(pluginOptions) {
4301
+ return {
4302
+ download: async (location) => {
4303
+ const { table, record, column, fileId = "" } = location ?? {};
4304
+ return await getFileItem({
4305
+ pathParams: {
4306
+ workspace: "{workspaceId}",
4307
+ dbBranchName: "{dbBranch}",
4308
+ region: "{region}",
4309
+ tableName: table ?? "",
4310
+ recordId: record ?? "",
4311
+ columnName: column ?? "",
4312
+ fileId
4313
+ },
4314
+ ...pluginOptions,
4315
+ rawResponse: true
4316
+ });
4317
+ },
4318
+ upload: async (location, file, options) => {
4319
+ const { table, record, column, fileId = "" } = location ?? {};
4320
+ const resolvedFile = await file;
4321
+ const contentType = options?.mediaType || getContentType(resolvedFile);
4322
+ const body = resolvedFile instanceof XataFile ? resolvedFile.toBlob() : resolvedFile;
4323
+ return await putFileItem({
4324
+ ...pluginOptions,
4325
+ pathParams: {
4326
+ workspace: "{workspaceId}",
4327
+ dbBranchName: "{dbBranch}",
4328
+ region: "{region}",
4329
+ tableName: table ?? "",
4330
+ recordId: record ?? "",
4331
+ columnName: column ?? "",
4332
+ fileId
4333
+ },
4334
+ body,
4335
+ headers: { "Content-Type": contentType }
4336
+ });
4337
+ },
4338
+ delete: async (location) => {
4339
+ const { table, record, column, fileId = "" } = location ?? {};
4340
+ return await deleteFileItem({
4341
+ pathParams: {
4342
+ workspace: "{workspaceId}",
4343
+ dbBranchName: "{dbBranch}",
4344
+ region: "{region}",
4345
+ tableName: table ?? "",
4346
+ recordId: record ?? "",
4347
+ columnName: column ?? "",
4348
+ fileId
4349
+ },
4350
+ ...pluginOptions
4351
+ });
4352
+ }
4353
+ };
4354
+ }
4355
+ }
4356
+ function getContentType(file) {
4357
+ if (typeof file === "string") {
4358
+ return "text/plain";
4359
+ }
4360
+ if ("mediaType" in file) {
4361
+ return file.mediaType;
4362
+ }
4363
+ if (isBlob(file)) {
4364
+ return file.type;
4365
+ }
4366
+ try {
4367
+ return file.type;
4368
+ } catch (e) {
4369
+ }
4370
+ return "application/octet-stream";
4371
+ }
4372
+
2880
4373
  var __accessCheck$1 = (obj, member, msg) => {
2881
4374
  if (!member.has(obj))
2882
4375
  throw TypeError("Cannot " + msg);
@@ -2901,27 +4394,27 @@ var __privateMethod$1 = (obj, member, method) => {
2901
4394
  };
2902
4395
  var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
2903
4396
  class SearchPlugin extends XataPlugin {
2904
- constructor(db, schemaTables) {
4397
+ constructor(db) {
2905
4398
  super();
2906
4399
  this.db = db;
2907
4400
  __privateAdd$1(this, _search);
2908
4401
  __privateAdd$1(this, _getSchemaTables);
2909
4402
  __privateAdd$1(this, _schemaTables, void 0);
2910
- __privateSet$1(this, _schemaTables, schemaTables);
2911
4403
  }
2912
- build({ getFetchProps }) {
4404
+ build(pluginOptions) {
4405
+ __privateSet$1(this, _schemaTables, pluginOptions.tables);
2913
4406
  return {
2914
4407
  all: async (query, options = {}) => {
2915
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
2916
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
4408
+ const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
4409
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
2917
4410
  return records.map((record) => {
2918
4411
  const { table = "orphan" } = record.xata;
2919
4412
  return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
2920
4413
  });
2921
4414
  },
2922
4415
  byTable: async (query, options = {}) => {
2923
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
2924
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
4416
+ const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
4417
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
2925
4418
  return records.reduce((acc, record) => {
2926
4419
  const { table = "orphan" } = record.xata;
2927
4420
  const items = acc[table] ?? [];
@@ -2934,113 +4427,112 @@ class SearchPlugin extends XataPlugin {
2934
4427
  }
2935
4428
  _schemaTables = new WeakMap();
2936
4429
  _search = new WeakSet();
2937
- search_fn = async function(query, options, getFetchProps) {
2938
- const fetchProps = await getFetchProps();
2939
- const { tables, fuzziness, highlight, prefix } = options ?? {};
4430
+ search_fn = async function(query, options, pluginOptions) {
4431
+ const { tables, fuzziness, highlight, prefix, page } = options ?? {};
2940
4432
  const { records } = await searchBranch({
2941
4433
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
2942
- body: { tables, query, fuzziness, prefix, highlight },
2943
- ...fetchProps
4434
+ // @ts-ignore https://github.com/xataio/client-ts/issues/313
4435
+ body: { tables, query, fuzziness, prefix, highlight, page },
4436
+ ...pluginOptions
2944
4437
  });
2945
4438
  return records;
2946
4439
  };
2947
4440
  _getSchemaTables = new WeakSet();
2948
- getSchemaTables_fn = async function(getFetchProps) {
4441
+ getSchemaTables_fn = async function(pluginOptions) {
2949
4442
  if (__privateGet$1(this, _schemaTables))
2950
4443
  return __privateGet$1(this, _schemaTables);
2951
- const fetchProps = await getFetchProps();
2952
4444
  const { schema } = await getBranchDetails({
2953
4445
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
2954
- ...fetchProps
4446
+ ...pluginOptions
2955
4447
  });
2956
4448
  __privateSet$1(this, _schemaTables, schema.tables);
2957
4449
  return schema.tables;
2958
4450
  };
2959
4451
 
2960
- const isBranchStrategyBuilder = (strategy) => {
2961
- return typeof strategy === "function";
2962
- };
2963
-
2964
- async function getCurrentBranchName(options) {
2965
- const { branch, envBranch } = getEnvironment();
2966
- if (branch) {
2967
- const details = await getDatabaseBranch(branch, options);
2968
- if (details)
2969
- return branch;
2970
- console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
2971
- }
2972
- const gitBranch = envBranch || await getGitBranch();
2973
- return resolveXataBranch(gitBranch, options);
2974
- }
2975
- async function getCurrentBranchDetails(options) {
2976
- const branch = await getCurrentBranchName(options);
2977
- return getDatabaseBranch(branch, options);
2978
- }
2979
- async function resolveXataBranch(gitBranch, options) {
2980
- const databaseURL = options?.databaseURL || getDatabaseURL();
2981
- const apiKey = options?.apiKey || getAPIKey();
2982
- if (!databaseURL)
2983
- throw new Error(
2984
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2985
- );
2986
- if (!apiKey)
2987
- throw new Error(
2988
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2989
- );
2990
- const [protocol, , host, , dbName] = databaseURL.split("/");
2991
- const urlParts = parseWorkspacesUrlParts(host);
2992
- if (!urlParts)
2993
- throw new Error(`Unable to parse workspace and region: ${databaseURL}`);
2994
- const { workspace, region } = urlParts;
2995
- const { fallbackBranch } = getEnvironment();
2996
- const { branch } = await resolveBranch({
2997
- apiKey,
2998
- apiUrl: databaseURL,
2999
- fetchImpl: getFetchImplementation(options?.fetchImpl),
3000
- workspacesApiUrl: `${protocol}//${host}`,
3001
- pathParams: { dbName, workspace, region },
3002
- queryParams: { gitBranch, fallbackBranch },
3003
- trace: defaultTrace
3004
- });
3005
- return branch;
3006
- }
3007
- async function getDatabaseBranch(branch, options) {
3008
- const databaseURL = options?.databaseURL || getDatabaseURL();
3009
- const apiKey = options?.apiKey || getAPIKey();
3010
- if (!databaseURL)
3011
- throw new Error(
3012
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
3013
- );
3014
- if (!apiKey)
3015
- throw new Error(
3016
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
3017
- );
3018
- const [protocol, , host, , database] = databaseURL.split("/");
3019
- const urlParts = parseWorkspacesUrlParts(host);
3020
- if (!urlParts)
3021
- throw new Error(`Unable to parse workspace and region: ${databaseURL}`);
3022
- const { workspace, region } = urlParts;
3023
- try {
3024
- return await getBranchDetails({
3025
- apiKey,
3026
- apiUrl: databaseURL,
3027
- fetchImpl: getFetchImplementation(options?.fetchImpl),
3028
- workspacesApiUrl: `${protocol}//${host}`,
3029
- pathParams: { dbBranchName: `${database}:${branch}`, workspace, region },
3030
- trace: defaultTrace
3031
- });
3032
- } catch (err) {
3033
- if (isObject(err) && err.status === 404)
3034
- return null;
3035
- throw err;
4452
+ function escapeElement(elementRepresentation) {
4453
+ const escaped = elementRepresentation.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
4454
+ return '"' + escaped + '"';
4455
+ }
4456
+ function arrayString(val) {
4457
+ let result = "{";
4458
+ for (let i = 0; i < val.length; i++) {
4459
+ if (i > 0) {
4460
+ result = result + ",";
4461
+ }
4462
+ if (val[i] === null || typeof val[i] === "undefined") {
4463
+ result = result + "NULL";
4464
+ } else if (Array.isArray(val[i])) {
4465
+ result = result + arrayString(val[i]);
4466
+ } else if (val[i] instanceof Buffer) {
4467
+ result += "\\\\x" + val[i].toString("hex");
4468
+ } else {
4469
+ result += escapeElement(prepareValue(val[i]));
4470
+ }
3036
4471
  }
4472
+ result = result + "}";
4473
+ return result;
3037
4474
  }
3038
- function getDatabaseURL() {
4475
+ function prepareValue(value) {
4476
+ if (!isDefined(value))
4477
+ return null;
4478
+ if (value instanceof Date) {
4479
+ return value.toISOString();
4480
+ }
4481
+ if (Array.isArray(value)) {
4482
+ return arrayString(value);
4483
+ }
4484
+ if (isObject(value)) {
4485
+ return JSON.stringify(value);
4486
+ }
3039
4487
  try {
3040
- const { databaseURL } = getEnvironment();
3041
- return databaseURL;
3042
- } catch (err) {
3043
- return void 0;
4488
+ return value.toString();
4489
+ } catch (e) {
4490
+ return value;
4491
+ }
4492
+ }
4493
+ function prepareParams(param1, param2) {
4494
+ if (isString(param1)) {
4495
+ return { statement: param1, params: param2?.map((value) => prepareValue(value)) };
4496
+ }
4497
+ if (isStringArray(param1)) {
4498
+ const statement = param1.reduce((acc, curr, index) => {
4499
+ return acc + curr + (index < (param2?.length ?? 0) ? "$" + (index + 1) : "");
4500
+ }, "");
4501
+ return { statement, params: param2?.map((value) => prepareValue(value)) };
4502
+ }
4503
+ if (isObject(param1)) {
4504
+ const { statement, params, consistency } = param1;
4505
+ return { statement, params: params?.map((value) => prepareValue(value)), consistency };
4506
+ }
4507
+ throw new Error("Invalid query");
4508
+ }
4509
+
4510
+ class SQLPlugin extends XataPlugin {
4511
+ build(pluginOptions) {
4512
+ return async (param1, ...param2) => {
4513
+ const { statement, params, consistency } = prepareParams(param1, param2);
4514
+ const { records, warning } = await sqlQuery({
4515
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4516
+ body: { statement, params, consistency },
4517
+ ...pluginOptions
4518
+ });
4519
+ return { records, warning };
4520
+ };
4521
+ }
4522
+ }
4523
+
4524
+ class TransactionPlugin extends XataPlugin {
4525
+ build(pluginOptions) {
4526
+ return {
4527
+ run: async (operations) => {
4528
+ const response = await branchTransaction({
4529
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4530
+ body: { operations },
4531
+ ...pluginOptions
4532
+ });
4533
+ return response;
4534
+ }
4535
+ };
3044
4536
  }
3045
4537
  }
3046
4538
 
@@ -3067,46 +4559,45 @@ var __privateMethod = (obj, member, method) => {
3067
4559
  return method;
3068
4560
  };
3069
4561
  const buildClient = (plugins) => {
3070
- var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
4562
+ var _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _a;
3071
4563
  return _a = class {
3072
- constructor(options = {}, schemaTables) {
4564
+ constructor(options = {}, tables) {
3073
4565
  __privateAdd(this, _parseOptions);
3074
4566
  __privateAdd(this, _getFetchProps);
3075
- __privateAdd(this, _evaluateBranch);
3076
- __privateAdd(this, _branch, void 0);
3077
4567
  __privateAdd(this, _options, void 0);
3078
4568
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
3079
4569
  __privateSet(this, _options, safeOptions);
3080
4570
  const pluginOptions = {
3081
- getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
4571
+ ...__privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
3082
4572
  cache: safeOptions.cache,
3083
- trace: safeOptions.trace
4573
+ host: safeOptions.host,
4574
+ tables
3084
4575
  };
3085
- const db = new SchemaPlugin(schemaTables).build(pluginOptions);
3086
- const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
4576
+ const db = new SchemaPlugin().build(pluginOptions);
4577
+ const search = new SearchPlugin(db).build(pluginOptions);
4578
+ const transactions = new TransactionPlugin().build(pluginOptions);
4579
+ const sql = new SQLPlugin().build(pluginOptions);
4580
+ const files = new FilesPlugin().build(pluginOptions);
4581
+ this.schema = { tables };
3087
4582
  this.db = db;
3088
4583
  this.search = search;
4584
+ this.transactions = transactions;
4585
+ this.sql = sql;
4586
+ this.files = files;
3089
4587
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
3090
4588
  if (namespace === void 0)
3091
4589
  continue;
3092
- const result = namespace.build(pluginOptions);
3093
- if (result instanceof Promise) {
3094
- void result.then((namespace2) => {
3095
- this[key] = namespace2;
3096
- });
3097
- } else {
3098
- this[key] = result;
3099
- }
4590
+ this[key] = namespace.build(pluginOptions);
3100
4591
  }
3101
4592
  }
3102
4593
  async getConfig() {
3103
4594
  const databaseURL = __privateGet(this, _options).databaseURL;
3104
- const branch = await __privateGet(this, _options).branch();
4595
+ const branch = __privateGet(this, _options).branch;
3105
4596
  return { databaseURL, branch };
3106
4597
  }
3107
- }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
4598
+ }, _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3108
4599
  const enableBrowser = options?.enableBrowser ?? getEnableBrowserVariable() ?? false;
3109
- const isBrowser = typeof window !== "undefined";
4600
+ const isBrowser = typeof window !== "undefined" && typeof Deno === "undefined";
3110
4601
  if (isBrowser && !enableBrowser) {
3111
4602
  throw new Error(
3112
4603
  "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."
@@ -3117,46 +4608,73 @@ const buildClient = (plugins) => {
3117
4608
  const apiKey = options?.apiKey || getAPIKey();
3118
4609
  const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
3119
4610
  const trace = options?.trace ?? defaultTrace;
3120
- const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
4611
+ const clientName = options?.clientName;
4612
+ const host = options?.host ?? "production";
4613
+ const xataAgentExtra = options?.xataAgentExtra;
3121
4614
  if (!apiKey) {
3122
4615
  throw new Error("Option apiKey is required");
3123
4616
  }
3124
4617
  if (!databaseURL) {
3125
4618
  throw new Error("Option databaseURL is required");
3126
4619
  }
3127
- return { fetch, databaseURL, apiKey, branch, cache, trace, clientID: generateUUID(), enableBrowser };
3128
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace, clientID }) {
3129
- const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
3130
- if (!branchValue)
3131
- throw new Error("Unable to resolve branch value");
4620
+ const envBranch = getBranch();
4621
+ const previewBranch = getPreviewBranch();
4622
+ const branch = options?.branch || previewBranch || envBranch || "main";
4623
+ if (!!previewBranch && branch !== previewBranch) {
4624
+ console.warn(
4625
+ `Ignoring preview branch ${previewBranch} because branch option was passed to the client constructor with value ${branch}`
4626
+ );
4627
+ } else if (!!envBranch && branch !== envBranch) {
4628
+ console.warn(
4629
+ `Ignoring branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
4630
+ );
4631
+ } else if (!!previewBranch && !!envBranch && previewBranch !== envBranch) {
4632
+ console.warn(
4633
+ `Ignoring preview branch ${previewBranch} and branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
4634
+ );
4635
+ } else if (!previewBranch && !envBranch && options?.branch === void 0) {
4636
+ console.warn(
4637
+ `No branch was passed to the client constructor. Using default branch ${branch}. You can set the branch with the environment variable XATA_BRANCH or by passing the branch option to the client constructor.`
4638
+ );
4639
+ }
4640
+ return {
4641
+ fetch,
4642
+ databaseURL,
4643
+ apiKey,
4644
+ branch,
4645
+ cache,
4646
+ trace,
4647
+ host,
4648
+ clientID: generateUUID(),
4649
+ enableBrowser,
4650
+ clientName,
4651
+ xataAgentExtra
4652
+ };
4653
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = function({
4654
+ fetch,
4655
+ apiKey,
4656
+ databaseURL,
4657
+ branch,
4658
+ trace,
4659
+ clientID,
4660
+ clientName,
4661
+ xataAgentExtra
4662
+ }) {
3132
4663
  return {
3133
- fetchImpl: fetch,
4664
+ fetch,
3134
4665
  apiKey,
3135
4666
  apiUrl: "",
4667
+ // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
3136
4668
  workspacesApiUrl: (path, params) => {
3137
4669
  const hasBranch = params.dbBranchName ?? params.branch;
3138
- const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branchValue}` : "");
4670
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branch}` : "");
3139
4671
  return databaseURL + newPath;
3140
4672
  },
3141
4673
  trace,
3142
- clientID
4674
+ clientID,
4675
+ clientName,
4676
+ xataAgentExtra
3143
4677
  };
3144
- }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
3145
- if (__privateGet(this, _branch))
3146
- return __privateGet(this, _branch);
3147
- if (param === void 0)
3148
- return void 0;
3149
- const strategies = Array.isArray(param) ? [...param] : [param];
3150
- const evaluateBranch = async (strategy) => {
3151
- return isBranchStrategyBuilder(strategy) ? await strategy() : strategy;
3152
- };
3153
- for await (const strategy of strategies) {
3154
- const branch = await evaluateBranch(strategy);
3155
- if (branch) {
3156
- __privateSet(this, _branch, branch);
3157
- return branch;
3158
- }
3159
- }
3160
4678
  }, _a;
3161
4679
  };
3162
4680
  class BaseClient extends buildClient() {
@@ -3230,7 +4748,7 @@ const deserialize = (json) => {
3230
4748
  };
3231
4749
 
3232
4750
  function buildWorkerRunner(config) {
3233
- return function xataWorker(name, _worker) {
4751
+ return function xataWorker(name, worker) {
3234
4752
  return async (...args) => {
3235
4753
  const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
3236
4754
  const result = await fetch(url, {
@@ -3252,6 +4770,8 @@ class XataError extends Error {
3252
4770
  }
3253
4771
 
3254
4772
  exports.BaseClient = BaseClient;
4773
+ exports.FetcherError = FetcherError;
4774
+ exports.FilesPlugin = FilesPlugin;
3255
4775
  exports.Operations = operationsByTag;
3256
4776
  exports.PAGINATION_DEFAULT_OFFSET = PAGINATION_DEFAULT_OFFSET;
3257
4777
  exports.PAGINATION_DEFAULT_SIZE = PAGINATION_DEFAULT_SIZE;
@@ -3260,23 +4780,31 @@ exports.PAGINATION_MAX_SIZE = PAGINATION_MAX_SIZE;
3260
4780
  exports.Page = Page;
3261
4781
  exports.Query = Query;
3262
4782
  exports.RecordArray = RecordArray;
4783
+ exports.RecordColumnTypes = RecordColumnTypes;
3263
4784
  exports.Repository = Repository;
3264
4785
  exports.RestRepository = RestRepository;
4786
+ exports.SQLPlugin = SQLPlugin;
3265
4787
  exports.SchemaPlugin = SchemaPlugin;
3266
4788
  exports.SearchPlugin = SearchPlugin;
3267
4789
  exports.Serializer = Serializer;
3268
4790
  exports.SimpleCache = SimpleCache;
4791
+ exports.TransactionPlugin = TransactionPlugin;
3269
4792
  exports.XataApiClient = XataApiClient;
3270
4793
  exports.XataApiPlugin = XataApiPlugin;
3271
4794
  exports.XataError = XataError;
4795
+ exports.XataFile = XataFile;
3272
4796
  exports.XataPlugin = XataPlugin;
3273
4797
  exports.acceptWorkspaceMemberInvite = acceptWorkspaceMemberInvite;
3274
4798
  exports.addGitBranchesEntry = addGitBranchesEntry;
3275
4799
  exports.addTableColumn = addTableColumn;
3276
4800
  exports.aggregateTable = aggregateTable;
3277
4801
  exports.applyBranchSchemaEdit = applyBranchSchemaEdit;
4802
+ exports.askTable = askTable;
4803
+ exports.askTableSession = askTableSession;
3278
4804
  exports.branchTransaction = branchTransaction;
3279
4805
  exports.buildClient = buildClient;
4806
+ exports.buildPreviewBranchName = buildPreviewBranchName;
4807
+ exports.buildProviderString = buildProviderString;
3280
4808
  exports.buildWorkerRunner = buildWorkerRunner;
3281
4809
  exports.bulkInsertTableRecords = bulkInsertTableRecords;
3282
4810
  exports.cancelWorkspaceMemberInvite = cancelWorkspaceMemberInvite;
@@ -3284,32 +4812,37 @@ exports.compareBranchSchemas = compareBranchSchemas;
3284
4812
  exports.compareBranchWithUserSchema = compareBranchWithUserSchema;
3285
4813
  exports.compareMigrationRequest = compareMigrationRequest;
3286
4814
  exports.contains = contains;
4815
+ exports.copyBranch = copyBranch;
3287
4816
  exports.createBranch = createBranch;
4817
+ exports.createCluster = createCluster;
3288
4818
  exports.createDatabase = createDatabase;
3289
4819
  exports.createMigrationRequest = createMigrationRequest;
3290
4820
  exports.createTable = createTable;
3291
4821
  exports.createUserAPIKey = createUserAPIKey;
3292
4822
  exports.createWorkspace = createWorkspace;
3293
- exports.dEPRECATEDcreateDatabase = dEPRECATEDcreateDatabase;
3294
- exports.dEPRECATEDdeleteDatabase = dEPRECATEDdeleteDatabase;
3295
- exports.dEPRECATEDgetDatabaseList = dEPRECATEDgetDatabaseList;
3296
- exports.dEPRECATEDgetDatabaseMetadata = dEPRECATEDgetDatabaseMetadata;
3297
- exports.dEPRECATEDupdateDatabaseMetadata = dEPRECATEDupdateDatabaseMetadata;
3298
4823
  exports.deleteBranch = deleteBranch;
3299
4824
  exports.deleteColumn = deleteColumn;
3300
4825
  exports.deleteDatabase = deleteDatabase;
4826
+ exports.deleteDatabaseGithubSettings = deleteDatabaseGithubSettings;
4827
+ exports.deleteFile = deleteFile;
4828
+ exports.deleteFileItem = deleteFileItem;
4829
+ exports.deleteOAuthAccessToken = deleteOAuthAccessToken;
3301
4830
  exports.deleteRecord = deleteRecord;
3302
4831
  exports.deleteTable = deleteTable;
3303
4832
  exports.deleteUser = deleteUser;
3304
4833
  exports.deleteUserAPIKey = deleteUserAPIKey;
4834
+ exports.deleteUserOAuthClient = deleteUserOAuthClient;
3305
4835
  exports.deleteWorkspace = deleteWorkspace;
3306
4836
  exports.deserialize = deserialize;
3307
4837
  exports.endsWith = endsWith;
3308
4838
  exports.equals = equals;
3309
4839
  exports.executeBranchMigrationPlan = executeBranchMigrationPlan;
3310
4840
  exports.exists = exists;
4841
+ exports.fileAccess = fileAccess;
3311
4842
  exports.ge = ge;
3312
4843
  exports.getAPIKey = getAPIKey;
4844
+ exports.getAuthorizationCode = getAuthorizationCode;
4845
+ exports.getBranch = getBranch;
3313
4846
  exports.getBranchDetails = getBranchDetails;
3314
4847
  exports.getBranchList = getBranchList;
3315
4848
  exports.getBranchMetadata = getBranchMetadata;
@@ -3317,29 +4850,38 @@ exports.getBranchMigrationHistory = getBranchMigrationHistory;
3317
4850
  exports.getBranchMigrationPlan = getBranchMigrationPlan;
3318
4851
  exports.getBranchSchemaHistory = getBranchSchemaHistory;
3319
4852
  exports.getBranchStats = getBranchStats;
4853
+ exports.getCluster = getCluster;
3320
4854
  exports.getColumn = getColumn;
3321
- exports.getCurrentBranchDetails = getCurrentBranchDetails;
3322
- exports.getCurrentBranchName = getCurrentBranchName;
4855
+ exports.getDatabaseGithubSettings = getDatabaseGithubSettings;
3323
4856
  exports.getDatabaseList = getDatabaseList;
3324
4857
  exports.getDatabaseMetadata = getDatabaseMetadata;
3325
4858
  exports.getDatabaseURL = getDatabaseURL;
4859
+ exports.getFile = getFile;
4860
+ exports.getFileItem = getFileItem;
3326
4861
  exports.getGitBranchesMapping = getGitBranchesMapping;
3327
4862
  exports.getHostUrl = getHostUrl;
3328
4863
  exports.getMigrationRequest = getMigrationRequest;
3329
4864
  exports.getMigrationRequestIsMerged = getMigrationRequestIsMerged;
4865
+ exports.getPreviewBranch = getPreviewBranch;
3330
4866
  exports.getRecord = getRecord;
4867
+ exports.getSchema = getSchema;
3331
4868
  exports.getTableColumns = getTableColumns;
3332
4869
  exports.getTableSchema = getTableSchema;
3333
4870
  exports.getUser = getUser;
3334
4871
  exports.getUserAPIKeys = getUserAPIKeys;
4872
+ exports.getUserOAuthAccessTokens = getUserOAuthAccessTokens;
4873
+ exports.getUserOAuthClients = getUserOAuthClients;
3335
4874
  exports.getWorkspace = getWorkspace;
3336
4875
  exports.getWorkspaceMembersList = getWorkspaceMembersList;
3337
4876
  exports.getWorkspacesList = getWorkspacesList;
4877
+ exports.grantAuthorizationCode = grantAuthorizationCode;
3338
4878
  exports.greaterEquals = greaterEquals;
3339
4879
  exports.greaterThan = greaterThan;
3340
4880
  exports.greaterThanEquals = greaterThanEquals;
3341
4881
  exports.gt = gt;
3342
4882
  exports.gte = gte;
4883
+ exports.iContains = iContains;
4884
+ exports.iPattern = iPattern;
3343
4885
  exports.includes = includes;
3344
4886
  exports.includesAll = includesAll;
3345
4887
  exports.includesAny = includesAny;
@@ -3353,11 +4895,14 @@ exports.isHostProviderAlias = isHostProviderAlias;
3353
4895
  exports.isHostProviderBuilder = isHostProviderBuilder;
3354
4896
  exports.isIdentifiable = isIdentifiable;
3355
4897
  exports.isNot = isNot;
4898
+ exports.isValidExpandedColumn = isValidExpandedColumn;
4899
+ exports.isValidSelectableColumns = isValidSelectableColumns;
3356
4900
  exports.isXataRecord = isXataRecord;
3357
4901
  exports.le = le;
3358
4902
  exports.lessEquals = lessEquals;
3359
4903
  exports.lessThan = lessThan;
3360
4904
  exports.lessThanEquals = lessThanEquals;
4905
+ exports.listClusters = listClusters;
3361
4906
  exports.listMigrationRequestsCommits = listMigrationRequestsCommits;
3362
4907
  exports.listRegions = listRegions;
3363
4908
  exports.lt = lt;
@@ -3369,23 +4914,32 @@ exports.parseProviderString = parseProviderString;
3369
4914
  exports.parseWorkspacesUrlParts = parseWorkspacesUrlParts;
3370
4915
  exports.pattern = pattern;
3371
4916
  exports.previewBranchSchemaEdit = previewBranchSchemaEdit;
4917
+ exports.pushBranchMigrations = pushBranchMigrations;
4918
+ exports.putFile = putFile;
4919
+ exports.putFileItem = putFileItem;
3372
4920
  exports.queryMigrationRequests = queryMigrationRequests;
3373
4921
  exports.queryTable = queryTable;
3374
4922
  exports.removeGitBranchesEntry = removeGitBranchesEntry;
3375
4923
  exports.removeWorkspaceMember = removeWorkspaceMember;
4924
+ exports.renameDatabase = renameDatabase;
3376
4925
  exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite;
3377
4926
  exports.resolveBranch = resolveBranch;
3378
4927
  exports.searchBranch = searchBranch;
3379
4928
  exports.searchTable = searchTable;
3380
4929
  exports.serialize = serialize;
3381
4930
  exports.setTableSchema = setTableSchema;
4931
+ exports.sqlQuery = sqlQuery;
3382
4932
  exports.startsWith = startsWith;
3383
4933
  exports.summarizeTable = summarizeTable;
4934
+ exports.transformImage = transformImage;
3384
4935
  exports.updateBranchMetadata = updateBranchMetadata;
3385
4936
  exports.updateBranchSchema = updateBranchSchema;
4937
+ exports.updateCluster = updateCluster;
3386
4938
  exports.updateColumn = updateColumn;
4939
+ exports.updateDatabaseGithubSettings = updateDatabaseGithubSettings;
3387
4940
  exports.updateDatabaseMetadata = updateDatabaseMetadata;
3388
4941
  exports.updateMigrationRequest = updateMigrationRequest;
4942
+ exports.updateOAuthAccessToken = updateOAuthAccessToken;
3389
4943
  exports.updateRecordWithID = updateRecordWithID;
3390
4944
  exports.updateTable = updateTable;
3391
4945
  exports.updateUser = updateUser;
@@ -3393,4 +4947,5 @@ exports.updateWorkspace = updateWorkspace;
3393
4947
  exports.updateWorkspaceMemberInvite = updateWorkspaceMemberInvite;
3394
4948
  exports.updateWorkspaceMemberRole = updateWorkspaceMemberRole;
3395
4949
  exports.upsertRecordWithID = upsertRecordWithID;
4950
+ exports.vectorSearchTable = vectorSearchTable;
3396
4951
  //# sourceMappingURL=index.cjs.map