@xata.io/client 0.0.0-alpha.vfbe46c7 → 0.0.0-alpha.vfc08a49f5b2f1e93114c76b97e7da90408e84709

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,27 +1,8 @@
1
1
  'use strict';
2
2
 
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- function _interopNamespace(e) {
6
- if (e && e.__esModule) return e;
7
- var n = Object.create(null);
8
- if (e) {
9
- Object.keys(e).forEach(function (k) {
10
- if (k !== 'default') {
11
- var d = Object.getOwnPropertyDescriptor(e, k);
12
- Object.defineProperty(n, k, d.get ? d : {
13
- enumerable: true,
14
- get: function () { return e[k]; }
15
- });
16
- }
17
- });
18
- }
19
- n["default"] = e;
20
- return Object.freeze(n);
21
- }
22
-
23
- const defaultTrace = async (_name, fn, _options) => {
3
+ const defaultTrace = async (name, fn, _options) => {
24
4
  return await fn({
5
+ name,
25
6
  setAttributes: () => {
26
7
  return;
27
8
  }
@@ -39,7 +20,8 @@ const TraceAttributes = {
39
20
  HTTP_METHOD: "http.method",
40
21
  HTTP_URL: "http.url",
41
22
  HTTP_ROUTE: "http.route",
42
- HTTP_TARGET: "http.target"
23
+ HTTP_TARGET: "http.target",
24
+ CLOUDFLARE_RAY_ID: "cf.ray"
43
25
  };
44
26
 
45
27
  function notEmpty(value) {
@@ -48,8 +30,18 @@ function notEmpty(value) {
48
30
  function compact(arr) {
49
31
  return arr.filter(notEmpty);
50
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
+ }
51
43
  function isObject(value) {
52
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
44
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date) && !isBlob(value);
53
45
  }
54
46
  function isDefined(value) {
55
47
  return value !== null && value !== void 0;
@@ -60,6 +52,21 @@ function isString(value) {
60
52
  function isStringArray(value) {
61
53
  return isDefined(value) && Array.isArray(value) && value.every(isString);
62
54
  }
55
+ function isNumber(value) {
56
+ return isDefined(value) && typeof value === "number";
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
+ }
63
70
  function toBase64(value) {
64
71
  try {
65
72
  return btoa(value);
@@ -68,16 +75,60 @@ function toBase64(value) {
68
75
  return buf.from(value).toString("base64");
69
76
  }
70
77
  }
78
+ function deepMerge(a, b) {
79
+ const result = { ...a };
80
+ for (const [key, value] of Object.entries(b)) {
81
+ if (isObject(value) && isObject(result[key])) {
82
+ result[key] = deepMerge(result[key], value);
83
+ } else {
84
+ result[key] = value;
85
+ }
86
+ }
87
+ return result;
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
+ }
71
120
 
72
121
  function getEnvironment() {
73
122
  try {
74
- if (isObject(process) && isObject(process.env)) {
123
+ if (isDefined(process) && isDefined(process.env)) {
75
124
  return {
76
125
  apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
77
126
  databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
78
127
  branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
79
- envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
80
- 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
81
132
  };
82
133
  }
83
134
  } catch (err) {
@@ -88,8 +139,10 @@ function getEnvironment() {
88
139
  apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
89
140
  databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
90
141
  branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
91
- envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
92
- 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")
93
146
  };
94
147
  }
95
148
  } catch (err) {
@@ -98,10 +151,31 @@ function getEnvironment() {
98
151
  apiKey: getGlobalApiKey(),
99
152
  databaseURL: getGlobalDatabaseURL(),
100
153
  branch: getGlobalBranch(),
101
- envBranch: void 0,
102
- fallbackBranch: getGlobalFallbackBranch()
154
+ deployPreview: void 0,
155
+ deployPreviewBranch: void 0,
156
+ vercelGitCommitRef: void 0,
157
+ vercelGitRepoOwner: void 0
103
158
  };
104
159
  }
160
+ function getEnableBrowserVariable() {
161
+ try {
162
+ if (isObject(process) && isObject(process.env) && process.env.XATA_ENABLE_BROWSER !== void 0) {
163
+ return process.env.XATA_ENABLE_BROWSER === "true";
164
+ }
165
+ } catch (err) {
166
+ }
167
+ try {
168
+ if (isObject(Deno) && isObject(Deno.env) && Deno.env.get("XATA_ENABLE_BROWSER") !== void 0) {
169
+ return Deno.env.get("XATA_ENABLE_BROWSER") === "true";
170
+ }
171
+ } catch (err) {
172
+ }
173
+ try {
174
+ return XATA_ENABLE_BROWSER === true || XATA_ENABLE_BROWSER === "true";
175
+ } catch (err) {
176
+ return void 0;
177
+ }
178
+ }
105
179
  function getGlobalApiKey() {
106
180
  try {
107
181
  return XATA_API_KEY;
@@ -123,56 +197,338 @@ function getGlobalBranch() {
123
197
  return void 0;
124
198
  }
125
199
  }
126
- function getGlobalFallbackBranch() {
200
+ function getDatabaseURL() {
127
201
  try {
128
- return XATA_FALLBACK_BRANCH;
202
+ const { databaseURL } = getEnvironment();
203
+ return databaseURL;
129
204
  } catch (err) {
130
205
  return void 0;
131
206
  }
132
207
  }
133
- async function getGitBranch() {
134
- const cmd = ["git", "branch", "--show-current"];
135
- const fullCmd = cmd.join(" ");
136
- const nodeModule = ["child", "process"].join("_");
137
- const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
208
+ function getAPIKey() {
138
209
  try {
139
- if (typeof require === "function") {
140
- return require(nodeModule).execSync(fullCmd, execOptions).trim();
141
- }
142
- const { execSync } = await (function (t) { return Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require(t)); }); })(nodeModule);
143
- return execSync(fullCmd, execOptions).toString().trim();
210
+ const { apiKey } = getEnvironment();
211
+ return apiKey;
144
212
  } catch (err) {
213
+ return void 0;
145
214
  }
215
+ }
216
+ function getBranch() {
146
217
  try {
147
- if (isObject(Deno)) {
148
- const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
149
- return new TextDecoder().decode(await process2.output()).trim();
150
- }
218
+ const { branch } = getEnvironment();
219
+ return branch;
151
220
  } catch (err) {
221
+ return void 0;
152
222
  }
153
223
  }
154
-
155
- function getAPIKey() {
224
+ function buildPreviewBranchName({ org, branch }) {
225
+ return `preview-${org}-${branch}`;
226
+ }
227
+ function getPreviewBranch() {
156
228
  try {
157
- const { apiKey } = getEnvironment();
158
- 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;
159
242
  } catch (err) {
160
243
  return void 0;
161
244
  }
162
245
  }
163
246
 
247
+ var __accessCheck$7 = (obj, member, msg) => {
248
+ if (!member.has(obj))
249
+ throw TypeError("Cannot " + msg);
250
+ };
251
+ var __privateGet$7 = (obj, member, getter) => {
252
+ __accessCheck$7(obj, member, "read from private field");
253
+ return getter ? getter.call(obj) : member.get(obj);
254
+ };
255
+ var __privateAdd$7 = (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$7 = (obj, member, value, setter) => {
261
+ __accessCheck$7(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$7(obj, member, "access private method");
267
+ return method;
268
+ };
269
+ var _fetch, _queue, _concurrency, _enqueue, enqueue_fn;
270
+ const REQUEST_TIMEOUT = 5 * 60 * 1e3;
164
271
  function getFetchImplementation(userFetch) {
165
272
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
166
- const fetchImpl = userFetch ?? globalFetch;
273
+ const globalThisFetch = typeof globalThis !== "undefined" ? globalThis.fetch : void 0;
274
+ const fetchImpl = userFetch ?? globalFetch ?? globalThisFetch;
167
275
  if (!fetchImpl) {
168
- throw new Error(
169
- `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
170
- );
276
+ throw new Error(`Couldn't find a global \`fetch\`. Pass a fetch implementation explicitly.`);
171
277
  }
172
278
  return fetchImpl;
173
279
  }
280
+ class ApiRequestPool {
281
+ constructor(concurrency = 10) {
282
+ __privateAdd$7(this, _enqueue);
283
+ __privateAdd$7(this, _fetch, void 0);
284
+ __privateAdd$7(this, _queue, void 0);
285
+ __privateAdd$7(this, _concurrency, void 0);
286
+ __privateSet$7(this, _queue, []);
287
+ __privateSet$7(this, _concurrency, concurrency);
288
+ this.running = 0;
289
+ this.started = 0;
290
+ }
291
+ setFetch(fetch2) {
292
+ __privateSet$7(this, _fetch, fetch2);
293
+ }
294
+ getFetch() {
295
+ if (!__privateGet$7(this, _fetch)) {
296
+ throw new Error("Fetch not set");
297
+ }
298
+ return __privateGet$7(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$7(this, _queue).push(resolve)).finally(() => {
331
+ this.started--;
332
+ this.running++;
333
+ }).then(() => task()).finally(() => {
334
+ this.running--;
335
+ const next = __privateGet$7(this, _queue).shift();
336
+ if (next !== void 0) {
337
+ this.started++;
338
+ next();
339
+ }
340
+ });
341
+ if (this.running + this.started < __privateGet$7(this, _concurrency)) {
342
+ const next = __privateGet$7(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
+ }
174
530
 
175
- const VERSION = "0.0.0-alpha.vfbe46c7";
531
+ const VERSION = "0.28.4";
176
532
 
177
533
  class ErrorWithCause extends Error {
178
534
  constructor(message, options) {
@@ -183,7 +539,7 @@ class FetcherError extends ErrorWithCause {
183
539
  constructor(status, data, requestId) {
184
540
  super(getMessage(data));
185
541
  this.status = status;
186
- this.errors = isBulkError(data) ? data.errors : void 0;
542
+ this.errors = isBulkError(data) ? data.errors : [{ message: getMessage(data), status }];
187
543
  this.requestId = requestId;
188
544
  if (data instanceof Error) {
189
545
  this.stack = data.stack;
@@ -215,6 +571,68 @@ function getMessage(data) {
215
571
  }
216
572
  }
217
573
 
574
+ function getHostUrl(provider, type) {
575
+ if (isHostProviderAlias(provider)) {
576
+ return providers[provider][type];
577
+ } else if (isHostProviderBuilder(provider)) {
578
+ return provider[type];
579
+ }
580
+ throw new Error("Invalid API provider");
581
+ }
582
+ const providers = {
583
+ production: {
584
+ main: "https://api.xata.io",
585
+ workspaces: "https://{workspaceId}.{region}.xata.sh"
586
+ },
587
+ staging: {
588
+ main: "https://api.staging-xata.dev",
589
+ workspaces: "https://{workspaceId}.{region}.staging-xata.dev"
590
+ },
591
+ dev: {
592
+ main: "https://api.dev-xata.dev",
593
+ workspaces: "https://{workspaceId}.{region}.dev-xata.dev"
594
+ },
595
+ local: {
596
+ main: "http://localhost:6001",
597
+ workspaces: "http://{workspaceId}.{region}.localhost:6001"
598
+ }
599
+ };
600
+ function isHostProviderAlias(alias) {
601
+ return isString(alias) && Object.keys(providers).includes(alias);
602
+ }
603
+ function isHostProviderBuilder(builder) {
604
+ return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
605
+ }
606
+ function parseProviderString(provider = "production") {
607
+ if (isHostProviderAlias(provider)) {
608
+ return provider;
609
+ }
610
+ const [main, workspaces] = provider.split(",");
611
+ if (!main || !workspaces)
612
+ return null;
613
+ return { main, workspaces };
614
+ }
615
+ function buildProviderString(provider) {
616
+ if (isHostProviderAlias(provider))
617
+ return provider;
618
+ return `${provider.main},${provider.workspaces}`;
619
+ }
620
+ function parseWorkspacesUrlParts(url) {
621
+ if (!isString(url))
622
+ return null;
623
+ const matches = {
624
+ production: url.match(/(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/),
625
+ staging: url.match(/(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.staging-xata\.dev.*/),
626
+ dev: url.match(/(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.dev-xata\.dev.*/),
627
+ local: url.match(/(?:https?:\/\/)?([^.]+)(?:\.([^.]+))\.localhost:(\d+)/)
628
+ };
629
+ const [host, match] = Object.entries(matches).find(([, match2]) => match2 !== null) ?? [];
630
+ if (!isHostProviderAlias(host) || !match)
631
+ return null;
632
+ return { workspace: match[1], region: match[2], host };
633
+ }
634
+
635
+ const pool = new ApiRequestPool();
218
636
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
219
637
  const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
220
638
  if (value === void 0 || value === null)
@@ -229,60 +647,110 @@ const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
229
647
  return url.replace(/\{\w*\}/g, (key) => cleanPathParams[key.slice(1, -1)]) + queryString;
230
648
  };
231
649
  function buildBaseUrl({
650
+ method,
651
+ endpoint,
232
652
  path,
233
653
  workspacesApiUrl,
234
654
  apiUrl,
235
- pathParams
655
+ pathParams = {}
236
656
  }) {
237
- if (pathParams?.workspace === void 0)
238
- return `${apiUrl}${path}`;
239
- const url = typeof workspacesApiUrl === "string" ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
240
- return url.replace("{workspaceId}", String(pathParams.workspace));
657
+ if (endpoint === "dataPlane") {
658
+ let url = isString(workspacesApiUrl) ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
659
+ if (method.toUpperCase() === "PUT" && [
660
+ "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
661
+ "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}"
662
+ ].includes(path)) {
663
+ const { host } = parseWorkspacesUrlParts(url) ?? {};
664
+ switch (host) {
665
+ case "production":
666
+ url = url.replace("xata.sh", "upload.xata.sh");
667
+ break;
668
+ case "staging":
669
+ url = url.replace("staging-xata.dev", "upload.staging-xata.dev");
670
+ break;
671
+ case "dev":
672
+ url = url.replace("dev-xata.dev", "upload.dev-xata.dev");
673
+ break;
674
+ }
675
+ }
676
+ const urlWithWorkspace = isString(pathParams.workspace) ? url.replace("{workspaceId}", String(pathParams.workspace)) : url;
677
+ return isString(pathParams.region) ? urlWithWorkspace.replace("{region}", String(pathParams.region)) : urlWithWorkspace;
678
+ }
679
+ return `${apiUrl}${path}`;
241
680
  }
242
681
  function hostHeader(url) {
243
682
  const pattern = /.*:\/\/(?<host>[^/]+).*/;
244
683
  const { groups } = pattern.exec(url) ?? {};
245
684
  return groups?.host ? { Host: groups.host } : {};
246
685
  }
686
+ async function parseBody(body, headers) {
687
+ if (!isDefined(body))
688
+ return void 0;
689
+ if (isBlob(body) || typeof body.text === "function") {
690
+ return body;
691
+ }
692
+ const { "Content-Type": contentType } = headers ?? {};
693
+ if (String(contentType).toLowerCase() === "application/json" && isObject(body)) {
694
+ return JSON.stringify(body);
695
+ }
696
+ return body;
697
+ }
698
+ const defaultClientID = generateUUID();
247
699
  async function fetch$1({
248
700
  url: path,
249
701
  method,
250
702
  body,
251
- headers,
703
+ headers: customHeaders,
252
704
  pathParams,
253
705
  queryParams,
254
- fetchImpl,
706
+ fetch: fetch2,
255
707
  apiKey,
708
+ endpoint,
256
709
  apiUrl,
257
710
  workspacesApiUrl,
258
711
  trace,
259
- signal
712
+ signal,
713
+ clientID,
714
+ sessionID,
715
+ clientName,
716
+ xataAgentExtra,
717
+ fetchOptions = {},
718
+ rawResponse = false
260
719
  }) {
261
- return trace(
720
+ pool.setFetch(fetch2);
721
+ return await trace(
262
722
  `${method.toUpperCase()} ${path}`,
263
723
  async ({ setAttributes }) => {
264
- const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
724
+ const baseUrl = buildBaseUrl({ method, endpoint, path, workspacesApiUrl, pathParams, apiUrl });
265
725
  const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
266
- const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
726
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\.[^.]+\./, "http://") : fullUrl;
267
727
  setAttributes({
268
728
  [TraceAttributes.HTTP_URL]: url,
269
729
  [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
270
730
  });
271
- const response = await fetchImpl(url, {
731
+ const xataAgent = compact([
732
+ ["client", "TS_SDK"],
733
+ ["version", VERSION],
734
+ isDefined(clientName) ? ["service", clientName] : void 0,
735
+ ...Object.entries(xataAgentExtra ?? {})
736
+ ]).map(([key, value]) => `${key}=${value}`).join("; ");
737
+ const headers = compactObject({
738
+ "Accept-Encoding": "identity",
739
+ "Content-Type": "application/json",
740
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
741
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
742
+ "X-Xata-Agent": xataAgent,
743
+ ...customHeaders,
744
+ ...hostHeader(fullUrl),
745
+ Authorization: `Bearer ${apiKey}`
746
+ });
747
+ const response = await pool.request(url, {
748
+ ...fetchOptions,
272
749
  method: method.toUpperCase(),
273
- body: body ? JSON.stringify(body) : void 0,
274
- headers: {
275
- "Content-Type": "application/json",
276
- "User-Agent": `Xata client-ts/${VERSION}`,
277
- ...headers,
278
- ...hostHeader(fullUrl),
279
- Authorization: `Bearer ${apiKey}`
280
- },
750
+ body: await parseBody(body, headers),
751
+ headers,
281
752
  signal
282
753
  });
283
- if (response.status === 204) {
284
- return {};
285
- }
286
754
  const { host, protocol } = parseUrl(response.url);
287
755
  const requestId = response.headers?.get("x-request-id") ?? void 0;
288
756
  setAttributes({
@@ -290,10 +758,20 @@ async function fetch$1({
290
758
  [TraceAttributes.HTTP_REQUEST_ID]: requestId,
291
759
  [TraceAttributes.HTTP_STATUS_CODE]: response.status,
292
760
  [TraceAttributes.HTTP_HOST]: host,
293
- [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
761
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", ""),
762
+ [TraceAttributes.CLOUDFLARE_RAY_ID]: response.headers?.get("cf-ray") ?? void 0
294
763
  });
764
+ const message = response.headers?.get("x-xata-message");
765
+ if (message)
766
+ console.warn(message);
767
+ if (response.status === 204) {
768
+ return {};
769
+ }
770
+ if (response.status === 429) {
771
+ throw new FetcherError(response.status, "Rate limit exceeded", requestId);
772
+ }
295
773
  try {
296
- const jsonResponse = await response.json();
774
+ const jsonResponse = rawResponse ? await response.blob() : await response.json();
297
775
  if (response.ok) {
298
776
  return jsonResponse;
299
777
  }
@@ -305,6 +783,59 @@ async function fetch$1({
305
783
  { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
306
784
  );
307
785
  }
786
+ function fetchSSERequest({
787
+ url: path,
788
+ method,
789
+ body,
790
+ headers: customHeaders,
791
+ pathParams,
792
+ queryParams,
793
+ fetch: fetch2,
794
+ apiKey,
795
+ endpoint,
796
+ apiUrl,
797
+ workspacesApiUrl,
798
+ onMessage,
799
+ onError,
800
+ onClose,
801
+ signal,
802
+ clientID,
803
+ sessionID,
804
+ clientName,
805
+ xataAgentExtra
806
+ }) {
807
+ const baseUrl = buildBaseUrl({ method, endpoint, path, workspacesApiUrl, pathParams, apiUrl });
808
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
809
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
810
+ void fetchEventSource(url, {
811
+ method,
812
+ body: JSON.stringify(body),
813
+ fetch: fetch2,
814
+ signal,
815
+ headers: {
816
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
817
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
818
+ "X-Xata-Agent": compact([
819
+ ["client", "TS_SDK"],
820
+ ["version", VERSION],
821
+ isDefined(clientName) ? ["service", clientName] : void 0,
822
+ ...Object.entries(xataAgentExtra ?? {})
823
+ ]).map(([key, value]) => `${key}=${value}`).join("; "),
824
+ ...customHeaders,
825
+ Authorization: `Bearer ${apiKey}`,
826
+ "Content-Type": "application/json"
827
+ },
828
+ onmessage(ev) {
829
+ onMessage?.(JSON.parse(ev.data));
830
+ },
831
+ onerror(ev) {
832
+ onError?.(JSON.parse(ev.data));
833
+ },
834
+ onclose() {
835
+ onClose?.();
836
+ }
837
+ });
838
+ }
308
839
  function parseUrl(url) {
309
840
  try {
310
841
  const { host, protocol } = new URL(url);
@@ -314,1028 +845,749 @@ function parseUrl(url) {
314
845
  }
315
846
  }
316
847
 
317
- const getUser = (variables, signal) => fetch$1({ url: "/user", method: "get", ...variables, signal });
318
- const updateUser = (variables, signal) => fetch$1({
319
- url: "/user",
320
- method: "put",
848
+ const dataPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "dataPlane" });
849
+
850
+ const applyMigration = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/pgroll/apply", method: "post", ...variables, signal });
851
+ const pgRollStatus = (variables, signal) => dataPlaneFetch({
852
+ url: "/db/{dbBranchName}/pgroll/status",
853
+ method: "get",
321
854
  ...variables,
322
855
  signal
323
856
  });
324
- const deleteUser = (variables, signal) => fetch$1({ url: "/user", method: "delete", ...variables, signal });
325
- const getUserAPIKeys = (variables, signal) => fetch$1({
326
- url: "/user/keys",
857
+ const pgRollJobStatus = (variables, signal) => dataPlaneFetch({
858
+ url: "/db/{dbBranchName}/pgroll/jobs/{jobId}",
327
859
  method: "get",
328
860
  ...variables,
329
861
  signal
330
862
  });
331
- const createUserAPIKey = (variables, signal) => fetch$1({
332
- url: "/user/keys/{keyName}",
333
- method: "post",
863
+ const pgRollMigrationHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/pgroll/migrations", method: "get", ...variables, signal });
864
+ const getBranchList = (variables, signal) => dataPlaneFetch({
865
+ url: "/dbs/{dbName}",
866
+ method: "get",
334
867
  ...variables,
335
868
  signal
336
869
  });
337
- const deleteUserAPIKey = (variables, signal) => fetch$1({
338
- url: "/user/keys/{keyName}",
339
- method: "delete",
870
+ const getBranchDetails = (variables, signal) => dataPlaneFetch({
871
+ url: "/db/{dbBranchName}",
872
+ method: "get",
340
873
  ...variables,
341
874
  signal
342
875
  });
343
- const createWorkspace = (variables, signal) => fetch$1({
344
- url: "/workspaces",
345
- method: "post",
876
+ const createBranch = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}", method: "put", ...variables, signal });
877
+ const deleteBranch = (variables, signal) => dataPlaneFetch({
878
+ url: "/db/{dbBranchName}",
879
+ method: "delete",
346
880
  ...variables,
347
881
  signal
348
882
  });
349
- const getWorkspacesList = (variables, signal) => fetch$1({
350
- url: "/workspaces",
883
+ const getSchema = (variables, signal) => dataPlaneFetch({
884
+ url: "/db/{dbBranchName}/schema",
351
885
  method: "get",
352
886
  ...variables,
353
887
  signal
354
888
  });
355
- const getWorkspace = (variables, signal) => fetch$1({
356
- url: "/workspaces/{workspaceId}",
357
- method: "get",
889
+ const copyBranch = (variables, signal) => dataPlaneFetch({
890
+ url: "/db/{dbBranchName}/copy",
891
+ method: "post",
358
892
  ...variables,
359
893
  signal
360
894
  });
361
- const updateWorkspace = (variables, signal) => fetch$1({
362
- url: "/workspaces/{workspaceId}",
895
+ const updateBranchMetadata = (variables, signal) => dataPlaneFetch({
896
+ url: "/db/{dbBranchName}/metadata",
363
897
  method: "put",
364
898
  ...variables,
365
899
  signal
366
900
  });
367
- const deleteWorkspace = (variables, signal) => fetch$1({
368
- url: "/workspaces/{workspaceId}",
369
- method: "delete",
901
+ const getBranchMetadata = (variables, signal) => dataPlaneFetch({
902
+ url: "/db/{dbBranchName}/metadata",
903
+ method: "get",
370
904
  ...variables,
371
905
  signal
372
906
  });
373
- const getWorkspaceMembersList = (variables, signal) => fetch$1({
374
- url: "/workspaces/{workspaceId}/members",
907
+ const getBranchStats = (variables, signal) => dataPlaneFetch({
908
+ url: "/db/{dbBranchName}/stats",
375
909
  method: "get",
376
910
  ...variables,
377
911
  signal
378
912
  });
379
- const updateWorkspaceMemberRole = (variables, signal) => fetch$1({ url: "/workspaces/{workspaceId}/members/{userId}", method: "put", ...variables, signal });
380
- const removeWorkspaceMember = (variables, signal) => fetch$1({
381
- url: "/workspaces/{workspaceId}/members/{userId}",
382
- method: "delete",
913
+ const getGitBranchesMapping = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables, signal });
914
+ const addGitBranchesEntry = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables, signal });
915
+ const removeGitBranchesEntry = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables, signal });
916
+ const resolveBranch = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/resolveBranch", method: "get", ...variables, signal });
917
+ const getBranchMigrationHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables, signal });
918
+ const getBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables, signal });
919
+ const executeBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables, signal });
920
+ const queryMigrationRequests = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/query", method: "post", ...variables, signal });
921
+ const createMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations", method: "post", ...variables, signal });
922
+ const getMigrationRequest = (variables, signal) => dataPlaneFetch({
923
+ url: "/dbs/{dbName}/migrations/{mrNumber}",
924
+ method: "get",
383
925
  ...variables,
384
926
  signal
385
927
  });
386
- const inviteWorkspaceMember = (variables, signal) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables, signal });
387
- const updateWorkspaceMemberInvite = (variables, signal) => fetch$1({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables, signal });
388
- const cancelWorkspaceMemberInvite = (variables, signal) => fetch$1({
389
- url: "/workspaces/{workspaceId}/invites/{inviteId}",
390
- method: "delete",
928
+ const updateMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/{mrNumber}", method: "patch", ...variables, signal });
929
+ const listMigrationRequestsCommits = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/{mrNumber}/commits", method: "post", ...variables, signal });
930
+ const compareMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/{mrNumber}/compare", method: "post", ...variables, signal });
931
+ const getMigrationRequestIsMerged = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/{mrNumber}/merge", method: "get", ...variables, signal });
932
+ const mergeMigrationRequest = (variables, signal) => dataPlaneFetch({
933
+ url: "/dbs/{dbName}/migrations/{mrNumber}/merge",
934
+ method: "post",
391
935
  ...variables,
392
936
  signal
393
937
  });
394
- const resendWorkspaceMemberInvite = (variables, signal) => fetch$1({
395
- url: "/workspaces/{workspaceId}/invites/{inviteId}/resend",
396
- method: "post",
938
+ const getBranchSchemaHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/history", method: "post", ...variables, signal });
939
+ const compareBranchWithUserSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/compare", method: "post", ...variables, signal });
940
+ const compareBranchSchemas = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/compare/{branchName}", method: "post", ...variables, signal });
941
+ const updateBranchSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/update", method: "post", ...variables, signal });
942
+ const previewBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables, signal });
943
+ const applyBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables, signal });
944
+ const pushBranchMigrations = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/push", method: "post", ...variables, signal });
945
+ const createTable = (variables, signal) => dataPlaneFetch({
946
+ url: "/db/{dbBranchName}/tables/{tableName}",
947
+ method: "put",
397
948
  ...variables,
398
949
  signal
399
950
  });
400
- const acceptWorkspaceMemberInvite = (variables, signal) => fetch$1({
401
- url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept",
402
- method: "post",
951
+ const deleteTable = (variables, signal) => dataPlaneFetch({
952
+ url: "/db/{dbBranchName}/tables/{tableName}",
953
+ method: "delete",
403
954
  ...variables,
404
955
  signal
405
956
  });
406
- const getDatabaseList = (variables, signal) => fetch$1({
407
- url: "/dbs",
957
+ const updateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}", method: "patch", ...variables, signal });
958
+ const getTableSchema = (variables, signal) => dataPlaneFetch({
959
+ url: "/db/{dbBranchName}/tables/{tableName}/schema",
408
960
  method: "get",
409
961
  ...variables,
410
962
  signal
411
963
  });
412
- const getBranchList = (variables, signal) => fetch$1({
413
- url: "/dbs/{dbName}",
964
+ const setTableSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/schema", method: "put", ...variables, signal });
965
+ const getTableColumns = (variables, signal) => dataPlaneFetch({
966
+ url: "/db/{dbBranchName}/tables/{tableName}/columns",
414
967
  method: "get",
415
968
  ...variables,
416
969
  signal
417
970
  });
418
- const createDatabase = (variables, signal) => fetch$1({
419
- url: "/dbs/{dbName}",
420
- method: "put",
971
+ const addTableColumn = (variables, signal) => dataPlaneFetch(
972
+ { url: "/db/{dbBranchName}/tables/{tableName}/columns", method: "post", ...variables, signal }
973
+ );
974
+ const getColumn = (variables, signal) => dataPlaneFetch({
975
+ url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
976
+ method: "get",
421
977
  ...variables,
422
978
  signal
423
979
  });
424
- const deleteDatabase = (variables, signal) => fetch$1({
425
- url: "/dbs/{dbName}",
980
+ const updateColumn = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}", method: "patch", ...variables, signal });
981
+ const deleteColumn = (variables, signal) => dataPlaneFetch({
982
+ url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
426
983
  method: "delete",
427
984
  ...variables,
428
985
  signal
429
986
  });
430
- const getDatabaseMetadata = (variables, signal) => fetch$1({
431
- url: "/dbs/{dbName}/metadata",
987
+ const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
988
+ const insertRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
989
+ const getFileItem = (variables, signal) => dataPlaneFetch({
990
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
432
991
  method: "get",
433
992
  ...variables,
434
993
  signal
435
994
  });
436
- const updateDatabaseMetadata = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/metadata", method: "patch", ...variables, signal });
437
- const getGitBranchesMapping = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables, signal });
438
- const addGitBranchesEntry = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables, signal });
439
- const removeGitBranchesEntry = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables, signal });
440
- const resolveBranch = (variables, signal) => fetch$1({
441
- url: "/dbs/{dbName}/resolveBranch",
442
- method: "get",
995
+ const putFileItem = (variables, signal) => dataPlaneFetch({
996
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
997
+ method: "put",
443
998
  ...variables,
444
999
  signal
445
1000
  });
446
- const queryMigrationRequests = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/migrations/query", method: "post", ...variables, signal });
447
- const createMigrationRequest = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/migrations", method: "post", ...variables, signal });
448
- const getMigrationRequest = (variables, signal) => fetch$1({
449
- url: "/dbs/{dbName}/migrations/{mrNumber}",
1001
+ const deleteFileItem = (variables, signal) => dataPlaneFetch({
1002
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
1003
+ method: "delete",
1004
+ ...variables,
1005
+ signal
1006
+ });
1007
+ const getFile = (variables, signal) => dataPlaneFetch({
1008
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
450
1009
  method: "get",
451
1010
  ...variables,
452
1011
  signal
453
1012
  });
454
- const updateMigrationRequest = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}", method: "patch", ...variables, signal });
455
- const listMigrationRequestsCommits = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/commits", method: "post", ...variables, signal });
456
- const compareMigrationRequest = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/compare", method: "post", ...variables, signal });
457
- const getMigrationRequestIsMerged = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/merge", method: "get", ...variables, signal });
458
- const mergeMigrationRequest = (variables, signal) => fetch$1({
459
- url: "/dbs/{dbName}/migrations/{mrNumber}/merge",
460
- method: "post",
1013
+ const putFile = (variables, signal) => dataPlaneFetch({
1014
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
1015
+ method: "put",
461
1016
  ...variables,
462
1017
  signal
463
1018
  });
464
- const getBranchDetails = (variables, signal) => fetch$1({
465
- url: "/db/{dbBranchName}",
1019
+ const deleteFile = (variables, signal) => dataPlaneFetch({
1020
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
1021
+ method: "delete",
1022
+ ...variables,
1023
+ signal
1024
+ });
1025
+ const getRecord = (variables, signal) => dataPlaneFetch({
1026
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
466
1027
  method: "get",
467
1028
  ...variables,
468
1029
  signal
469
1030
  });
470
- const createBranch = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}", method: "put", ...variables, signal });
471
- const deleteBranch = (variables, signal) => fetch$1({
472
- url: "/db/{dbBranchName}",
473
- method: "delete",
1031
+ const insertRecordWithID = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables, signal });
1032
+ const updateRecordWithID = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables, signal });
1033
+ const upsertRecordWithID = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables, signal });
1034
+ const deleteRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "delete", ...variables, signal });
1035
+ const bulkInsertTableRecords = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/bulk", method: "post", ...variables, signal });
1036
+ const queryTable = (variables, signal) => dataPlaneFetch({
1037
+ url: "/db/{dbBranchName}/tables/{tableName}/query",
1038
+ method: "post",
474
1039
  ...variables,
475
1040
  signal
476
1041
  });
477
- const updateBranchMetadata = (variables, signal) => fetch$1({
478
- url: "/db/{dbBranchName}/metadata",
479
- method: "put",
1042
+ const searchBranch = (variables, signal) => dataPlaneFetch({
1043
+ url: "/db/{dbBranchName}/search",
1044
+ method: "post",
480
1045
  ...variables,
481
1046
  signal
482
1047
  });
483
- const getBranchMetadata = (variables, signal) => fetch$1({
484
- url: "/db/{dbBranchName}/metadata",
485
- method: "get",
1048
+ const searchTable = (variables, signal) => dataPlaneFetch({
1049
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
1050
+ method: "post",
486
1051
  ...variables,
487
1052
  signal
488
1053
  });
489
- const getBranchMigrationHistory = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables, signal });
490
- const executeBranchMigrationPlan = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables, signal });
491
- const getBranchMigrationPlan = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables, signal });
492
- const compareBranchWithUserSchema = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/schema/compare", method: "post", ...variables, signal });
493
- const compareBranchSchemas = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/schema/compare/{branchName}", method: "post", ...variables, signal });
494
- const updateBranchSchema = (variables, signal) => fetch$1({
495
- url: "/db/{dbBranchName}/schema/update",
1054
+ const vectorSearchTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/vectorSearch", method: "post", ...variables, signal });
1055
+ const askTable = (variables, signal) => dataPlaneFetch({
1056
+ url: "/db/{dbBranchName}/tables/{tableName}/ask",
496
1057
  method: "post",
497
1058
  ...variables,
498
1059
  signal
499
1060
  });
500
- const previewBranchSchemaEdit = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables, signal });
501
- const applyBranchSchemaEdit = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables, signal });
502
- const getBranchSchemaHistory = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/schema/history", method: "post", ...variables, signal });
503
- const getBranchStats = (variables, signal) => fetch$1({
504
- url: "/db/{dbBranchName}/stats",
1061
+ const askTableSession = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}", method: "post", ...variables, signal });
1062
+ const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
1063
+ const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
1064
+ const fileAccess = (variables, signal) => dataPlaneFetch({
1065
+ url: "/file/{fileId}",
505
1066
  method: "get",
506
1067
  ...variables,
507
1068
  signal
508
1069
  });
509
- const createTable = (variables, signal) => fetch$1({
510
- url: "/db/{dbBranchName}/tables/{tableName}",
1070
+ const fileUpload = (variables, signal) => dataPlaneFetch({
1071
+ url: "/file/{fileId}",
511
1072
  method: "put",
512
1073
  ...variables,
513
1074
  signal
514
1075
  });
515
- const deleteTable = (variables, signal) => fetch$1({
516
- url: "/db/{dbBranchName}/tables/{tableName}",
517
- method: "delete",
1076
+ const sqlQuery = (variables, signal) => dataPlaneFetch({
1077
+ url: "/db/{dbBranchName}/sql",
1078
+ method: "post",
518
1079
  ...variables,
519
1080
  signal
520
1081
  });
521
- const updateTable = (variables, signal) => fetch$1({
522
- url: "/db/{dbBranchName}/tables/{tableName}",
523
- method: "patch",
1082
+ const operationsByTag$2 = {
1083
+ branch: {
1084
+ applyMigration,
1085
+ pgRollStatus,
1086
+ pgRollJobStatus,
1087
+ pgRollMigrationHistory,
1088
+ getBranchList,
1089
+ getBranchDetails,
1090
+ createBranch,
1091
+ deleteBranch,
1092
+ copyBranch,
1093
+ updateBranchMetadata,
1094
+ getBranchMetadata,
1095
+ getBranchStats,
1096
+ getGitBranchesMapping,
1097
+ addGitBranchesEntry,
1098
+ removeGitBranchesEntry,
1099
+ resolveBranch
1100
+ },
1101
+ migrations: {
1102
+ getSchema,
1103
+ getBranchMigrationHistory,
1104
+ getBranchMigrationPlan,
1105
+ executeBranchMigrationPlan,
1106
+ getBranchSchemaHistory,
1107
+ compareBranchWithUserSchema,
1108
+ compareBranchSchemas,
1109
+ updateBranchSchema,
1110
+ previewBranchSchemaEdit,
1111
+ applyBranchSchemaEdit,
1112
+ pushBranchMigrations
1113
+ },
1114
+ migrationRequests: {
1115
+ queryMigrationRequests,
1116
+ createMigrationRequest,
1117
+ getMigrationRequest,
1118
+ updateMigrationRequest,
1119
+ listMigrationRequestsCommits,
1120
+ compareMigrationRequest,
1121
+ getMigrationRequestIsMerged,
1122
+ mergeMigrationRequest
1123
+ },
1124
+ table: {
1125
+ createTable,
1126
+ deleteTable,
1127
+ updateTable,
1128
+ getTableSchema,
1129
+ setTableSchema,
1130
+ getTableColumns,
1131
+ addTableColumn,
1132
+ getColumn,
1133
+ updateColumn,
1134
+ deleteColumn
1135
+ },
1136
+ records: {
1137
+ branchTransaction,
1138
+ insertRecord,
1139
+ getRecord,
1140
+ insertRecordWithID,
1141
+ updateRecordWithID,
1142
+ upsertRecordWithID,
1143
+ deleteRecord,
1144
+ bulkInsertTableRecords
1145
+ },
1146
+ files: { getFileItem, putFileItem, deleteFileItem, getFile, putFile, deleteFile, fileAccess, fileUpload },
1147
+ searchAndFilter: {
1148
+ queryTable,
1149
+ searchBranch,
1150
+ searchTable,
1151
+ vectorSearchTable,
1152
+ askTable,
1153
+ askTableSession,
1154
+ summarizeTable,
1155
+ aggregateTable
1156
+ },
1157
+ sql: { sqlQuery }
1158
+ };
1159
+
1160
+ const controlPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "controlPlane" });
1161
+
1162
+ const getAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "get", ...variables, signal });
1163
+ const grantAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "post", ...variables, signal });
1164
+ const getUser = (variables, signal) => controlPlaneFetch({
1165
+ url: "/user",
1166
+ method: "get",
524
1167
  ...variables,
525
1168
  signal
526
1169
  });
527
- const getTableSchema = (variables, signal) => fetch$1({
528
- url: "/db/{dbBranchName}/tables/{tableName}/schema",
529
- method: "get",
1170
+ const updateUser = (variables, signal) => controlPlaneFetch({
1171
+ url: "/user",
1172
+ method: "put",
530
1173
  ...variables,
531
1174
  signal
532
1175
  });
533
- const setTableSchema = (variables, signal) => fetch$1({
534
- url: "/db/{dbBranchName}/tables/{tableName}/schema",
535
- method: "put",
1176
+ const deleteUser = (variables, signal) => controlPlaneFetch({
1177
+ url: "/user",
1178
+ method: "delete",
536
1179
  ...variables,
537
1180
  signal
538
1181
  });
539
- const getTableColumns = (variables, signal) => fetch$1({
540
- url: "/db/{dbBranchName}/tables/{tableName}/columns",
1182
+ const getUserAPIKeys = (variables, signal) => controlPlaneFetch({
1183
+ url: "/user/keys",
541
1184
  method: "get",
542
1185
  ...variables,
543
1186
  signal
544
1187
  });
545
- const addTableColumn = (variables, signal) => fetch$1({
546
- url: "/db/{dbBranchName}/tables/{tableName}/columns",
1188
+ const createUserAPIKey = (variables, signal) => controlPlaneFetch({
1189
+ url: "/user/keys/{keyName}",
547
1190
  method: "post",
548
1191
  ...variables,
549
1192
  signal
550
1193
  });
551
- const getColumn = (variables, signal) => fetch$1({
552
- url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
1194
+ const deleteUserAPIKey = (variables, signal) => controlPlaneFetch({
1195
+ url: "/user/keys/{keyName}",
1196
+ method: "delete",
1197
+ ...variables,
1198
+ signal
1199
+ });
1200
+ const getUserOAuthClients = (variables, signal) => controlPlaneFetch({
1201
+ url: "/user/oauth/clients",
553
1202
  method: "get",
554
1203
  ...variables,
555
1204
  signal
556
1205
  });
557
- const deleteColumn = (variables, signal) => fetch$1({
558
- url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
1206
+ const deleteUserOAuthClient = (variables, signal) => controlPlaneFetch({
1207
+ url: "/user/oauth/clients/{clientId}",
559
1208
  method: "delete",
560
1209
  ...variables,
561
1210
  signal
562
1211
  });
563
- const updateColumn = (variables, signal) => fetch$1({
564
- url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
565
- method: "patch",
1212
+ const getUserOAuthAccessTokens = (variables, signal) => controlPlaneFetch({
1213
+ url: "/user/oauth/tokens",
1214
+ method: "get",
566
1215
  ...variables,
567
1216
  signal
568
1217
  });
569
- const insertRecord = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
570
- const insertRecordWithID = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables, signal });
571
- const updateRecordWithID = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables, signal });
572
- const upsertRecordWithID = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables, signal });
573
- const deleteRecord = (variables, signal) => fetch$1({
574
- url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
1218
+ const deleteOAuthAccessToken = (variables, signal) => controlPlaneFetch({
1219
+ url: "/user/oauth/tokens/{token}",
575
1220
  method: "delete",
576
1221
  ...variables,
577
1222
  signal
578
1223
  });
579
- const getRecord = (variables, signal) => fetch$1({
580
- url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
1224
+ const updateOAuthAccessToken = (variables, signal) => controlPlaneFetch({ url: "/user/oauth/tokens/{token}", method: "patch", ...variables, signal });
1225
+ const getWorkspacesList = (variables, signal) => controlPlaneFetch({
1226
+ url: "/workspaces",
581
1227
  method: "get",
582
1228
  ...variables,
583
1229
  signal
584
1230
  });
585
- const bulkInsertTableRecords = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/bulk", method: "post", ...variables, signal });
586
- const queryTable = (variables, signal) => fetch$1({
587
- url: "/db/{dbBranchName}/tables/{tableName}/query",
1231
+ const createWorkspace = (variables, signal) => controlPlaneFetch({
1232
+ url: "/workspaces",
588
1233
  method: "post",
589
1234
  ...variables,
590
1235
  signal
591
1236
  });
592
- const searchTable = (variables, signal) => fetch$1({
593
- url: "/db/{dbBranchName}/tables/{tableName}/search",
594
- method: "post",
1237
+ const getWorkspace = (variables, signal) => controlPlaneFetch({
1238
+ url: "/workspaces/{workspaceId}",
1239
+ method: "get",
595
1240
  ...variables,
596
1241
  signal
597
1242
  });
598
- const searchBranch = (variables, signal) => fetch$1({
599
- url: "/db/{dbBranchName}/search",
600
- method: "post",
1243
+ const updateWorkspace = (variables, signal) => controlPlaneFetch({
1244
+ url: "/workspaces/{workspaceId}",
1245
+ method: "put",
601
1246
  ...variables,
602
1247
  signal
603
1248
  });
604
- const summarizeTable = (variables, signal) => fetch$1({
605
- url: "/db/{dbBranchName}/tables/{tableName}/summarize",
606
- method: "post",
1249
+ const deleteWorkspace = (variables, signal) => controlPlaneFetch({
1250
+ url: "/workspaces/{workspaceId}",
1251
+ method: "delete",
607
1252
  ...variables,
608
1253
  signal
609
1254
  });
610
- const aggregateTable = (variables) => fetch$1({
611
- url: "/db/{dbBranchName}/tables/{tableName}/aggregate",
612
- method: "post",
613
- ...variables
1255
+ const getWorkspaceMembersList = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/members", method: "get", ...variables, signal });
1256
+ const updateWorkspaceMemberRole = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/members/{userId}", method: "put", ...variables, signal });
1257
+ const removeWorkspaceMember = (variables, signal) => controlPlaneFetch({
1258
+ url: "/workspaces/{workspaceId}/members/{userId}",
1259
+ method: "delete",
1260
+ ...variables,
1261
+ signal
614
1262
  });
615
- const operationsByTag = {
616
- users: { getUser, updateUser, deleteUser, getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
1263
+ const inviteWorkspaceMember = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables, signal });
1264
+ const updateWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables, signal });
1265
+ const cancelWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "delete", ...variables, signal });
1266
+ const acceptWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept", method: "post", ...variables, signal });
1267
+ const resendWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}/resend", method: "post", ...variables, signal });
1268
+ const listClusters = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/clusters", method: "get", ...variables, signal });
1269
+ const createCluster = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/clusters", method: "post", ...variables, signal });
1270
+ const getCluster = (variables, signal) => controlPlaneFetch({
1271
+ url: "/workspaces/{workspaceId}/clusters/{clusterId}",
1272
+ method: "get",
1273
+ ...variables,
1274
+ signal
1275
+ });
1276
+ const updateCluster = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/clusters/{clusterId}", method: "patch", ...variables, signal });
1277
+ const getDatabaseList = (variables, signal) => controlPlaneFetch({
1278
+ url: "/workspaces/{workspaceId}/dbs",
1279
+ method: "get",
1280
+ ...variables,
1281
+ signal
1282
+ });
1283
+ const createDatabase = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "put", ...variables, signal });
1284
+ const deleteDatabase = (variables, signal) => controlPlaneFetch({
1285
+ url: "/workspaces/{workspaceId}/dbs/{dbName}",
1286
+ method: "delete",
1287
+ ...variables,
1288
+ signal
1289
+ });
1290
+ const getDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "get", ...variables, signal });
1291
+ const updateDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "patch", ...variables, signal });
1292
+ const renameDatabase = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/rename", method: "post", ...variables, signal });
1293
+ const getDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "get", ...variables, signal });
1294
+ const updateDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "put", ...variables, signal });
1295
+ const deleteDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "delete", ...variables, signal });
1296
+ const listRegions = (variables, signal) => controlPlaneFetch({
1297
+ url: "/workspaces/{workspaceId}/regions",
1298
+ method: "get",
1299
+ ...variables,
1300
+ signal
1301
+ });
1302
+ const operationsByTag$1 = {
1303
+ oAuth: {
1304
+ getAuthorizationCode,
1305
+ grantAuthorizationCode,
1306
+ getUserOAuthClients,
1307
+ deleteUserOAuthClient,
1308
+ getUserOAuthAccessTokens,
1309
+ deleteOAuthAccessToken,
1310
+ updateOAuthAccessToken
1311
+ },
1312
+ users: { getUser, updateUser, deleteUser },
1313
+ authentication: { getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
617
1314
  workspaces: {
618
- createWorkspace,
619
1315
  getWorkspacesList,
1316
+ createWorkspace,
620
1317
  getWorkspace,
621
1318
  updateWorkspace,
622
1319
  deleteWorkspace,
623
1320
  getWorkspaceMembersList,
624
1321
  updateWorkspaceMemberRole,
625
- removeWorkspaceMember,
1322
+ removeWorkspaceMember
1323
+ },
1324
+ invites: {
626
1325
  inviteWorkspaceMember,
627
1326
  updateWorkspaceMemberInvite,
628
1327
  cancelWorkspaceMemberInvite,
629
- resendWorkspaceMemberInvite,
630
- acceptWorkspaceMemberInvite
1328
+ acceptWorkspaceMemberInvite,
1329
+ resendWorkspaceMemberInvite
631
1330
  },
632
- database: {
1331
+ xbcontrolOther: { listClusters, createCluster, getCluster, updateCluster },
1332
+ databases: {
633
1333
  getDatabaseList,
634
1334
  createDatabase,
635
1335
  deleteDatabase,
636
1336
  getDatabaseMetadata,
637
1337
  updateDatabaseMetadata,
638
- getGitBranchesMapping,
639
- addGitBranchesEntry,
640
- removeGitBranchesEntry,
641
- resolveBranch
642
- },
643
- branch: {
644
- getBranchList,
645
- getBranchDetails,
646
- createBranch,
647
- deleteBranch,
648
- updateBranchMetadata,
649
- getBranchMetadata,
650
- getBranchStats
651
- },
652
- migrationRequests: {
653
- queryMigrationRequests,
654
- createMigrationRequest,
655
- getMigrationRequest,
656
- updateMigrationRequest,
657
- listMigrationRequestsCommits,
658
- compareMigrationRequest,
659
- getMigrationRequestIsMerged,
660
- mergeMigrationRequest
661
- },
662
- branchSchema: {
663
- getBranchMigrationHistory,
664
- executeBranchMigrationPlan,
665
- getBranchMigrationPlan,
666
- compareBranchWithUserSchema,
667
- compareBranchSchemas,
668
- updateBranchSchema,
669
- previewBranchSchemaEdit,
670
- applyBranchSchemaEdit,
671
- getBranchSchemaHistory
672
- },
673
- table: {
674
- createTable,
675
- deleteTable,
676
- updateTable,
677
- getTableSchema,
678
- setTableSchema,
679
- getTableColumns,
680
- addTableColumn,
681
- getColumn,
682
- deleteColumn,
683
- updateColumn
684
- },
685
- records: {
686
- insertRecord,
687
- insertRecordWithID,
688
- updateRecordWithID,
689
- upsertRecordWithID,
690
- deleteRecord,
691
- getRecord,
692
- bulkInsertTableRecords,
693
- queryTable,
694
- searchTable,
695
- searchBranch,
696
- summarizeTable,
697
- aggregateTable
1338
+ renameDatabase,
1339
+ getDatabaseGithubSettings,
1340
+ updateDatabaseGithubSettings,
1341
+ deleteDatabaseGithubSettings,
1342
+ listRegions
698
1343
  }
699
1344
  };
700
1345
 
701
- function getHostUrl(provider, type) {
702
- if (isHostProviderAlias(provider)) {
703
- return providers[provider][type];
704
- } else if (isHostProviderBuilder(provider)) {
705
- return provider[type];
706
- }
707
- throw new Error("Invalid API provider");
708
- }
709
- const providers = {
710
- production: {
711
- main: "https://api.xata.io",
712
- workspaces: "https://{workspaceId}.xata.sh"
713
- },
714
- staging: {
715
- main: "https://staging.xatabase.co",
716
- workspaces: "https://{workspaceId}.staging.xatabase.co"
717
- }
718
- };
719
- function isHostProviderAlias(alias) {
720
- return isString(alias) && Object.keys(providers).includes(alias);
721
- }
722
- function isHostProviderBuilder(builder) {
723
- return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
724
- }
725
- function parseProviderString(provider = "production") {
726
- if (isHostProviderAlias(provider)) {
727
- return provider;
728
- }
729
- const [main, workspaces] = provider.split(",");
730
- if (!main || !workspaces)
731
- return null;
732
- return { main, workspaces };
733
- }
1346
+ const operationsByTag = deepMerge(operationsByTag$2, operationsByTag$1);
734
1347
 
735
- var __accessCheck$7 = (obj, member, msg) => {
736
- if (!member.has(obj))
737
- throw TypeError("Cannot " + msg);
738
- };
739
- var __privateGet$7 = (obj, member, getter) => {
740
- __accessCheck$7(obj, member, "read from private field");
741
- return getter ? getter.call(obj) : member.get(obj);
742
- };
743
- var __privateAdd$7 = (obj, member, value) => {
744
- if (member.has(obj))
745
- throw TypeError("Cannot add the same private member more than once");
746
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
747
- };
748
- var __privateSet$7 = (obj, member, value, setter) => {
749
- __accessCheck$7(obj, member, "write to private field");
750
- setter ? setter.call(obj, value) : member.set(obj, value);
751
- return value;
752
- };
753
- var _extraProps, _namespaces;
754
- class XataApiClient {
1348
+ const buildApiClient = () => class {
755
1349
  constructor(options = {}) {
756
- __privateAdd$7(this, _extraProps, void 0);
757
- __privateAdd$7(this, _namespaces, {});
758
1350
  const provider = options.host ?? "production";
759
1351
  const apiKey = options.apiKey ?? getAPIKey();
760
1352
  const trace = options.trace ?? defaultTrace;
1353
+ const clientID = generateUUID();
761
1354
  if (!apiKey) {
762
1355
  throw new Error("Could not resolve a valid apiKey");
763
1356
  }
764
- __privateSet$7(this, _extraProps, {
1357
+ const extraProps = {
765
1358
  apiUrl: getHostUrl(provider, "main"),
766
1359
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
767
- fetchImpl: getFetchImplementation(options.fetch),
1360
+ fetch: getFetchImplementation(options.fetch),
768
1361
  apiKey,
769
- trace
770
- });
771
- }
772
- get user() {
773
- if (!__privateGet$7(this, _namespaces).user)
774
- __privateGet$7(this, _namespaces).user = new UserApi(__privateGet$7(this, _extraProps));
775
- return __privateGet$7(this, _namespaces).user;
776
- }
777
- get workspaces() {
778
- if (!__privateGet$7(this, _namespaces).workspaces)
779
- __privateGet$7(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$7(this, _extraProps));
780
- return __privateGet$7(this, _namespaces).workspaces;
781
- }
782
- get databases() {
783
- if (!__privateGet$7(this, _namespaces).databases)
784
- __privateGet$7(this, _namespaces).databases = new DatabaseApi(__privateGet$7(this, _extraProps));
785
- return __privateGet$7(this, _namespaces).databases;
786
- }
787
- get branches() {
788
- if (!__privateGet$7(this, _namespaces).branches)
789
- __privateGet$7(this, _namespaces).branches = new BranchApi(__privateGet$7(this, _extraProps));
790
- return __privateGet$7(this, _namespaces).branches;
791
- }
792
- get tables() {
793
- if (!__privateGet$7(this, _namespaces).tables)
794
- __privateGet$7(this, _namespaces).tables = new TableApi(__privateGet$7(this, _extraProps));
795
- return __privateGet$7(this, _namespaces).tables;
796
- }
797
- get records() {
798
- if (!__privateGet$7(this, _namespaces).records)
799
- __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
800
- return __privateGet$7(this, _namespaces).records;
801
- }
802
- get migrationRequests() {
803
- if (!__privateGet$7(this, _namespaces).migrationRequests)
804
- __privateGet$7(this, _namespaces).migrationRequests = new MigrationRequestsApi(__privateGet$7(this, _extraProps));
805
- return __privateGet$7(this, _namespaces).migrationRequests;
806
- }
807
- get branchSchema() {
808
- if (!__privateGet$7(this, _namespaces).branchSchema)
809
- __privateGet$7(this, _namespaces).branchSchema = new BranchSchemaApi(__privateGet$7(this, _extraProps));
810
- return __privateGet$7(this, _namespaces).branchSchema;
811
- }
812
- }
813
- _extraProps = new WeakMap();
814
- _namespaces = new WeakMap();
815
- class UserApi {
816
- constructor(extraProps) {
817
- this.extraProps = extraProps;
818
- }
819
- getUser() {
820
- return operationsByTag.users.getUser({ ...this.extraProps });
821
- }
822
- updateUser(user) {
823
- return operationsByTag.users.updateUser({ body: user, ...this.extraProps });
824
- }
825
- deleteUser() {
826
- return operationsByTag.users.deleteUser({ ...this.extraProps });
827
- }
828
- getUserAPIKeys() {
829
- return operationsByTag.users.getUserAPIKeys({ ...this.extraProps });
830
- }
831
- createUserAPIKey(keyName) {
832
- return operationsByTag.users.createUserAPIKey({
833
- pathParams: { keyName },
834
- ...this.extraProps
835
- });
836
- }
837
- deleteUserAPIKey(keyName) {
838
- return operationsByTag.users.deleteUserAPIKey({
839
- pathParams: { keyName },
840
- ...this.extraProps
1362
+ trace,
1363
+ clientName: options.clientName,
1364
+ xataAgentExtra: options.xataAgentExtra,
1365
+ clientID
1366
+ };
1367
+ return new Proxy(this, {
1368
+ get: (_target, namespace) => {
1369
+ if (operationsByTag[namespace] === void 0) {
1370
+ return void 0;
1371
+ }
1372
+ return new Proxy(
1373
+ {},
1374
+ {
1375
+ get: (_target2, operation) => {
1376
+ if (operationsByTag[namespace][operation] === void 0) {
1377
+ return void 0;
1378
+ }
1379
+ const method = operationsByTag[namespace][operation];
1380
+ return async (params) => {
1381
+ return await method({ ...params, ...extraProps });
1382
+ };
1383
+ }
1384
+ }
1385
+ );
1386
+ }
841
1387
  });
842
1388
  }
1389
+ };
1390
+ class XataApiClient extends buildApiClient() {
843
1391
  }
844
- class WorkspaceApi {
845
- constructor(extraProps) {
846
- this.extraProps = extraProps;
847
- }
848
- createWorkspace(workspaceMeta) {
849
- return operationsByTag.workspaces.createWorkspace({
850
- body: workspaceMeta,
851
- ...this.extraProps
852
- });
853
- }
854
- getWorkspacesList() {
855
- return operationsByTag.workspaces.getWorkspacesList({ ...this.extraProps });
856
- }
857
- getWorkspace(workspaceId) {
858
- return operationsByTag.workspaces.getWorkspace({
859
- pathParams: { workspaceId },
860
- ...this.extraProps
861
- });
862
- }
863
- updateWorkspace(workspaceId, workspaceMeta) {
864
- return operationsByTag.workspaces.updateWorkspace({
865
- pathParams: { workspaceId },
866
- body: workspaceMeta,
867
- ...this.extraProps
868
- });
869
- }
870
- deleteWorkspace(workspaceId) {
871
- return operationsByTag.workspaces.deleteWorkspace({
872
- pathParams: { workspaceId },
873
- ...this.extraProps
874
- });
875
- }
876
- getWorkspaceMembersList(workspaceId) {
877
- return operationsByTag.workspaces.getWorkspaceMembersList({
878
- pathParams: { workspaceId },
879
- ...this.extraProps
880
- });
881
- }
882
- updateWorkspaceMemberRole(workspaceId, userId, role) {
883
- return operationsByTag.workspaces.updateWorkspaceMemberRole({
884
- pathParams: { workspaceId, userId },
885
- body: { role },
886
- ...this.extraProps
887
- });
888
- }
889
- removeWorkspaceMember(workspaceId, userId) {
890
- return operationsByTag.workspaces.removeWorkspaceMember({
891
- pathParams: { workspaceId, userId },
892
- ...this.extraProps
893
- });
894
- }
895
- inviteWorkspaceMember(workspaceId, email, role) {
896
- return operationsByTag.workspaces.inviteWorkspaceMember({
897
- pathParams: { workspaceId },
898
- body: { email, role },
899
- ...this.extraProps
900
- });
901
- }
902
- updateWorkspaceMemberInvite(workspaceId, inviteId, role) {
903
- return operationsByTag.workspaces.updateWorkspaceMemberInvite({
904
- pathParams: { workspaceId, inviteId },
905
- body: { role },
906
- ...this.extraProps
907
- });
908
- }
909
- cancelWorkspaceMemberInvite(workspaceId, inviteId) {
910
- return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
911
- pathParams: { workspaceId, inviteId },
912
- ...this.extraProps
913
- });
914
- }
915
- resendWorkspaceMemberInvite(workspaceId, inviteId) {
916
- return operationsByTag.workspaces.resendWorkspaceMemberInvite({
917
- pathParams: { workspaceId, inviteId },
918
- ...this.extraProps
919
- });
920
- }
921
- acceptWorkspaceMemberInvite(workspaceId, inviteKey) {
922
- return operationsByTag.workspaces.acceptWorkspaceMemberInvite({
923
- pathParams: { workspaceId, inviteKey },
924
- ...this.extraProps
925
- });
1392
+
1393
+ class XataApiPlugin {
1394
+ build(options) {
1395
+ return new XataApiClient(options);
926
1396
  }
927
1397
  }
928
- class DatabaseApi {
929
- constructor(extraProps) {
930
- this.extraProps = extraProps;
931
- }
932
- getDatabaseList(workspace) {
933
- return operationsByTag.database.getDatabaseList({
934
- pathParams: { workspace },
935
- ...this.extraProps
936
- });
937
- }
938
- createDatabase(workspace, dbName, options = {}) {
939
- return operationsByTag.database.createDatabase({
940
- pathParams: { workspace, dbName },
941
- body: options,
942
- ...this.extraProps
943
- });
944
- }
945
- deleteDatabase(workspace, dbName) {
946
- return operationsByTag.database.deleteDatabase({
947
- pathParams: { workspace, dbName },
948
- ...this.extraProps
949
- });
950
- }
951
- getDatabaseMetadata(workspace, dbName) {
952
- return operationsByTag.database.getDatabaseMetadata({
953
- pathParams: { workspace, dbName },
954
- ...this.extraProps
955
- });
956
- }
957
- updateDatabaseMetadata(workspace, dbName, options = {}) {
958
- return operationsByTag.database.updateDatabaseMetadata({
959
- pathParams: { workspace, dbName },
960
- body: options,
961
- ...this.extraProps
962
- });
963
- }
964
- getGitBranchesMapping(workspace, dbName) {
965
- return operationsByTag.database.getGitBranchesMapping({
966
- pathParams: { workspace, dbName },
967
- ...this.extraProps
968
- });
969
- }
970
- addGitBranchesEntry(workspace, dbName, body) {
971
- return operationsByTag.database.addGitBranchesEntry({
972
- pathParams: { workspace, dbName },
973
- body,
974
- ...this.extraProps
975
- });
976
- }
977
- removeGitBranchesEntry(workspace, dbName, gitBranch) {
978
- return operationsByTag.database.removeGitBranchesEntry({
979
- pathParams: { workspace, dbName },
980
- queryParams: { gitBranch },
981
- ...this.extraProps
982
- });
983
- }
984
- resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
985
- return operationsByTag.database.resolveBranch({
986
- pathParams: { workspace, dbName },
987
- queryParams: { gitBranch, fallbackBranch },
988
- ...this.extraProps
989
- });
990
- }
1398
+
1399
+ class XataPlugin {
991
1400
  }
992
- class BranchApi {
993
- constructor(extraProps) {
994
- this.extraProps = extraProps;
995
- }
996
- getBranchList(workspace, dbName) {
997
- return operationsByTag.branch.getBranchList({
998
- pathParams: { workspace, dbName },
999
- ...this.extraProps
1000
- });
1001
- }
1002
- getBranchDetails(workspace, database, branch) {
1003
- return operationsByTag.branch.getBranchDetails({
1004
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1005
- ...this.extraProps
1006
- });
1007
- }
1008
- createBranch(workspace, database, branch, from, options = {}) {
1009
- return operationsByTag.branch.createBranch({
1010
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1011
- queryParams: isString(from) ? { from } : void 0,
1012
- body: options,
1013
- ...this.extraProps
1014
- });
1015
- }
1016
- deleteBranch(workspace, database, branch) {
1017
- return operationsByTag.branch.deleteBranch({
1018
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1019
- ...this.extraProps
1020
- });
1021
- }
1022
- updateBranchMetadata(workspace, database, branch, metadata = {}) {
1023
- return operationsByTag.branch.updateBranchMetadata({
1024
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1025
- body: metadata,
1026
- ...this.extraProps
1027
- });
1028
- }
1029
- getBranchMetadata(workspace, database, branch) {
1030
- return operationsByTag.branch.getBranchMetadata({
1031
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1032
- ...this.extraProps
1033
- });
1034
- }
1035
- getBranchStats(workspace, database, branch) {
1036
- return operationsByTag.branch.getBranchStats({
1037
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1038
- ...this.extraProps
1039
- });
1040
- }
1401
+
1402
+ function buildTransformString(transformations) {
1403
+ return transformations.flatMap(
1404
+ (t) => Object.entries(t).map(([key, value]) => {
1405
+ if (key === "trim") {
1406
+ const { left = 0, top = 0, right = 0, bottom = 0 } = value;
1407
+ return `${key}=${[top, right, bottom, left].join(";")}`;
1408
+ }
1409
+ if (key === "gravity" && typeof value === "object") {
1410
+ const { x = 0.5, y = 0.5 } = value;
1411
+ return `${key}=${[x, y].join("x")}`;
1412
+ }
1413
+ return `${key}=${value}`;
1414
+ })
1415
+ ).join(",");
1041
1416
  }
1042
- class TableApi {
1043
- constructor(extraProps) {
1044
- this.extraProps = extraProps;
1045
- }
1046
- createTable(workspace, database, branch, tableName) {
1047
- return operationsByTag.table.createTable({
1048
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1049
- ...this.extraProps
1050
- });
1051
- }
1052
- deleteTable(workspace, database, branch, tableName) {
1053
- return operationsByTag.table.deleteTable({
1054
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1055
- ...this.extraProps
1056
- });
1057
- }
1058
- updateTable(workspace, database, branch, tableName, options) {
1059
- return operationsByTag.table.updateTable({
1060
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1061
- body: options,
1062
- ...this.extraProps
1063
- });
1064
- }
1065
- getTableSchema(workspace, database, branch, tableName) {
1066
- return operationsByTag.table.getTableSchema({
1067
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1068
- ...this.extraProps
1069
- });
1070
- }
1071
- setTableSchema(workspace, database, branch, tableName, options) {
1072
- return operationsByTag.table.setTableSchema({
1073
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1074
- body: options,
1075
- ...this.extraProps
1076
- });
1077
- }
1078
- getTableColumns(workspace, database, branch, tableName) {
1079
- return operationsByTag.table.getTableColumns({
1080
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1081
- ...this.extraProps
1082
- });
1083
- }
1084
- addTableColumn(workspace, database, branch, tableName, column) {
1085
- return operationsByTag.table.addTableColumn({
1086
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1087
- body: column,
1088
- ...this.extraProps
1089
- });
1090
- }
1091
- getColumn(workspace, database, branch, tableName, columnName) {
1092
- return operationsByTag.table.getColumn({
1093
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, columnName },
1094
- ...this.extraProps
1095
- });
1096
- }
1097
- deleteColumn(workspace, database, branch, tableName, columnName) {
1098
- return operationsByTag.table.deleteColumn({
1099
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, columnName },
1100
- ...this.extraProps
1101
- });
1102
- }
1103
- updateColumn(workspace, database, branch, tableName, columnName, options) {
1104
- return operationsByTag.table.updateColumn({
1105
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, columnName },
1106
- body: options,
1107
- ...this.extraProps
1108
- });
1109
- }
1417
+ function transformImage(url, ...transformations) {
1418
+ if (!isDefined(url))
1419
+ return void 0;
1420
+ const newTransformations = buildTransformString(transformations);
1421
+ const { hostname, pathname, search } = new URL(url);
1422
+ const pathParts = pathname.split("/");
1423
+ const transformIndex = pathParts.findIndex((part) => part === "transform");
1424
+ const removedItems = transformIndex >= 0 ? pathParts.splice(transformIndex, 2) : [];
1425
+ const transform = `/transform/${[removedItems[1], newTransformations].filter(isDefined).join(",")}`;
1426
+ const path = pathParts.join("/");
1427
+ return `https://${hostname}${transform}${path}${search}`;
1110
1428
  }
1111
- class RecordsApi {
1112
- constructor(extraProps) {
1113
- this.extraProps = extraProps;
1114
- }
1115
- insertRecord(workspace, database, branch, tableName, record, options = {}) {
1116
- return operationsByTag.records.insertRecord({
1117
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1118
- queryParams: options,
1119
- body: record,
1120
- ...this.extraProps
1121
- });
1122
- }
1123
- insertRecordWithID(workspace, database, branch, tableName, recordId, record, options = {}) {
1124
- return operationsByTag.records.insertRecordWithID({
1125
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1126
- queryParams: options,
1127
- body: record,
1128
- ...this.extraProps
1129
- });
1130
- }
1131
- updateRecordWithID(workspace, database, branch, tableName, recordId, record, options = {}) {
1132
- return operationsByTag.records.updateRecordWithID({
1133
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1134
- queryParams: options,
1135
- body: record,
1136
- ...this.extraProps
1137
- });
1138
- }
1139
- upsertRecordWithID(workspace, database, branch, tableName, recordId, record, options = {}) {
1140
- return operationsByTag.records.upsertRecordWithID({
1141
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1142
- queryParams: options,
1143
- body: record,
1144
- ...this.extraProps
1145
- });
1146
- }
1147
- deleteRecord(workspace, database, branch, tableName, recordId, options = {}) {
1148
- return operationsByTag.records.deleteRecord({
1149
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1150
- queryParams: options,
1151
- ...this.extraProps
1152
- });
1153
- }
1154
- getRecord(workspace, database, branch, tableName, recordId, options = {}) {
1155
- return operationsByTag.records.getRecord({
1156
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1157
- queryParams: options,
1158
- ...this.extraProps
1159
- });
1160
- }
1161
- bulkInsertTableRecords(workspace, database, branch, tableName, records, options = {}) {
1162
- return operationsByTag.records.bulkInsertTableRecords({
1163
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1164
- queryParams: options,
1165
- body: { records },
1166
- ...this.extraProps
1167
- });
1168
- }
1169
- queryTable(workspace, database, branch, tableName, query) {
1170
- return operationsByTag.records.queryTable({
1171
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1172
- body: query,
1173
- ...this.extraProps
1174
- });
1175
- }
1176
- searchTable(workspace, database, branch, tableName, query) {
1177
- return operationsByTag.records.searchTable({
1178
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1179
- body: query,
1180
- ...this.extraProps
1181
- });
1182
- }
1183
- searchBranch(workspace, database, branch, query) {
1184
- return operationsByTag.records.searchBranch({
1185
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1186
- body: query,
1187
- ...this.extraProps
1188
- });
1429
+
1430
+ class XataFile {
1431
+ constructor(file) {
1432
+ this.id = file.id;
1433
+ this.name = file.name;
1434
+ this.mediaType = file.mediaType;
1435
+ this.base64Content = file.base64Content;
1436
+ this.enablePublicUrl = file.enablePublicUrl;
1437
+ this.signedUrlTimeout = file.signedUrlTimeout;
1438
+ this.uploadUrlTimeout = file.uploadUrlTimeout;
1439
+ this.size = file.size;
1440
+ this.version = file.version;
1441
+ this.url = file.url;
1442
+ this.signedUrl = file.signedUrl;
1443
+ this.uploadUrl = file.uploadUrl;
1444
+ this.attributes = file.attributes;
1445
+ }
1446
+ static fromBuffer(buffer, options = {}) {
1447
+ const base64Content = buffer.toString("base64");
1448
+ return new XataFile({ ...options, base64Content });
1449
+ }
1450
+ toBuffer() {
1451
+ if (!this.base64Content) {
1452
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
1453
+ }
1454
+ return Buffer.from(this.base64Content, "base64");
1189
1455
  }
1190
- summarizeTable(workspace, database, branch, tableName, query) {
1191
- return operationsByTag.records.summarizeTable({
1192
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1193
- body: query,
1194
- ...this.extraProps
1195
- });
1456
+ static fromArrayBuffer(arrayBuffer, options = {}) {
1457
+ const uint8Array = new Uint8Array(arrayBuffer);
1458
+ return this.fromUint8Array(uint8Array, options);
1196
1459
  }
1197
- aggregateTable(workspace, database, branch, tableName, query) {
1198
- return operationsByTag.records.aggregateTable({
1199
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1200
- body: query,
1201
- ...this.extraProps
1202
- });
1460
+ toArrayBuffer() {
1461
+ if (!this.base64Content) {
1462
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
1463
+ }
1464
+ const binary = atob(this.base64Content);
1465
+ return new ArrayBuffer(binary.length);
1203
1466
  }
1204
- }
1205
- class MigrationRequestsApi {
1206
- constructor(extraProps) {
1207
- this.extraProps = extraProps;
1467
+ static fromUint8Array(uint8Array, options = {}) {
1468
+ let binary = "";
1469
+ for (let i = 0; i < uint8Array.byteLength; i++) {
1470
+ binary += String.fromCharCode(uint8Array[i]);
1471
+ }
1472
+ const base64Content = btoa(binary);
1473
+ return new XataFile({ ...options, base64Content });
1208
1474
  }
1209
- queryMigrationRequests(workspace, database, options = {}) {
1210
- return operationsByTag.migrationRequests.queryMigrationRequests({
1211
- pathParams: { workspace, dbName: database },
1212
- body: options,
1213
- ...this.extraProps
1214
- });
1475
+ toUint8Array() {
1476
+ if (!this.base64Content) {
1477
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
1478
+ }
1479
+ const binary = atob(this.base64Content);
1480
+ const uint8Array = new Uint8Array(binary.length);
1481
+ for (let i = 0; i < binary.length; i++) {
1482
+ uint8Array[i] = binary.charCodeAt(i);
1483
+ }
1484
+ return uint8Array;
1215
1485
  }
1216
- createMigrationRequest(workspace, database, options) {
1217
- return operationsByTag.migrationRequests.createMigrationRequest({
1218
- pathParams: { workspace, dbName: database },
1219
- body: options,
1220
- ...this.extraProps
1221
- });
1486
+ static async fromBlob(file, options = {}) {
1487
+ const name = options.name ?? file.name;
1488
+ const mediaType = file.type;
1489
+ const arrayBuffer = await file.arrayBuffer();
1490
+ return this.fromArrayBuffer(arrayBuffer, { ...options, name, mediaType });
1222
1491
  }
1223
- getMigrationRequest(workspace, database, migrationRequest) {
1224
- return operationsByTag.migrationRequests.getMigrationRequest({
1225
- pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1226
- ...this.extraProps
1227
- });
1492
+ toBlob() {
1493
+ if (!this.base64Content) {
1494
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
1495
+ }
1496
+ const binary = atob(this.base64Content);
1497
+ const uint8Array = new Uint8Array(binary.length);
1498
+ for (let i = 0; i < binary.length; i++) {
1499
+ uint8Array[i] = binary.charCodeAt(i);
1500
+ }
1501
+ return new Blob([uint8Array], { type: this.mediaType });
1228
1502
  }
1229
- updateMigrationRequest(workspace, database, migrationRequest, options) {
1230
- return operationsByTag.migrationRequests.updateMigrationRequest({
1231
- pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1232
- body: options,
1233
- ...this.extraProps
1234
- });
1503
+ static fromString(string, options = {}) {
1504
+ const base64Content = btoa(string);
1505
+ return new XataFile({ ...options, base64Content });
1235
1506
  }
1236
- listMigrationRequestsCommits(workspace, database, migrationRequest, options = {}) {
1237
- return operationsByTag.migrationRequests.listMigrationRequestsCommits({
1238
- pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1239
- body: options,
1240
- ...this.extraProps
1241
- });
1507
+ toString() {
1508
+ if (!this.base64Content) {
1509
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
1510
+ }
1511
+ return atob(this.base64Content);
1242
1512
  }
1243
- compareMigrationRequest(workspace, database, migrationRequest) {
1244
- return operationsByTag.migrationRequests.compareMigrationRequest({
1245
- pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1246
- ...this.extraProps
1247
- });
1513
+ static fromBase64(base64Content, options = {}) {
1514
+ return new XataFile({ ...options, base64Content });
1248
1515
  }
1249
- getMigrationRequestIsMerged(workspace, database, migrationRequest) {
1250
- return operationsByTag.migrationRequests.getMigrationRequestIsMerged({
1251
- pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1252
- ...this.extraProps
1253
- });
1516
+ toBase64() {
1517
+ if (!this.base64Content) {
1518
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
1519
+ }
1520
+ return this.base64Content;
1254
1521
  }
1255
- mergeMigrationRequest(workspace, database, migrationRequest) {
1256
- return operationsByTag.migrationRequests.mergeMigrationRequest({
1257
- pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1258
- ...this.extraProps
1259
- });
1522
+ transform(...options) {
1523
+ return {
1524
+ url: transformImage(this.url, ...options),
1525
+ signedUrl: transformImage(this.signedUrl, ...options),
1526
+ metadataUrl: transformImage(this.url, ...options, { format: "json" }),
1527
+ metadataSignedUrl: transformImage(this.signedUrl, ...options, { format: "json" })
1528
+ };
1260
1529
  }
1261
1530
  }
1262
- class BranchSchemaApi {
1263
- constructor(extraProps) {
1264
- this.extraProps = extraProps;
1265
- }
1266
- getBranchMigrationHistory(workspace, database, branch, options = {}) {
1267
- return operationsByTag.branchSchema.getBranchMigrationHistory({
1268
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1269
- body: options,
1270
- ...this.extraProps
1271
- });
1272
- }
1273
- executeBranchMigrationPlan(workspace, database, branch, migrationPlan) {
1274
- return operationsByTag.branchSchema.executeBranchMigrationPlan({
1275
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1276
- body: migrationPlan,
1277
- ...this.extraProps
1278
- });
1279
- }
1280
- getBranchMigrationPlan(workspace, database, branch, schema) {
1281
- return operationsByTag.branchSchema.getBranchMigrationPlan({
1282
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1283
- body: schema,
1284
- ...this.extraProps
1285
- });
1286
- }
1287
- compareBranchWithUserSchema(workspace, database, branch, schema) {
1288
- return operationsByTag.branchSchema.compareBranchWithUserSchema({
1289
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1290
- body: { schema },
1291
- ...this.extraProps
1292
- });
1293
- }
1294
- compareBranchSchemas(workspace, database, branch, branchName, schema) {
1295
- return operationsByTag.branchSchema.compareBranchSchemas({
1296
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, branchName },
1297
- body: { schema },
1298
- ...this.extraProps
1299
- });
1300
- }
1301
- updateBranchSchema(workspace, database, branch, migration) {
1302
- return operationsByTag.branchSchema.updateBranchSchema({
1303
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1304
- body: migration,
1305
- ...this.extraProps
1306
- });
1307
- }
1308
- previewBranchSchemaEdit(workspace, database, branch, migration) {
1309
- return operationsByTag.branchSchema.previewBranchSchemaEdit({
1310
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1311
- body: migration,
1312
- ...this.extraProps
1313
- });
1314
- }
1315
- applyBranchSchemaEdit(workspace, database, branch, edits) {
1316
- return operationsByTag.branchSchema.applyBranchSchemaEdit({
1317
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1318
- body: { edits },
1319
- ...this.extraProps
1320
- });
1321
- }
1322
- getBranchSchemaHistory(workspace, database, branch, options = {}) {
1323
- return operationsByTag.branchSchema.getBranchSchemaHistory({
1324
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1325
- body: options,
1326
- ...this.extraProps
1327
- });
1328
- }
1531
+ const parseInputFileEntry = async (entry) => {
1532
+ if (!isDefined(entry))
1533
+ return null;
1534
+ const { id, name, mediaType, base64Content, enablePublicUrl, signedUrlTimeout, uploadUrlTimeout } = await entry;
1535
+ return compactObject({
1536
+ id,
1537
+ // Name cannot be an empty string in our API
1538
+ name: name ? name : void 0,
1539
+ mediaType,
1540
+ base64Content,
1541
+ enablePublicUrl,
1542
+ signedUrlTimeout,
1543
+ uploadUrlTimeout
1544
+ });
1545
+ };
1546
+
1547
+ function cleanFilter(filter) {
1548
+ if (!isDefined(filter))
1549
+ return void 0;
1550
+ if (!isObject(filter))
1551
+ return filter;
1552
+ const values = Object.fromEntries(
1553
+ Object.entries(filter).reduce((acc, [key, value]) => {
1554
+ if (!isDefined(value))
1555
+ return acc;
1556
+ if (Array.isArray(value)) {
1557
+ const clean = value.map((item) => cleanFilter(item)).filter((item) => isDefined(item));
1558
+ if (clean.length === 0)
1559
+ return acc;
1560
+ return [...acc, [key, clean]];
1561
+ }
1562
+ if (isObject(value)) {
1563
+ const clean = cleanFilter(value);
1564
+ if (!isDefined(clean))
1565
+ return acc;
1566
+ return [...acc, [key, clean]];
1567
+ }
1568
+ return [...acc, [key, value]];
1569
+ }, [])
1570
+ );
1571
+ return Object.keys(values).length > 0 ? values : void 0;
1329
1572
  }
1330
1573
 
1331
- class XataApiPlugin {
1332
- async build(options) {
1333
- const { fetchImpl, apiKey } = await options.getFetchProps();
1334
- return new XataApiClient({ fetch: fetchImpl, apiKey });
1574
+ function stringifyJson(value) {
1575
+ if (!isDefined(value))
1576
+ return value;
1577
+ if (isString(value))
1578
+ return value;
1579
+ try {
1580
+ return JSON.stringify(value);
1581
+ } catch (e) {
1582
+ return value;
1335
1583
  }
1336
1584
  }
1337
-
1338
- class XataPlugin {
1585
+ function parseJson(value) {
1586
+ try {
1587
+ return JSON.parse(value);
1588
+ } catch (e) {
1589
+ return value;
1590
+ }
1339
1591
  }
1340
1592
 
1341
1593
  var __accessCheck$6 = (obj, member, msg) => {
@@ -1364,31 +1616,59 @@ class Page {
1364
1616
  this.meta = meta;
1365
1617
  this.records = new RecordArray(this, records);
1366
1618
  }
1619
+ /**
1620
+ * Retrieves the next page of results.
1621
+ * @param size Maximum number of results to be retrieved.
1622
+ * @param offset Number of results to skip when retrieving the results.
1623
+ * @returns The next page or results.
1624
+ */
1367
1625
  async nextPage(size, offset) {
1368
1626
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
1369
1627
  }
1628
+ /**
1629
+ * Retrieves the previous page of results.
1630
+ * @param size Maximum number of results to be retrieved.
1631
+ * @param offset Number of results to skip when retrieving the results.
1632
+ * @returns The previous page or results.
1633
+ */
1370
1634
  async previousPage(size, offset) {
1371
1635
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
1372
1636
  }
1373
- async firstPage(size, offset) {
1374
- return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
1375
- }
1376
- async lastPage(size, offset) {
1377
- return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
1378
- }
1637
+ /**
1638
+ * Retrieves the start page of results.
1639
+ * @param size Maximum number of results to be retrieved.
1640
+ * @param offset Number of results to skip when retrieving the results.
1641
+ * @returns The start page or results.
1642
+ */
1643
+ async startPage(size, offset) {
1644
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, start: this.meta.page.cursor } });
1645
+ }
1646
+ /**
1647
+ * Retrieves the end page of results.
1648
+ * @param size Maximum number of results to be retrieved.
1649
+ * @param offset Number of results to skip when retrieving the results.
1650
+ * @returns The end page or results.
1651
+ */
1652
+ async endPage(size, offset) {
1653
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, end: this.meta.page.cursor } });
1654
+ }
1655
+ /**
1656
+ * Shortcut method to check if there will be additional results if the next page of results is retrieved.
1657
+ * @returns Whether or not there will be additional results in the next page of results.
1658
+ */
1379
1659
  hasNextPage() {
1380
1660
  return this.meta.page.more;
1381
1661
  }
1382
1662
  }
1383
1663
  _query = new WeakMap();
1384
- const PAGINATION_MAX_SIZE = 200;
1664
+ const PAGINATION_MAX_SIZE = 1e3;
1385
1665
  const PAGINATION_DEFAULT_SIZE = 20;
1386
- const PAGINATION_MAX_OFFSET = 800;
1666
+ const PAGINATION_MAX_OFFSET = 49e3;
1387
1667
  const PAGINATION_DEFAULT_OFFSET = 0;
1388
1668
  function isCursorPaginationOptions(options) {
1389
- return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
1669
+ return isDefined(options) && (isDefined(options.start) || isDefined(options.end) || isDefined(options.after) || isDefined(options.before));
1390
1670
  }
1391
- const _RecordArray = class extends Array {
1671
+ const _RecordArray = class _RecordArray extends Array {
1392
1672
  constructor(...args) {
1393
1673
  super(..._RecordArray.parseConstructorParams(...args));
1394
1674
  __privateAdd$6(this, _page, void 0);
@@ -1407,31 +1687,60 @@ const _RecordArray = class extends Array {
1407
1687
  toArray() {
1408
1688
  return new Array(...this);
1409
1689
  }
1690
+ toSerializable() {
1691
+ return JSON.parse(this.toString());
1692
+ }
1693
+ toString() {
1694
+ return JSON.stringify(this.toArray());
1695
+ }
1410
1696
  map(callbackfn, thisArg) {
1411
1697
  return this.toArray().map(callbackfn, thisArg);
1412
1698
  }
1699
+ /**
1700
+ * Retrieve next page of records
1701
+ *
1702
+ * @returns A new array of objects
1703
+ */
1413
1704
  async nextPage(size, offset) {
1414
1705
  const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1415
1706
  return new _RecordArray(newPage);
1416
1707
  }
1708
+ /**
1709
+ * Retrieve previous page of records
1710
+ *
1711
+ * @returns A new array of objects
1712
+ */
1417
1713
  async previousPage(size, offset) {
1418
1714
  const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1419
1715
  return new _RecordArray(newPage);
1420
1716
  }
1421
- async firstPage(size, offset) {
1422
- const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1717
+ /**
1718
+ * Retrieve start page of records
1719
+ *
1720
+ * @returns A new array of objects
1721
+ */
1722
+ async startPage(size, offset) {
1723
+ const newPage = await __privateGet$6(this, _page).startPage(size, offset);
1423
1724
  return new _RecordArray(newPage);
1424
1725
  }
1425
- async lastPage(size, offset) {
1426
- const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1726
+ /**
1727
+ * Retrieve end page of records
1728
+ *
1729
+ * @returns A new array of objects
1730
+ */
1731
+ async endPage(size, offset) {
1732
+ const newPage = await __privateGet$6(this, _page).endPage(size, offset);
1427
1733
  return new _RecordArray(newPage);
1428
1734
  }
1735
+ /**
1736
+ * @returns Boolean indicating if there is a next page
1737
+ */
1429
1738
  hasNextPage() {
1430
1739
  return __privateGet$6(this, _page).meta.page.more;
1431
1740
  }
1432
1741
  };
1433
- let RecordArray = _RecordArray;
1434
1742
  _page = new WeakMap();
1743
+ let RecordArray = _RecordArray;
1435
1744
 
1436
1745
  var __accessCheck$5 = (obj, member, msg) => {
1437
1746
  if (!member.has(obj))
@@ -1456,13 +1765,14 @@ var __privateMethod$3 = (obj, member, method) => {
1456
1765
  return method;
1457
1766
  };
1458
1767
  var _table$1, _repository, _data, _cleanFilterConstraint, cleanFilterConstraint_fn;
1459
- const _Query = class {
1768
+ const _Query = class _Query {
1460
1769
  constructor(repository, table, data, rawParent) {
1461
1770
  __privateAdd$5(this, _cleanFilterConstraint);
1462
1771
  __privateAdd$5(this, _table$1, void 0);
1463
1772
  __privateAdd$5(this, _repository, void 0);
1464
1773
  __privateAdd$5(this, _data, { filter: {} });
1465
- this.meta = { page: { cursor: "start", more: true } };
1774
+ // Implements pagination
1775
+ this.meta = { page: { cursor: "start", more: true, size: PAGINATION_DEFAULT_SIZE } };
1466
1776
  this.records = new RecordArray(this, []);
1467
1777
  __privateSet$5(this, _table$1, table);
1468
1778
  if (repository) {
@@ -1477,9 +1787,11 @@ const _Query = class {
1477
1787
  __privateGet$5(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
1478
1788
  __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1479
1789
  __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1480
- __privateGet$5(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
1790
+ __privateGet$5(this, _data).columns = data.columns ?? parent?.columns;
1791
+ __privateGet$5(this, _data).consistency = data.consistency ?? parent?.consistency;
1481
1792
  __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1482
1793
  __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
1794
+ __privateGet$5(this, _data).fetchOptions = data.fetchOptions ?? parent?.fetchOptions;
1483
1795
  this.any = this.any.bind(this);
1484
1796
  this.all = this.all.bind(this);
1485
1797
  this.not = this.not.bind(this);
@@ -1497,18 +1809,38 @@ const _Query = class {
1497
1809
  const key = JSON.stringify({ columns, filter, sort, pagination });
1498
1810
  return toBase64(key);
1499
1811
  }
1812
+ /**
1813
+ * Builds a new query object representing a logical OR between the given subqueries.
1814
+ * @param queries An array of subqueries.
1815
+ * @returns A new Query object.
1816
+ */
1500
1817
  any(...queries) {
1501
1818
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
1502
1819
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
1503
1820
  }
1821
+ /**
1822
+ * Builds a new query object representing a logical AND between the given subqueries.
1823
+ * @param queries An array of subqueries.
1824
+ * @returns A new Query object.
1825
+ */
1504
1826
  all(...queries) {
1505
1827
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
1506
1828
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1507
1829
  }
1830
+ /**
1831
+ * Builds a new query object representing a logical OR negating each subquery. In pseudo-code: !q1 OR !q2
1832
+ * @param queries An array of subqueries.
1833
+ * @returns A new Query object.
1834
+ */
1508
1835
  not(...queries) {
1509
1836
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
1510
1837
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
1511
1838
  }
1839
+ /**
1840
+ * Builds a new query object representing a logical AND negating each subquery. In pseudo-code: !q1 AND !q2
1841
+ * @param queries An array of subqueries.
1842
+ * @returns A new Query object.
1843
+ */
1512
1844
  none(...queries) {
1513
1845
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
1514
1846
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
@@ -1531,6 +1863,11 @@ const _Query = class {
1531
1863
  const sort = [...originalSort, { column, direction }];
1532
1864
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
1533
1865
  }
1866
+ /**
1867
+ * Builds a new query specifying the set of columns to be returned in the query response.
1868
+ * @param columns Array of column names to be returned by the query.
1869
+ * @returns A new Query object.
1870
+ */
1534
1871
  select(columns) {
1535
1872
  return new _Query(
1536
1873
  __privateGet$5(this, _repository),
@@ -1543,6 +1880,12 @@ const _Query = class {
1543
1880
  const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
1544
1881
  return __privateGet$5(this, _repository).query(query);
1545
1882
  }
1883
+ /**
1884
+ * Get results in an iterator
1885
+ *
1886
+ * @async
1887
+ * @returns Async interable of results
1888
+ */
1546
1889
  async *[Symbol.asyncIterator]() {
1547
1890
  for await (const [record] of this.getIterator({ batchSize: 1 })) {
1548
1891
  yield record;
@@ -1593,26 +1936,63 @@ const _Query = class {
1593
1936
  throw new Error("No results found.");
1594
1937
  return records[0];
1595
1938
  }
1939
+ async summarize(params = {}) {
1940
+ const { summaries, summariesFilter, ...options } = params;
1941
+ const query = new _Query(
1942
+ __privateGet$5(this, _repository),
1943
+ __privateGet$5(this, _table$1),
1944
+ options,
1945
+ __privateGet$5(this, _data)
1946
+ );
1947
+ return __privateGet$5(this, _repository).summarizeTable(query, summaries, summariesFilter);
1948
+ }
1949
+ /**
1950
+ * Builds a new query object adding a cache TTL in milliseconds.
1951
+ * @param ttl The cache TTL in milliseconds.
1952
+ * @returns A new Query object.
1953
+ */
1596
1954
  cache(ttl) {
1597
1955
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1598
1956
  }
1957
+ /**
1958
+ * Retrieve next page of records
1959
+ *
1960
+ * @returns A new page object.
1961
+ */
1599
1962
  nextPage(size, offset) {
1600
- return this.firstPage(size, offset);
1963
+ return this.startPage(size, offset);
1601
1964
  }
1965
+ /**
1966
+ * Retrieve previous page of records
1967
+ *
1968
+ * @returns A new page object
1969
+ */
1602
1970
  previousPage(size, offset) {
1603
- return this.firstPage(size, offset);
1604
- }
1605
- firstPage(size, offset) {
1971
+ return this.startPage(size, offset);
1972
+ }
1973
+ /**
1974
+ * Retrieve start page of records
1975
+ *
1976
+ * @returns A new page object
1977
+ */
1978
+ startPage(size, offset) {
1606
1979
  return this.getPaginated({ pagination: { size, offset } });
1607
1980
  }
1608
- lastPage(size, offset) {
1981
+ /**
1982
+ * Retrieve last page of records
1983
+ *
1984
+ * @returns A new page object
1985
+ */
1986
+ endPage(size, offset) {
1609
1987
  return this.getPaginated({ pagination: { size, offset, before: "end" } });
1610
1988
  }
1989
+ /**
1990
+ * @returns Boolean indicating if there is a next page
1991
+ */
1611
1992
  hasNextPage() {
1612
1993
  return this.meta.page.more;
1613
1994
  }
1614
1995
  };
1615
- let Query = _Query;
1616
1996
  _table$1 = new WeakMap();
1617
1997
  _repository = new WeakMap();
1618
1998
  _data = new WeakMap();
@@ -1627,13 +2007,29 @@ cleanFilterConstraint_fn = function(column, value) {
1627
2007
  }
1628
2008
  return value;
1629
2009
  };
2010
+ let Query = _Query;
1630
2011
  function cleanParent(data, parent) {
1631
2012
  if (isCursorPaginationOptions(data.pagination)) {
1632
- return { ...parent, sorting: void 0, filter: void 0 };
2013
+ return { ...parent, sort: void 0, filter: void 0 };
1633
2014
  }
1634
2015
  return parent;
1635
2016
  }
1636
2017
 
2018
+ const RecordColumnTypes = [
2019
+ "bool",
2020
+ "int",
2021
+ "float",
2022
+ "string",
2023
+ "text",
2024
+ "email",
2025
+ "multiple",
2026
+ "link",
2027
+ "datetime",
2028
+ "vector",
2029
+ "file[]",
2030
+ "file",
2031
+ "json"
2032
+ ];
1637
2033
  function isIdentifiable(x) {
1638
2034
  return isObject(x) && isString(x?.id);
1639
2035
  }
@@ -1643,11 +2039,33 @@ function isXataRecord(x) {
1643
2039
  return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1644
2040
  }
1645
2041
 
2042
+ function isValidExpandedColumn(column) {
2043
+ return isObject(column) && isString(column.name);
2044
+ }
2045
+ function isValidSelectableColumns(columns) {
2046
+ if (!Array.isArray(columns)) {
2047
+ return false;
2048
+ }
2049
+ return columns.every((column) => {
2050
+ if (typeof column === "string") {
2051
+ return true;
2052
+ }
2053
+ if (typeof column === "object") {
2054
+ return isValidExpandedColumn(column);
2055
+ }
2056
+ return false;
2057
+ });
2058
+ }
2059
+
1646
2060
  function isSortFilterString(value) {
1647
2061
  return isString(value);
1648
2062
  }
1649
2063
  function isSortFilterBase(filter) {
1650
- return isObject(filter) && Object.values(filter).every((value) => value === "asc" || value === "desc");
2064
+ return isObject(filter) && Object.entries(filter).every(([key, value]) => {
2065
+ if (key === "*")
2066
+ return value === "random";
2067
+ return value === "asc" || value === "desc";
2068
+ });
1651
2069
  }
1652
2070
  function isSortFilterObject(filter) {
1653
2071
  return isObject(filter) && !isSortFilterBase(filter) && filter.column !== void 0;
@@ -1688,7 +2106,8 @@ var __privateMethod$2 = (obj, member, method) => {
1688
2106
  __accessCheck$4(obj, member, "access private method");
1689
2107
  return method;
1690
2108
  };
1691
- 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;
2109
+ 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;
2110
+ const BULK_OPERATION_MAX_SIZE = 1e3;
1692
2111
  class Repository extends Query {
1693
2112
  }
1694
2113
  class RestRepository extends Query {
@@ -1700,13 +2119,16 @@ class RestRepository extends Query {
1700
2119
  );
1701
2120
  __privateAdd$4(this, _insertRecordWithoutId);
1702
2121
  __privateAdd$4(this, _insertRecordWithId);
1703
- __privateAdd$4(this, _bulkInsertTableRecords);
2122
+ __privateAdd$4(this, _insertRecords);
1704
2123
  __privateAdd$4(this, _updateRecordWithID);
2124
+ __privateAdd$4(this, _updateRecords);
1705
2125
  __privateAdd$4(this, _upsertRecordWithID);
1706
2126
  __privateAdd$4(this, _deleteRecord);
2127
+ __privateAdd$4(this, _deleteRecords);
1707
2128
  __privateAdd$4(this, _setCacheQuery);
1708
2129
  __privateAdd$4(this, _getCacheQuery);
1709
2130
  __privateAdd$4(this, _getSchemaTables$1);
2131
+ __privateAdd$4(this, _transformObjectToApi);
1710
2132
  __privateAdd$4(this, _table, void 0);
1711
2133
  __privateAdd$4(this, _getFetchProps, void 0);
1712
2134
  __privateAdd$4(this, _db, void 0);
@@ -1714,10 +2136,10 @@ class RestRepository extends Query {
1714
2136
  __privateAdd$4(this, _schemaTables$2, void 0);
1715
2137
  __privateAdd$4(this, _trace, void 0);
1716
2138
  __privateSet$4(this, _table, options.table);
1717
- __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1718
2139
  __privateSet$4(this, _db, options.db);
1719
2140
  __privateSet$4(this, _cache, options.pluginOptions.cache);
1720
2141
  __privateSet$4(this, _schemaTables$2, options.schemaTables);
2142
+ __privateSet$4(this, _getFetchProps, () => ({ ...options.pluginOptions, sessionID: generateUUID() }));
1721
2143
  const trace = options.pluginOptions.trace ?? defaultTrace;
1722
2144
  __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
1723
2145
  return trace(name, fn, {
@@ -1728,28 +2150,31 @@ class RestRepository extends Query {
1728
2150
  });
1729
2151
  });
1730
2152
  }
1731
- async create(a, b, c) {
2153
+ async create(a, b, c, d) {
1732
2154
  return __privateGet$4(this, _trace).call(this, "create", async () => {
2155
+ const ifVersion = parseIfVersion(b, c, d);
1733
2156
  if (Array.isArray(a)) {
1734
2157
  if (a.length === 0)
1735
2158
  return [];
1736
- const columns = isStringArray(b) ? b : void 0;
1737
- return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
2159
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: true });
2160
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2161
+ const result = await this.read(ids, columns);
2162
+ return result;
1738
2163
  }
1739
2164
  if (isString(a) && isObject(b)) {
1740
2165
  if (a === "")
1741
2166
  throw new Error("The id can't be empty");
1742
- const columns = isStringArray(c) ? c : void 0;
1743
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns);
2167
+ const columns = isValidSelectableColumns(c) ? c : void 0;
2168
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
1744
2169
  }
1745
2170
  if (isObject(a) && isString(a.id)) {
1746
2171
  if (a.id === "")
1747
2172
  throw new Error("The id can't be empty");
1748
- const columns = isStringArray(b) ? b : void 0;
1749
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns);
2173
+ const columns = isValidSelectableColumns(b) ? b : void 0;
2174
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
1750
2175
  }
1751
2176
  if (isObject(a)) {
1752
- const columns = isStringArray(b) ? b : void 0;
2177
+ const columns = isValidSelectableColumns(b) ? b : void 0;
1753
2178
  return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
1754
2179
  }
1755
2180
  throw new Error("Invalid arguments for create method");
@@ -1757,7 +2182,7 @@ class RestRepository extends Query {
1757
2182
  }
1758
2183
  async read(a, b) {
1759
2184
  return __privateGet$4(this, _trace).call(this, "read", async () => {
1760
- const columns = isStringArray(b) ? b : ["*"];
2185
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
1761
2186
  if (Array.isArray(a)) {
1762
2187
  if (a.length === 0)
1763
2188
  return [];
@@ -1771,20 +2196,26 @@ class RestRepository extends Query {
1771
2196
  }
1772
2197
  const id = extractId(a);
1773
2198
  if (id) {
1774
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1775
2199
  try {
1776
2200
  const response = await getRecord({
1777
2201
  pathParams: {
1778
2202
  workspace: "{workspaceId}",
1779
2203
  dbBranchName: "{dbBranch}",
2204
+ region: "{region}",
1780
2205
  tableName: __privateGet$4(this, _table),
1781
2206
  recordId: id
1782
2207
  },
1783
2208
  queryParams: { columns },
1784
- ...fetchProps
2209
+ ...__privateGet$4(this, _getFetchProps).call(this)
1785
2210
  });
1786
2211
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1787
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2212
+ return initObject(
2213
+ __privateGet$4(this, _db),
2214
+ schemaTables,
2215
+ __privateGet$4(this, _table),
2216
+ response,
2217
+ columns
2218
+ );
1788
2219
  } catch (e) {
1789
2220
  if (isObject(e) && e.status === 404) {
1790
2221
  return null;
@@ -1814,31 +2245,42 @@ class RestRepository extends Query {
1814
2245
  return result;
1815
2246
  });
1816
2247
  }
1817
- async update(a, b, c) {
2248
+ async update(a, b, c, d) {
1818
2249
  return __privateGet$4(this, _trace).call(this, "update", async () => {
2250
+ const ifVersion = parseIfVersion(b, c, d);
1819
2251
  if (Array.isArray(a)) {
1820
2252
  if (a.length === 0)
1821
2253
  return [];
1822
- if (a.length > 100) {
1823
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1824
- }
1825
- const columns = isStringArray(b) ? b : ["*"];
1826
- return Promise.all(a.map((object) => this.update(object, columns)));
1827
- }
1828
- if (isString(a) && isObject(b)) {
1829
- const columns = isStringArray(c) ? c : void 0;
1830
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns);
2254
+ const existing = await this.read(a, ["id"]);
2255
+ const updates = a.filter((_item, index) => existing[index] !== null);
2256
+ await __privateMethod$2(this, _updateRecords, updateRecords_fn).call(this, updates, {
2257
+ ifVersion,
2258
+ upsert: false
2259
+ });
2260
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2261
+ const result = await this.read(a, columns);
2262
+ return result;
1831
2263
  }
1832
- if (isObject(a) && isString(a.id)) {
1833
- const columns = isStringArray(b) ? b : void 0;
1834
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
2264
+ try {
2265
+ if (isString(a) && isObject(b)) {
2266
+ const columns = isValidSelectableColumns(c) ? c : void 0;
2267
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2268
+ }
2269
+ if (isObject(a) && isString(a.id)) {
2270
+ const columns = isValidSelectableColumns(b) ? b : void 0;
2271
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
2272
+ }
2273
+ } catch (error) {
2274
+ if (error.status === 422)
2275
+ return null;
2276
+ throw error;
1835
2277
  }
1836
2278
  throw new Error("Invalid arguments for update method");
1837
2279
  });
1838
2280
  }
1839
- async updateOrThrow(a, b, c) {
2281
+ async updateOrThrow(a, b, c, d) {
1840
2282
  return __privateGet$4(this, _trace).call(this, "updateOrThrow", async () => {
1841
- const result = await this.update(a, b, c);
2283
+ const result = await this.update(a, b, c, d);
1842
2284
  if (Array.isArray(result)) {
1843
2285
  const missingIds = compact(
1844
2286
  a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
@@ -1855,37 +2297,89 @@ class RestRepository extends Query {
1855
2297
  return result;
1856
2298
  });
1857
2299
  }
1858
- async createOrUpdate(a, b, c) {
2300
+ async createOrUpdate(a, b, c, d) {
1859
2301
  return __privateGet$4(this, _trace).call(this, "createOrUpdate", async () => {
2302
+ const ifVersion = parseIfVersion(b, c, d);
1860
2303
  if (Array.isArray(a)) {
1861
2304
  if (a.length === 0)
1862
2305
  return [];
1863
- if (a.length > 100) {
1864
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1865
- }
1866
- const columns = isStringArray(b) ? b : ["*"];
1867
- return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
2306
+ await __privateMethod$2(this, _updateRecords, updateRecords_fn).call(this, a, {
2307
+ ifVersion,
2308
+ upsert: true
2309
+ });
2310
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2311
+ const result = await this.read(a, columns);
2312
+ return result;
1868
2313
  }
1869
2314
  if (isString(a) && isObject(b)) {
1870
- const columns = isStringArray(c) ? c : void 0;
1871
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns);
2315
+ if (a === "")
2316
+ throw new Error("The id can't be empty");
2317
+ const columns = isValidSelectableColumns(c) ? c : void 0;
2318
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
1872
2319
  }
1873
2320
  if (isObject(a) && isString(a.id)) {
1874
- const columns = isStringArray(c) ? c : void 0;
1875
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
2321
+ if (a.id === "")
2322
+ throw new Error("The id can't be empty");
2323
+ const columns = isValidSelectableColumns(c) ? c : void 0;
2324
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
2325
+ }
2326
+ if (!isDefined(a) && isObject(b)) {
2327
+ return await this.create(b, c);
2328
+ }
2329
+ if (isObject(a) && !isDefined(a.id)) {
2330
+ return await this.create(a, b);
1876
2331
  }
1877
2332
  throw new Error("Invalid arguments for createOrUpdate method");
1878
2333
  });
1879
2334
  }
2335
+ async createOrReplace(a, b, c, d) {
2336
+ return __privateGet$4(this, _trace).call(this, "createOrReplace", async () => {
2337
+ const ifVersion = parseIfVersion(b, c, d);
2338
+ if (Array.isArray(a)) {
2339
+ if (a.length === 0)
2340
+ return [];
2341
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: false });
2342
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2343
+ const result = await this.read(ids, columns);
2344
+ return result;
2345
+ }
2346
+ if (isString(a) && isObject(b)) {
2347
+ if (a === "")
2348
+ throw new Error("The id can't be empty");
2349
+ const columns = isValidSelectableColumns(c) ? c : void 0;
2350
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
2351
+ }
2352
+ if (isObject(a) && isString(a.id)) {
2353
+ if (a.id === "")
2354
+ throw new Error("The id can't be empty");
2355
+ const columns = isValidSelectableColumns(c) ? c : void 0;
2356
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
2357
+ }
2358
+ if (!isDefined(a) && isObject(b)) {
2359
+ return await this.create(b, c);
2360
+ }
2361
+ if (isObject(a) && !isDefined(a.id)) {
2362
+ return await this.create(a, b);
2363
+ }
2364
+ throw new Error("Invalid arguments for createOrReplace method");
2365
+ });
2366
+ }
1880
2367
  async delete(a, b) {
1881
2368
  return __privateGet$4(this, _trace).call(this, "delete", async () => {
1882
2369
  if (Array.isArray(a)) {
1883
2370
  if (a.length === 0)
1884
2371
  return [];
1885
- if (a.length > 100) {
1886
- console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1887
- }
1888
- return Promise.all(a.map((id) => this.delete(id, b)));
2372
+ const ids = a.map((o) => {
2373
+ if (isString(o))
2374
+ return o;
2375
+ if (isString(o.id))
2376
+ return o.id;
2377
+ throw new Error("Invalid arguments for delete method");
2378
+ });
2379
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2380
+ const result = await this.read(a, columns);
2381
+ await __privateMethod$2(this, _deleteRecords, deleteRecords_fn).call(this, ids);
2382
+ return result;
1889
2383
  }
1890
2384
  if (isString(a)) {
1891
2385
  return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
@@ -1916,30 +2410,68 @@ class RestRepository extends Query {
1916
2410
  }
1917
2411
  async search(query, options = {}) {
1918
2412
  return __privateGet$4(this, _trace).call(this, "search", async () => {
1919
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1920
- const { records } = await searchTable({
1921
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
2413
+ const { records, totalCount } = await searchTable({
2414
+ pathParams: {
2415
+ workspace: "{workspaceId}",
2416
+ dbBranchName: "{dbBranch}",
2417
+ region: "{region}",
2418
+ tableName: __privateGet$4(this, _table)
2419
+ },
1922
2420
  body: {
1923
2421
  query,
1924
2422
  fuzziness: options.fuzziness,
1925
2423
  prefix: options.prefix,
1926
2424
  highlight: options.highlight,
1927
2425
  filter: options.filter,
1928
- boosters: options.boosters
2426
+ boosters: options.boosters,
2427
+ page: options.page,
2428
+ target: options.target
2429
+ },
2430
+ ...__privateGet$4(this, _getFetchProps).call(this)
2431
+ });
2432
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2433
+ return {
2434
+ records: records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"])),
2435
+ totalCount
2436
+ };
2437
+ });
2438
+ }
2439
+ async vectorSearch(column, query, options) {
2440
+ return __privateGet$4(this, _trace).call(this, "vectorSearch", async () => {
2441
+ const { records, totalCount } = await vectorSearchTable({
2442
+ pathParams: {
2443
+ workspace: "{workspaceId}",
2444
+ dbBranchName: "{dbBranch}",
2445
+ region: "{region}",
2446
+ tableName: __privateGet$4(this, _table)
1929
2447
  },
1930
- ...fetchProps
2448
+ body: {
2449
+ column,
2450
+ queryVector: query,
2451
+ similarityFunction: options?.similarityFunction,
2452
+ size: options?.size,
2453
+ filter: options?.filter
2454
+ },
2455
+ ...__privateGet$4(this, _getFetchProps).call(this)
1931
2456
  });
1932
2457
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1933
- return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
2458
+ return {
2459
+ records: records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"])),
2460
+ totalCount
2461
+ };
1934
2462
  });
1935
2463
  }
1936
2464
  async aggregate(aggs, filter) {
1937
2465
  return __privateGet$4(this, _trace).call(this, "aggregate", async () => {
1938
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1939
2466
  const result = await aggregateTable({
1940
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
2467
+ pathParams: {
2468
+ workspace: "{workspaceId}",
2469
+ dbBranchName: "{dbBranch}",
2470
+ region: "{region}",
2471
+ tableName: __privateGet$4(this, _table)
2472
+ },
1941
2473
  body: { aggs, filter },
1942
- ...fetchProps
2474
+ ...__privateGet$4(this, _getFetchProps).call(this)
1943
2475
  });
1944
2476
  return result;
1945
2477
  });
@@ -1950,26 +2482,100 @@ class RestRepository extends Query {
1950
2482
  if (cacheQuery)
1951
2483
  return new Page(query, cacheQuery.meta, cacheQuery.records);
1952
2484
  const data = query.getQueryOptions();
1953
- const body = {
1954
- filter: cleanFilter(data.filter),
1955
- sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1956
- page: data.pagination,
1957
- columns: data.columns
1958
- };
1959
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1960
2485
  const { meta, records: objects } = await queryTable({
1961
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1962
- body,
1963
- ...fetchProps
2486
+ pathParams: {
2487
+ workspace: "{workspaceId}",
2488
+ dbBranchName: "{dbBranch}",
2489
+ region: "{region}",
2490
+ tableName: __privateGet$4(this, _table)
2491
+ },
2492
+ body: {
2493
+ filter: cleanFilter(data.filter),
2494
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2495
+ page: data.pagination,
2496
+ columns: data.columns ?? ["*"],
2497
+ consistency: data.consistency
2498
+ },
2499
+ fetchOptions: data.fetchOptions,
2500
+ ...__privateGet$4(this, _getFetchProps).call(this)
1964
2501
  });
1965
2502
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1966
2503
  const records = objects.map(
1967
- (record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record, data.columns ?? ["*"])
2504
+ (record) => initObject(
2505
+ __privateGet$4(this, _db),
2506
+ schemaTables,
2507
+ __privateGet$4(this, _table),
2508
+ record,
2509
+ data.columns ?? ["*"]
2510
+ )
1968
2511
  );
1969
2512
  await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1970
2513
  return new Page(query, meta, records);
1971
2514
  });
1972
2515
  }
2516
+ async summarizeTable(query, summaries, summariesFilter) {
2517
+ return __privateGet$4(this, _trace).call(this, "summarize", async () => {
2518
+ const data = query.getQueryOptions();
2519
+ const result = await summarizeTable({
2520
+ pathParams: {
2521
+ workspace: "{workspaceId}",
2522
+ dbBranchName: "{dbBranch}",
2523
+ region: "{region}",
2524
+ tableName: __privateGet$4(this, _table)
2525
+ },
2526
+ body: {
2527
+ filter: cleanFilter(data.filter),
2528
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2529
+ columns: data.columns,
2530
+ consistency: data.consistency,
2531
+ page: data.pagination?.size !== void 0 ? { size: data.pagination?.size } : void 0,
2532
+ summaries,
2533
+ summariesFilter
2534
+ },
2535
+ ...__privateGet$4(this, _getFetchProps).call(this)
2536
+ });
2537
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2538
+ return {
2539
+ ...result,
2540
+ summaries: result.summaries.map(
2541
+ (summary) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), summary, data.columns ?? [])
2542
+ )
2543
+ };
2544
+ });
2545
+ }
2546
+ ask(question, options) {
2547
+ const questionParam = options?.sessionId ? { message: question } : { question };
2548
+ const params = {
2549
+ pathParams: {
2550
+ workspace: "{workspaceId}",
2551
+ dbBranchName: "{dbBranch}",
2552
+ region: "{region}",
2553
+ tableName: __privateGet$4(this, _table),
2554
+ sessionId: options?.sessionId
2555
+ },
2556
+ body: {
2557
+ ...questionParam,
2558
+ rules: options?.rules,
2559
+ searchType: options?.searchType,
2560
+ search: options?.searchType === "keyword" ? options?.search : void 0,
2561
+ vectorSearch: options?.searchType === "vector" ? options?.vectorSearch : void 0
2562
+ },
2563
+ ...__privateGet$4(this, _getFetchProps).call(this)
2564
+ };
2565
+ if (options?.onMessage) {
2566
+ fetchSSERequest({
2567
+ endpoint: "dataPlane",
2568
+ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}",
2569
+ method: "POST",
2570
+ onMessage: (message) => {
2571
+ options.onMessage?.({ answer: message.text, records: message.records });
2572
+ },
2573
+ ...params
2574
+ });
2575
+ } else {
2576
+ return askTableSession(params);
2577
+ }
2578
+ }
1973
2579
  }
1974
2580
  _table = new WeakMap();
1975
2581
  _getFetchProps = new WeakMap();
@@ -1979,65 +2585,86 @@ _schemaTables$2 = new WeakMap();
1979
2585
  _trace = new WeakMap();
1980
2586
  _insertRecordWithoutId = new WeakSet();
1981
2587
  insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1982
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1983
- const record = transformObjectLinks(object);
2588
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
1984
2589
  const response = await insertRecord({
1985
2590
  pathParams: {
1986
2591
  workspace: "{workspaceId}",
1987
2592
  dbBranchName: "{dbBranch}",
2593
+ region: "{region}",
1988
2594
  tableName: __privateGet$4(this, _table)
1989
2595
  },
1990
2596
  queryParams: { columns },
1991
2597
  body: record,
1992
- ...fetchProps
2598
+ ...__privateGet$4(this, _getFetchProps).call(this)
1993
2599
  });
1994
2600
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1995
2601
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
1996
2602
  };
1997
2603
  _insertRecordWithId = new WeakSet();
1998
- insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
1999
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2000
- const record = transformObjectLinks(object);
2604
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { createOnly, ifVersion }) {
2605
+ if (!recordId)
2606
+ return null;
2607
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2001
2608
  const response = await insertRecordWithID({
2002
2609
  pathParams: {
2003
2610
  workspace: "{workspaceId}",
2004
2611
  dbBranchName: "{dbBranch}",
2612
+ region: "{region}",
2005
2613
  tableName: __privateGet$4(this, _table),
2006
2614
  recordId
2007
2615
  },
2008
2616
  body: record,
2009
- queryParams: { createOnly: true, columns },
2010
- ...fetchProps
2617
+ queryParams: { createOnly, columns, ifVersion },
2618
+ ...__privateGet$4(this, _getFetchProps).call(this)
2011
2619
  });
2012
2620
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2013
2621
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2014
2622
  };
2015
- _bulkInsertTableRecords = new WeakSet();
2016
- bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
2017
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2018
- const records = objects.map((object) => transformObjectLinks(object));
2019
- const response = await bulkInsertTableRecords({
2020
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
2021
- queryParams: { columns },
2022
- body: { records },
2023
- ...fetchProps
2623
+ _insertRecords = new WeakSet();
2624
+ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2625
+ const operations = await promiseMap(objects, async (object) => {
2626
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2627
+ return { insert: { table: __privateGet$4(this, _table), record, createOnly, ifVersion } };
2024
2628
  });
2025
- if (!isResponseWithRecords(response)) {
2026
- throw new Error("Request included columns but server didn't include them");
2629
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
2630
+ const ids = [];
2631
+ for (const operations2 of chunkedOperations) {
2632
+ const { results } = await branchTransaction({
2633
+ pathParams: {
2634
+ workspace: "{workspaceId}",
2635
+ dbBranchName: "{dbBranch}",
2636
+ region: "{region}"
2637
+ },
2638
+ body: { operations: operations2 },
2639
+ ...__privateGet$4(this, _getFetchProps).call(this)
2640
+ });
2641
+ for (const result of results) {
2642
+ if (result.operation === "insert") {
2643
+ ids.push(result.id);
2644
+ } else {
2645
+ ids.push(null);
2646
+ }
2647
+ }
2027
2648
  }
2028
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2029
- return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, columns));
2649
+ return ids;
2030
2650
  };
2031
2651
  _updateRecordWithID = new WeakSet();
2032
- updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
2033
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2034
- const record = transformObjectLinks(object);
2652
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2653
+ if (!recordId)
2654
+ return null;
2655
+ const { id: _id, ...record } = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2035
2656
  try {
2036
2657
  const response = await updateRecordWithID({
2037
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
2038
- queryParams: { columns },
2658
+ pathParams: {
2659
+ workspace: "{workspaceId}",
2660
+ dbBranchName: "{dbBranch}",
2661
+ region: "{region}",
2662
+ tableName: __privateGet$4(this, _table),
2663
+ recordId
2664
+ },
2665
+ queryParams: { columns, ifVersion },
2039
2666
  body: record,
2040
- ...fetchProps
2667
+ ...__privateGet$4(this, _getFetchProps).call(this)
2041
2668
  });
2042
2669
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2043
2670
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2048,26 +2675,68 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
2048
2675
  throw e;
2049
2676
  }
2050
2677
  };
2678
+ _updateRecords = new WeakSet();
2679
+ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2680
+ const operations = await promiseMap(objects, async ({ id, ...object }) => {
2681
+ const fields = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2682
+ return { update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields } };
2683
+ });
2684
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
2685
+ const ids = [];
2686
+ for (const operations2 of chunkedOperations) {
2687
+ const { results } = await branchTransaction({
2688
+ pathParams: {
2689
+ workspace: "{workspaceId}",
2690
+ dbBranchName: "{dbBranch}",
2691
+ region: "{region}"
2692
+ },
2693
+ body: { operations: operations2 },
2694
+ ...__privateGet$4(this, _getFetchProps).call(this)
2695
+ });
2696
+ for (const result of results) {
2697
+ if (result.operation === "update") {
2698
+ ids.push(result.id);
2699
+ } else {
2700
+ ids.push(null);
2701
+ }
2702
+ }
2703
+ }
2704
+ return ids;
2705
+ };
2051
2706
  _upsertRecordWithID = new WeakSet();
2052
- upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
2053
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2707
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2708
+ if (!recordId)
2709
+ return null;
2054
2710
  const response = await upsertRecordWithID({
2055
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
2056
- queryParams: { columns },
2711
+ pathParams: {
2712
+ workspace: "{workspaceId}",
2713
+ dbBranchName: "{dbBranch}",
2714
+ region: "{region}",
2715
+ tableName: __privateGet$4(this, _table),
2716
+ recordId
2717
+ },
2718
+ queryParams: { columns, ifVersion },
2057
2719
  body: object,
2058
- ...fetchProps
2720
+ ...__privateGet$4(this, _getFetchProps).call(this)
2059
2721
  });
2060
2722
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2061
2723
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2062
2724
  };
2063
2725
  _deleteRecord = new WeakSet();
2064
2726
  deleteRecord_fn = async function(recordId, columns = ["*"]) {
2065
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2727
+ if (!recordId)
2728
+ return null;
2066
2729
  try {
2067
2730
  const response = await deleteRecord({
2068
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
2731
+ pathParams: {
2732
+ workspace: "{workspaceId}",
2733
+ dbBranchName: "{dbBranch}",
2734
+ region: "{region}",
2735
+ tableName: __privateGet$4(this, _table),
2736
+ recordId
2737
+ },
2069
2738
  queryParams: { columns },
2070
- ...fetchProps
2739
+ ...__privateGet$4(this, _getFetchProps).call(this)
2071
2740
  });
2072
2741
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2073
2742
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2078,17 +2747,36 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2078
2747
  throw e;
2079
2748
  }
2080
2749
  };
2750
+ _deleteRecords = new WeakSet();
2751
+ deleteRecords_fn = async function(recordIds) {
2752
+ const chunkedOperations = chunk(
2753
+ compact(recordIds).map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
2754
+ BULK_OPERATION_MAX_SIZE
2755
+ );
2756
+ for (const operations of chunkedOperations) {
2757
+ await branchTransaction({
2758
+ pathParams: {
2759
+ workspace: "{workspaceId}",
2760
+ dbBranchName: "{dbBranch}",
2761
+ region: "{region}"
2762
+ },
2763
+ body: { operations },
2764
+ ...__privateGet$4(this, _getFetchProps).call(this)
2765
+ });
2766
+ }
2767
+ };
2081
2768
  _setCacheQuery = new WeakSet();
2082
2769
  setCacheQuery_fn = async function(query, meta, records) {
2083
- await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
2770
+ await __privateGet$4(this, _cache)?.set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: /* @__PURE__ */ new Date(), meta, records });
2084
2771
  };
2085
2772
  _getCacheQuery = new WeakSet();
2086
2773
  getCacheQuery_fn = async function(query) {
2087
2774
  const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
2088
- const result = await __privateGet$4(this, _cache).get(key);
2775
+ const result = await __privateGet$4(this, _cache)?.get(key);
2089
2776
  if (!result)
2090
2777
  return null;
2091
- const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
2778
+ const defaultTTL = __privateGet$4(this, _cache)?.defaultQueryTTL ?? -1;
2779
+ const { cache: ttl = defaultTTL } = query.getQueryOptions();
2092
2780
  if (ttl < 0)
2093
2781
  return null;
2094
2782
  const hasExpired = result.date.getTime() + ttl < Date.now();
@@ -2098,39 +2786,66 @@ _getSchemaTables$1 = new WeakSet();
2098
2786
  getSchemaTables_fn$1 = async function() {
2099
2787
  if (__privateGet$4(this, _schemaTables$2))
2100
2788
  return __privateGet$4(this, _schemaTables$2);
2101
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2102
2789
  const { schema } = await getBranchDetails({
2103
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
2104
- ...fetchProps
2790
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
2791
+ ...__privateGet$4(this, _getFetchProps).call(this)
2105
2792
  });
2106
2793
  __privateSet$4(this, _schemaTables$2, schema.tables);
2107
2794
  return schema.tables;
2108
2795
  };
2109
- const transformObjectLinks = (object) => {
2110
- return Object.entries(object).reduce((acc, [key, value]) => {
2796
+ _transformObjectToApi = new WeakSet();
2797
+ transformObjectToApi_fn = async function(object) {
2798
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2799
+ const schema = schemaTables.find((table) => table.name === __privateGet$4(this, _table));
2800
+ if (!schema)
2801
+ throw new Error(`Table ${__privateGet$4(this, _table)} not found in schema`);
2802
+ const result = {};
2803
+ for (const [key, value] of Object.entries(object)) {
2111
2804
  if (key === "xata")
2112
- return acc;
2113
- return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
2114
- }, {});
2805
+ continue;
2806
+ const type = schema.columns.find((column) => column.name === key)?.type;
2807
+ switch (type) {
2808
+ case "link": {
2809
+ result[key] = isIdentifiable(value) ? value.id : value;
2810
+ break;
2811
+ }
2812
+ case "datetime": {
2813
+ result[key] = value instanceof Date ? value.toISOString() : value;
2814
+ break;
2815
+ }
2816
+ case `file`:
2817
+ result[key] = await parseInputFileEntry(value);
2818
+ break;
2819
+ case "file[]":
2820
+ result[key] = await promiseMap(value, (item) => parseInputFileEntry(item));
2821
+ break;
2822
+ case "json":
2823
+ result[key] = stringifyJson(value);
2824
+ break;
2825
+ default:
2826
+ result[key] = value;
2827
+ }
2828
+ }
2829
+ return result;
2115
2830
  };
2116
2831
  const initObject = (db, schemaTables, table, object, selectedColumns) => {
2117
- const result = {};
2832
+ const data = {};
2118
2833
  const { xata, ...rest } = object ?? {};
2119
- Object.assign(result, rest);
2834
+ Object.assign(data, rest);
2120
2835
  const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
2121
2836
  if (!columns)
2122
2837
  console.error(`Table ${table} not found in schema`);
2123
2838
  for (const column of columns ?? []) {
2124
2839
  if (!isValidColumn(selectedColumns, column))
2125
2840
  continue;
2126
- const value = result[column.name];
2841
+ const value = data[column.name];
2127
2842
  switch (column.type) {
2128
2843
  case "datetime": {
2129
- const date = value !== void 0 ? new Date(value) : void 0;
2130
- if (date && isNaN(date.getTime())) {
2844
+ const date = value !== void 0 ? new Date(value) : null;
2845
+ if (date !== null && isNaN(date.getTime())) {
2131
2846
  console.error(`Failed to parse date ${value} for field ${column.name}`);
2132
- } else if (date) {
2133
- result[column.name] = date;
2847
+ } else {
2848
+ data[column.name] = date;
2134
2849
  }
2135
2850
  break;
2136
2851
  }
@@ -2143,47 +2858,77 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
2143
2858
  if (item === column.name) {
2144
2859
  return [...acc, "*"];
2145
2860
  }
2146
- if (item.startsWith(`${column.name}.`)) {
2861
+ if (isString(item) && item.startsWith(`${column.name}.`)) {
2147
2862
  const [, ...path] = item.split(".");
2148
2863
  return [...acc, path.join(".")];
2149
2864
  }
2150
2865
  return acc;
2151
2866
  }, []);
2152
- result[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
2867
+ data[column.name] = initObject(
2868
+ db,
2869
+ schemaTables,
2870
+ linkTable,
2871
+ value,
2872
+ selectedLinkColumns
2873
+ );
2153
2874
  } else {
2154
- result[column.name] = null;
2875
+ data[column.name] = null;
2155
2876
  }
2156
2877
  break;
2157
2878
  }
2879
+ case "file":
2880
+ data[column.name] = isDefined(value) ? new XataFile(value) : null;
2881
+ break;
2882
+ case "file[]":
2883
+ data[column.name] = value?.map((item) => new XataFile(item)) ?? null;
2884
+ break;
2885
+ case "json":
2886
+ data[column.name] = parseJson(value);
2887
+ break;
2158
2888
  default:
2159
- result[column.name] = value ?? null;
2889
+ data[column.name] = value ?? null;
2160
2890
  if (column.notNull === true && value === null) {
2161
2891
  console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
2162
2892
  }
2163
2893
  break;
2164
2894
  }
2165
2895
  }
2166
- result.read = function(columns2) {
2167
- return db[table].read(result["id"], columns2);
2896
+ const record = { ...data };
2897
+ const metadata = xata !== void 0 ? { ...xata, createdAt: new Date(xata.createdAt), updatedAt: new Date(xata.updatedAt) } : void 0;
2898
+ record.read = function(columns2) {
2899
+ return db[table].read(record["id"], columns2);
2168
2900
  };
2169
- result.update = function(data, columns2) {
2170
- return db[table].update(result["id"], data, columns2);
2901
+ record.update = function(data2, b, c) {
2902
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
2903
+ const ifVersion = parseIfVersion(b, c);
2904
+ return db[table].update(record["id"], data2, columns2, { ifVersion });
2171
2905
  };
2172
- result.delete = function() {
2173
- return db[table].delete(result["id"]);
2906
+ record.replace = function(data2, b, c) {
2907
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
2908
+ const ifVersion = parseIfVersion(b, c);
2909
+ return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
2174
2910
  };
2175
- result.getMetadata = function() {
2176
- return xata;
2911
+ record.delete = function() {
2912
+ return db[table].delete(record["id"]);
2177
2913
  };
2178
- for (const prop of ["read", "update", "delete", "getMetadata"]) {
2179
- Object.defineProperty(result, prop, { enumerable: false });
2914
+ if (metadata !== void 0) {
2915
+ record.xata = Object.freeze(metadata);
2180
2916
  }
2181
- Object.freeze(result);
2182
- return result;
2917
+ record.getMetadata = function() {
2918
+ return record.xata;
2919
+ };
2920
+ record.toSerializable = function() {
2921
+ return JSON.parse(JSON.stringify(record));
2922
+ };
2923
+ record.toString = function() {
2924
+ return JSON.stringify(record);
2925
+ };
2926
+ for (const prop of ["read", "update", "replace", "delete", "getMetadata", "toSerializable", "toString"]) {
2927
+ Object.defineProperty(record, prop, { enumerable: false });
2928
+ }
2929
+ Object.freeze(record);
2930
+ return record;
2183
2931
  };
2184
- function isResponseWithRecords(value) {
2185
- return isObject(value) && Array.isArray(value.records);
2186
- }
2187
2932
  function extractId(value) {
2188
2933
  if (isString(value))
2189
2934
  return value;
@@ -2191,20 +2936,18 @@ function extractId(value) {
2191
2936
  return value.id;
2192
2937
  return void 0;
2193
2938
  }
2194
- function cleanFilter(filter) {
2195
- if (!filter)
2196
- return void 0;
2197
- const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
2198
- return values.length > 0 ? filter : void 0;
2199
- }
2200
2939
  function isValidColumn(columns, column) {
2201
2940
  if (columns.includes("*"))
2202
2941
  return true;
2203
- if (column.type === "link") {
2204
- const linkColumns = columns.filter((item) => item.startsWith(column.name));
2205
- return linkColumns.length > 0;
2942
+ return columns.filter((item) => isString(item) && item.startsWith(column.name)).length > 0;
2943
+ }
2944
+ function parseIfVersion(...args) {
2945
+ for (const arg of args) {
2946
+ if (isObject(arg) && isNumber(arg.ifVersion)) {
2947
+ return arg.ifVersion;
2948
+ }
2206
2949
  }
2207
- return columns.includes(column.name);
2950
+ return void 0;
2208
2951
  }
2209
2952
 
2210
2953
  var __accessCheck$3 = (obj, member, msg) => {
@@ -2273,10 +3016,12 @@ const notExists = (column) => ({ $notExists: column });
2273
3016
  const startsWith = (value) => ({ $startsWith: value });
2274
3017
  const endsWith = (value) => ({ $endsWith: value });
2275
3018
  const pattern = (value) => ({ $pattern: value });
3019
+ const iPattern = (value) => ({ $iPattern: value });
2276
3020
  const is = (value) => ({ $is: value });
2277
3021
  const equals = is;
2278
3022
  const isNot = (value) => ({ $isNot: value });
2279
3023
  const contains = (value) => ({ $contains: value });
3024
+ const iContains = (value) => ({ $iContains: value });
2280
3025
  const includes = (value) => ({ $includes: value });
2281
3026
  const includesAll = (value) => ({ $includesAll: value });
2282
3027
  const includesNone = (value) => ({ $includesNone: value });
@@ -2332,6 +3077,80 @@ class SchemaPlugin extends XataPlugin {
2332
3077
  _tables = new WeakMap();
2333
3078
  _schemaTables$1 = new WeakMap();
2334
3079
 
3080
+ class FilesPlugin extends XataPlugin {
3081
+ build(pluginOptions) {
3082
+ return {
3083
+ download: async (location) => {
3084
+ const { table, record, column, fileId = "" } = location ?? {};
3085
+ return await getFileItem({
3086
+ pathParams: {
3087
+ workspace: "{workspaceId}",
3088
+ dbBranchName: "{dbBranch}",
3089
+ region: "{region}",
3090
+ tableName: table ?? "",
3091
+ recordId: record ?? "",
3092
+ columnName: column ?? "",
3093
+ fileId
3094
+ },
3095
+ ...pluginOptions,
3096
+ rawResponse: true
3097
+ });
3098
+ },
3099
+ upload: async (location, file, options) => {
3100
+ const { table, record, column, fileId = "" } = location ?? {};
3101
+ const resolvedFile = await file;
3102
+ const contentType = options?.mediaType || getContentType(resolvedFile);
3103
+ const body = resolvedFile instanceof XataFile ? resolvedFile.toBlob() : resolvedFile;
3104
+ return await putFileItem({
3105
+ ...pluginOptions,
3106
+ pathParams: {
3107
+ workspace: "{workspaceId}",
3108
+ dbBranchName: "{dbBranch}",
3109
+ region: "{region}",
3110
+ tableName: table ?? "",
3111
+ recordId: record ?? "",
3112
+ columnName: column ?? "",
3113
+ fileId
3114
+ },
3115
+ body,
3116
+ headers: { "Content-Type": contentType }
3117
+ });
3118
+ },
3119
+ delete: async (location) => {
3120
+ const { table, record, column, fileId = "" } = location ?? {};
3121
+ return await deleteFileItem({
3122
+ pathParams: {
3123
+ workspace: "{workspaceId}",
3124
+ dbBranchName: "{dbBranch}",
3125
+ region: "{region}",
3126
+ tableName: table ?? "",
3127
+ recordId: record ?? "",
3128
+ columnName: column ?? "",
3129
+ fileId
3130
+ },
3131
+ ...pluginOptions
3132
+ });
3133
+ }
3134
+ };
3135
+ }
3136
+ }
3137
+ function getContentType(file) {
3138
+ if (typeof file === "string") {
3139
+ return "text/plain";
3140
+ }
3141
+ if ("mediaType" in file && file.mediaType !== void 0) {
3142
+ return file.mediaType;
3143
+ }
3144
+ if (isBlob(file)) {
3145
+ return file.type;
3146
+ }
3147
+ try {
3148
+ return file.type;
3149
+ } catch (e) {
3150
+ }
3151
+ return "application/octet-stream";
3152
+ }
3153
+
2335
3154
  var __accessCheck$1 = (obj, member, msg) => {
2336
3155
  if (!member.has(obj))
2337
3156
  throw TypeError("Cannot " + msg);
@@ -2364,133 +3183,141 @@ class SearchPlugin extends XataPlugin {
2364
3183
  __privateAdd$1(this, _schemaTables, void 0);
2365
3184
  __privateSet$1(this, _schemaTables, schemaTables);
2366
3185
  }
2367
- build({ getFetchProps }) {
3186
+ build(pluginOptions) {
2368
3187
  return {
2369
3188
  all: async (query, options = {}) => {
2370
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
2371
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
2372
- return records.map((record) => {
2373
- const { table = "orphan" } = record.xata;
2374
- return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
2375
- });
3189
+ const { records, totalCount } = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
3190
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
3191
+ return {
3192
+ totalCount,
3193
+ records: records.map((record) => {
3194
+ const { table = "orphan" } = record.xata;
3195
+ return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
3196
+ })
3197
+ };
2376
3198
  },
2377
3199
  byTable: async (query, options = {}) => {
2378
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
2379
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
2380
- return records.reduce((acc, record) => {
3200
+ const { records: rawRecords, totalCount } = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
3201
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
3202
+ const records = rawRecords.reduce((acc, record) => {
2381
3203
  const { table = "orphan" } = record.xata;
2382
3204
  const items = acc[table] ?? [];
2383
3205
  const item = initObject(this.db, schemaTables, table, record, ["*"]);
2384
3206
  return { ...acc, [table]: [...items, item] };
2385
3207
  }, {});
3208
+ return { totalCount, records };
2386
3209
  }
2387
3210
  };
2388
3211
  }
2389
3212
  }
2390
3213
  _schemaTables = new WeakMap();
2391
3214
  _search = new WeakSet();
2392
- search_fn = async function(query, options, getFetchProps) {
2393
- const fetchProps = await getFetchProps();
2394
- const { tables, fuzziness, highlight, prefix } = options ?? {};
2395
- const { records } = await searchBranch({
2396
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
2397
- body: { tables, query, fuzziness, prefix, highlight },
2398
- ...fetchProps
3215
+ search_fn = async function(query, options, pluginOptions) {
3216
+ const { tables, fuzziness, highlight, prefix, page } = options ?? {};
3217
+ const { records, totalCount } = await searchBranch({
3218
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3219
+ // @ts-ignore https://github.com/xataio/client-ts/issues/313
3220
+ body: { tables, query, fuzziness, prefix, highlight, page },
3221
+ ...pluginOptions
2399
3222
  });
2400
- return records;
3223
+ return { records, totalCount };
2401
3224
  };
2402
3225
  _getSchemaTables = new WeakSet();
2403
- getSchemaTables_fn = async function(getFetchProps) {
3226
+ getSchemaTables_fn = async function(pluginOptions) {
2404
3227
  if (__privateGet$1(this, _schemaTables))
2405
3228
  return __privateGet$1(this, _schemaTables);
2406
- const fetchProps = await getFetchProps();
2407
3229
  const { schema } = await getBranchDetails({
2408
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
2409
- ...fetchProps
3230
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3231
+ ...pluginOptions
2410
3232
  });
2411
3233
  __privateSet$1(this, _schemaTables, schema.tables);
2412
3234
  return schema.tables;
2413
3235
  };
2414
3236
 
2415
- const isBranchStrategyBuilder = (strategy) => {
2416
- return typeof strategy === "function";
2417
- };
2418
-
2419
- async function getCurrentBranchName(options) {
2420
- const { branch, envBranch } = getEnvironment();
2421
- if (branch) {
2422
- const details = await getDatabaseBranch(branch, options);
2423
- if (details)
2424
- return branch;
2425
- console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
2426
- }
2427
- const gitBranch = envBranch || await getGitBranch();
2428
- return resolveXataBranch(gitBranch, options);
2429
- }
2430
- async function getCurrentBranchDetails(options) {
2431
- const branch = await getCurrentBranchName(options);
2432
- return getDatabaseBranch(branch, options);
2433
- }
2434
- async function resolveXataBranch(gitBranch, options) {
2435
- const databaseURL = options?.databaseURL || getDatabaseURL();
2436
- const apiKey = options?.apiKey || getAPIKey();
2437
- if (!databaseURL)
2438
- throw new Error(
2439
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2440
- );
2441
- if (!apiKey)
2442
- throw new Error(
2443
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2444
- );
2445
- const [protocol, , host, , dbName] = databaseURL.split("/");
2446
- const [workspace] = host.split(".");
2447
- const { fallbackBranch } = getEnvironment();
2448
- const { branch } = await resolveBranch({
2449
- apiKey,
2450
- apiUrl: databaseURL,
2451
- fetchImpl: getFetchImplementation(options?.fetchImpl),
2452
- workspacesApiUrl: `${protocol}//${host}`,
2453
- pathParams: { dbName, workspace },
2454
- queryParams: { gitBranch, fallbackBranch },
2455
- trace: defaultTrace
2456
- });
2457
- return branch;
2458
- }
2459
- async function getDatabaseBranch(branch, options) {
2460
- const databaseURL = options?.databaseURL || getDatabaseURL();
2461
- const apiKey = options?.apiKey || getAPIKey();
2462
- if (!databaseURL)
2463
- throw new Error(
2464
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2465
- );
2466
- if (!apiKey)
2467
- throw new Error(
2468
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2469
- );
2470
- const [protocol, , host, , database] = databaseURL.split("/");
2471
- const [workspace] = host.split(".");
2472
- const dbBranchName = `${database}:${branch}`;
2473
- try {
2474
- return await getBranchDetails({
2475
- apiKey,
2476
- apiUrl: databaseURL,
2477
- fetchImpl: getFetchImplementation(options?.fetchImpl),
2478
- workspacesApiUrl: `${protocol}//${host}`,
2479
- pathParams: { dbBranchName, workspace },
2480
- trace: defaultTrace
2481
- });
2482
- } catch (err) {
2483
- if (isObject(err) && err.status === 404)
2484
- return null;
2485
- throw err;
3237
+ function escapeElement(elementRepresentation) {
3238
+ const escaped = elementRepresentation.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
3239
+ return '"' + escaped + '"';
3240
+ }
3241
+ function arrayString(val) {
3242
+ let result = "{";
3243
+ for (let i = 0; i < val.length; i++) {
3244
+ if (i > 0) {
3245
+ result = result + ",";
3246
+ }
3247
+ if (val[i] === null || typeof val[i] === "undefined") {
3248
+ result = result + "NULL";
3249
+ } else if (Array.isArray(val[i])) {
3250
+ result = result + arrayString(val[i]);
3251
+ } else if (val[i] instanceof Buffer) {
3252
+ result += "\\\\x" + val[i].toString("hex");
3253
+ } else {
3254
+ result += escapeElement(prepareValue(val[i]));
3255
+ }
2486
3256
  }
3257
+ result = result + "}";
3258
+ return result;
2487
3259
  }
2488
- function getDatabaseURL() {
3260
+ function prepareValue(value) {
3261
+ if (!isDefined(value))
3262
+ return null;
3263
+ if (value instanceof Date) {
3264
+ return value.toISOString();
3265
+ }
3266
+ if (Array.isArray(value)) {
3267
+ return arrayString(value);
3268
+ }
3269
+ if (isObject(value)) {
3270
+ return JSON.stringify(value);
3271
+ }
2489
3272
  try {
2490
- const { databaseURL } = getEnvironment();
2491
- return databaseURL;
2492
- } catch (err) {
2493
- return void 0;
3273
+ return value.toString();
3274
+ } catch (e) {
3275
+ return value;
3276
+ }
3277
+ }
3278
+ function prepareParams(param1, param2) {
3279
+ if (isString(param1)) {
3280
+ return { statement: param1, params: param2?.map((value) => prepareValue(value)) };
3281
+ }
3282
+ if (isStringArray(param1)) {
3283
+ const statement = param1.reduce((acc, curr, index) => {
3284
+ return acc + curr + (index < (param2?.length ?? 0) ? "$" + (index + 1) : "");
3285
+ }, "");
3286
+ return { statement, params: param2?.map((value) => prepareValue(value)) };
3287
+ }
3288
+ if (isObject(param1)) {
3289
+ const { statement, params, consistency } = param1;
3290
+ return { statement, params: params?.map((value) => prepareValue(value)), consistency };
3291
+ }
3292
+ throw new Error("Invalid query");
3293
+ }
3294
+
3295
+ class SQLPlugin extends XataPlugin {
3296
+ build(pluginOptions) {
3297
+ return async (param1, ...param2) => {
3298
+ const { statement, params, consistency } = prepareParams(param1, param2);
3299
+ const { records, warning, columns } = await sqlQuery({
3300
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3301
+ body: { statement, params, consistency },
3302
+ ...pluginOptions
3303
+ });
3304
+ return { records, warning, columns };
3305
+ };
3306
+ }
3307
+ }
3308
+
3309
+ class TransactionPlugin extends XataPlugin {
3310
+ build(pluginOptions) {
3311
+ return {
3312
+ run: async (operations) => {
3313
+ const response = await branchTransaction({
3314
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3315
+ body: { operations },
3316
+ ...pluginOptions
3317
+ });
3318
+ return response;
3319
+ }
3320
+ };
2494
3321
  }
2495
3322
  }
2496
3323
 
@@ -2517,88 +3344,120 @@ var __privateMethod = (obj, member, method) => {
2517
3344
  return method;
2518
3345
  };
2519
3346
  const buildClient = (plugins) => {
2520
- var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
3347
+ var _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _a;
2521
3348
  return _a = class {
2522
3349
  constructor(options = {}, schemaTables) {
2523
3350
  __privateAdd(this, _parseOptions);
2524
3351
  __privateAdd(this, _getFetchProps);
2525
- __privateAdd(this, _evaluateBranch);
2526
- __privateAdd(this, _branch, void 0);
2527
3352
  __privateAdd(this, _options, void 0);
2528
3353
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
2529
3354
  __privateSet(this, _options, safeOptions);
2530
3355
  const pluginOptions = {
2531
- getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
3356
+ ...__privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
2532
3357
  cache: safeOptions.cache,
2533
- trace: safeOptions.trace
3358
+ host: safeOptions.host
2534
3359
  };
2535
3360
  const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2536
3361
  const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
3362
+ const transactions = new TransactionPlugin().build(pluginOptions);
3363
+ const sql = new SQLPlugin().build(pluginOptions);
3364
+ const files = new FilesPlugin().build(pluginOptions);
2537
3365
  this.db = db;
2538
3366
  this.search = search;
3367
+ this.transactions = transactions;
3368
+ this.sql = sql;
3369
+ this.files = files;
2539
3370
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
2540
3371
  if (namespace === void 0)
2541
3372
  continue;
2542
- const result = namespace.build(pluginOptions);
2543
- if (result instanceof Promise) {
2544
- void result.then((namespace2) => {
2545
- this[key] = namespace2;
2546
- });
2547
- } else {
2548
- this[key] = result;
2549
- }
3373
+ this[key] = namespace.build(pluginOptions);
2550
3374
  }
2551
3375
  }
2552
3376
  async getConfig() {
2553
3377
  const databaseURL = __privateGet(this, _options).databaseURL;
2554
- const branch = await __privateGet(this, _options).branch();
3378
+ const branch = __privateGet(this, _options).branch;
2555
3379
  return { databaseURL, branch };
2556
3380
  }
2557
- }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3381
+ }, _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3382
+ const enableBrowser = options?.enableBrowser ?? getEnableBrowserVariable() ?? false;
3383
+ const isBrowser = typeof window !== "undefined" && typeof Deno === "undefined";
3384
+ if (isBrowser && !enableBrowser) {
3385
+ throw new Error(
3386
+ "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."
3387
+ );
3388
+ }
2558
3389
  const fetch = getFetchImplementation(options?.fetch);
2559
3390
  const databaseURL = options?.databaseURL || getDatabaseURL();
2560
3391
  const apiKey = options?.apiKey || getAPIKey();
2561
3392
  const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
2562
3393
  const trace = options?.trace ?? defaultTrace;
2563
- const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
3394
+ const clientName = options?.clientName;
3395
+ const host = options?.host ?? "production";
3396
+ const xataAgentExtra = options?.xataAgentExtra;
2564
3397
  if (!apiKey) {
2565
3398
  throw new Error("Option apiKey is required");
2566
3399
  }
2567
3400
  if (!databaseURL) {
2568
3401
  throw new Error("Option databaseURL is required");
2569
3402
  }
2570
- return { fetch, databaseURL, apiKey, branch, cache, trace };
2571
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace }) {
2572
- const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
2573
- if (!branchValue)
2574
- throw new Error("Unable to resolve branch value");
3403
+ const envBranch = getBranch();
3404
+ const previewBranch = getPreviewBranch();
3405
+ const branch = options?.branch || previewBranch || envBranch || "main";
3406
+ if (!!previewBranch && branch !== previewBranch) {
3407
+ console.warn(
3408
+ `Ignoring preview branch ${previewBranch} because branch option was passed to the client constructor with value ${branch}`
3409
+ );
3410
+ } else if (!!envBranch && branch !== envBranch) {
3411
+ console.warn(
3412
+ `Ignoring branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
3413
+ );
3414
+ } else if (!!previewBranch && !!envBranch && previewBranch !== envBranch) {
3415
+ console.warn(
3416
+ `Ignoring preview branch ${previewBranch} and branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
3417
+ );
3418
+ } else if (!previewBranch && !envBranch && options?.branch === void 0) {
3419
+ console.warn(
3420
+ `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.`
3421
+ );
3422
+ }
3423
+ return {
3424
+ fetch,
3425
+ databaseURL,
3426
+ apiKey,
3427
+ branch,
3428
+ cache,
3429
+ trace,
3430
+ host,
3431
+ clientID: generateUUID(),
3432
+ enableBrowser,
3433
+ clientName,
3434
+ xataAgentExtra
3435
+ };
3436
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = function({
3437
+ fetch,
3438
+ apiKey,
3439
+ databaseURL,
3440
+ branch,
3441
+ trace,
3442
+ clientID,
3443
+ clientName,
3444
+ xataAgentExtra
3445
+ }) {
2575
3446
  return {
2576
- fetchImpl: fetch,
3447
+ fetch,
2577
3448
  apiKey,
2578
3449
  apiUrl: "",
3450
+ // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
2579
3451
  workspacesApiUrl: (path, params) => {
2580
3452
  const hasBranch = params.dbBranchName ?? params.branch;
2581
- const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branchValue}` : "");
3453
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branch}` : "");
2582
3454
  return databaseURL + newPath;
2583
3455
  },
2584
- trace
2585
- };
2586
- }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
2587
- if (__privateGet(this, _branch))
2588
- return __privateGet(this, _branch);
2589
- if (param === void 0)
2590
- return void 0;
2591
- const strategies = Array.isArray(param) ? [...param] : [param];
2592
- const evaluateBranch = async (strategy) => {
2593
- return isBranchStrategyBuilder(strategy) ? await strategy() : strategy;
3456
+ trace,
3457
+ clientID,
3458
+ clientName,
3459
+ xataAgentExtra
2594
3460
  };
2595
- for await (const strategy of strategies) {
2596
- const branch = await evaluateBranch(strategy);
2597
- if (branch) {
2598
- __privateSet(this, _branch, branch);
2599
- return branch;
2600
- }
2601
- }
2602
3461
  }, _a;
2603
3462
  };
2604
3463
  class BaseClient extends buildClient() {
@@ -2671,21 +3530,6 @@ const deserialize = (json) => {
2671
3530
  return defaultSerializer.fromJSON(json);
2672
3531
  };
2673
3532
 
2674
- function buildWorkerRunner(config) {
2675
- return function xataWorker(name, _worker) {
2676
- return async (...args) => {
2677
- const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
2678
- const result = await fetch(url, {
2679
- method: "POST",
2680
- headers: { "Content-Type": "application/json" },
2681
- body: serialize({ args })
2682
- });
2683
- const text = await result.text();
2684
- return deserialize(text);
2685
- };
2686
- };
2687
- }
2688
-
2689
3533
  class XataError extends Error {
2690
3534
  constructor(message, status) {
2691
3535
  super(message);
@@ -2694,6 +3538,8 @@ class XataError extends Error {
2694
3538
  }
2695
3539
 
2696
3540
  exports.BaseClient = BaseClient;
3541
+ exports.FetcherError = FetcherError;
3542
+ exports.FilesPlugin = FilesPlugin;
2697
3543
  exports.Operations = operationsByTag;
2698
3544
  exports.PAGINATION_DEFAULT_OFFSET = PAGINATION_DEFAULT_OFFSET;
2699
3545
  exports.PAGINATION_DEFAULT_SIZE = PAGINATION_DEFAULT_SIZE;
@@ -2702,30 +3548,41 @@ exports.PAGINATION_MAX_SIZE = PAGINATION_MAX_SIZE;
2702
3548
  exports.Page = Page;
2703
3549
  exports.Query = Query;
2704
3550
  exports.RecordArray = RecordArray;
3551
+ exports.RecordColumnTypes = RecordColumnTypes;
2705
3552
  exports.Repository = Repository;
2706
3553
  exports.RestRepository = RestRepository;
3554
+ exports.SQLPlugin = SQLPlugin;
2707
3555
  exports.SchemaPlugin = SchemaPlugin;
2708
3556
  exports.SearchPlugin = SearchPlugin;
2709
3557
  exports.Serializer = Serializer;
2710
3558
  exports.SimpleCache = SimpleCache;
3559
+ exports.TransactionPlugin = TransactionPlugin;
2711
3560
  exports.XataApiClient = XataApiClient;
2712
3561
  exports.XataApiPlugin = XataApiPlugin;
2713
3562
  exports.XataError = XataError;
3563
+ exports.XataFile = XataFile;
2714
3564
  exports.XataPlugin = XataPlugin;
2715
3565
  exports.acceptWorkspaceMemberInvite = acceptWorkspaceMemberInvite;
2716
3566
  exports.addGitBranchesEntry = addGitBranchesEntry;
2717
3567
  exports.addTableColumn = addTableColumn;
2718
3568
  exports.aggregateTable = aggregateTable;
2719
3569
  exports.applyBranchSchemaEdit = applyBranchSchemaEdit;
3570
+ exports.applyMigration = applyMigration;
3571
+ exports.askTable = askTable;
3572
+ exports.askTableSession = askTableSession;
3573
+ exports.branchTransaction = branchTransaction;
2720
3574
  exports.buildClient = buildClient;
2721
- exports.buildWorkerRunner = buildWorkerRunner;
3575
+ exports.buildPreviewBranchName = buildPreviewBranchName;
3576
+ exports.buildProviderString = buildProviderString;
2722
3577
  exports.bulkInsertTableRecords = bulkInsertTableRecords;
2723
3578
  exports.cancelWorkspaceMemberInvite = cancelWorkspaceMemberInvite;
2724
3579
  exports.compareBranchSchemas = compareBranchSchemas;
2725
3580
  exports.compareBranchWithUserSchema = compareBranchWithUserSchema;
2726
3581
  exports.compareMigrationRequest = compareMigrationRequest;
2727
3582
  exports.contains = contains;
3583
+ exports.copyBranch = copyBranch;
2728
3584
  exports.createBranch = createBranch;
3585
+ exports.createCluster = createCluster;
2729
3586
  exports.createDatabase = createDatabase;
2730
3587
  exports.createMigrationRequest = createMigrationRequest;
2731
3588
  exports.createTable = createTable;
@@ -2734,18 +3591,27 @@ exports.createWorkspace = createWorkspace;
2734
3591
  exports.deleteBranch = deleteBranch;
2735
3592
  exports.deleteColumn = deleteColumn;
2736
3593
  exports.deleteDatabase = deleteDatabase;
3594
+ exports.deleteDatabaseGithubSettings = deleteDatabaseGithubSettings;
3595
+ exports.deleteFile = deleteFile;
3596
+ exports.deleteFileItem = deleteFileItem;
3597
+ exports.deleteOAuthAccessToken = deleteOAuthAccessToken;
2737
3598
  exports.deleteRecord = deleteRecord;
2738
3599
  exports.deleteTable = deleteTable;
2739
3600
  exports.deleteUser = deleteUser;
2740
3601
  exports.deleteUserAPIKey = deleteUserAPIKey;
3602
+ exports.deleteUserOAuthClient = deleteUserOAuthClient;
2741
3603
  exports.deleteWorkspace = deleteWorkspace;
2742
3604
  exports.deserialize = deserialize;
2743
3605
  exports.endsWith = endsWith;
2744
3606
  exports.equals = equals;
2745
3607
  exports.executeBranchMigrationPlan = executeBranchMigrationPlan;
2746
3608
  exports.exists = exists;
3609
+ exports.fileAccess = fileAccess;
3610
+ exports.fileUpload = fileUpload;
2747
3611
  exports.ge = ge;
2748
3612
  exports.getAPIKey = getAPIKey;
3613
+ exports.getAuthorizationCode = getAuthorizationCode;
3614
+ exports.getBranch = getBranch;
2749
3615
  exports.getBranchDetails = getBranchDetails;
2750
3616
  exports.getBranchList = getBranchList;
2751
3617
  exports.getBranchMetadata = getBranchMetadata;
@@ -2753,29 +3619,38 @@ exports.getBranchMigrationHistory = getBranchMigrationHistory;
2753
3619
  exports.getBranchMigrationPlan = getBranchMigrationPlan;
2754
3620
  exports.getBranchSchemaHistory = getBranchSchemaHistory;
2755
3621
  exports.getBranchStats = getBranchStats;
3622
+ exports.getCluster = getCluster;
2756
3623
  exports.getColumn = getColumn;
2757
- exports.getCurrentBranchDetails = getCurrentBranchDetails;
2758
- exports.getCurrentBranchName = getCurrentBranchName;
3624
+ exports.getDatabaseGithubSettings = getDatabaseGithubSettings;
2759
3625
  exports.getDatabaseList = getDatabaseList;
2760
3626
  exports.getDatabaseMetadata = getDatabaseMetadata;
2761
3627
  exports.getDatabaseURL = getDatabaseURL;
3628
+ exports.getFile = getFile;
3629
+ exports.getFileItem = getFileItem;
2762
3630
  exports.getGitBranchesMapping = getGitBranchesMapping;
2763
3631
  exports.getHostUrl = getHostUrl;
2764
3632
  exports.getMigrationRequest = getMigrationRequest;
2765
3633
  exports.getMigrationRequestIsMerged = getMigrationRequestIsMerged;
3634
+ exports.getPreviewBranch = getPreviewBranch;
2766
3635
  exports.getRecord = getRecord;
3636
+ exports.getSchema = getSchema;
2767
3637
  exports.getTableColumns = getTableColumns;
2768
3638
  exports.getTableSchema = getTableSchema;
2769
3639
  exports.getUser = getUser;
2770
3640
  exports.getUserAPIKeys = getUserAPIKeys;
3641
+ exports.getUserOAuthAccessTokens = getUserOAuthAccessTokens;
3642
+ exports.getUserOAuthClients = getUserOAuthClients;
2771
3643
  exports.getWorkspace = getWorkspace;
2772
3644
  exports.getWorkspaceMembersList = getWorkspaceMembersList;
2773
3645
  exports.getWorkspacesList = getWorkspacesList;
3646
+ exports.grantAuthorizationCode = grantAuthorizationCode;
2774
3647
  exports.greaterEquals = greaterEquals;
2775
3648
  exports.greaterThan = greaterThan;
2776
3649
  exports.greaterThanEquals = greaterThanEquals;
2777
3650
  exports.gt = gt;
2778
3651
  exports.gte = gte;
3652
+ exports.iContains = iContains;
3653
+ exports.iPattern = iPattern;
2779
3654
  exports.includes = includes;
2780
3655
  exports.includesAll = includesAll;
2781
3656
  exports.includesAny = includesAny;
@@ -2789,37 +3664,54 @@ exports.isHostProviderAlias = isHostProviderAlias;
2789
3664
  exports.isHostProviderBuilder = isHostProviderBuilder;
2790
3665
  exports.isIdentifiable = isIdentifiable;
2791
3666
  exports.isNot = isNot;
3667
+ exports.isValidExpandedColumn = isValidExpandedColumn;
3668
+ exports.isValidSelectableColumns = isValidSelectableColumns;
2792
3669
  exports.isXataRecord = isXataRecord;
2793
3670
  exports.le = le;
2794
3671
  exports.lessEquals = lessEquals;
2795
3672
  exports.lessThan = lessThan;
2796
3673
  exports.lessThanEquals = lessThanEquals;
3674
+ exports.listClusters = listClusters;
2797
3675
  exports.listMigrationRequestsCommits = listMigrationRequestsCommits;
3676
+ exports.listRegions = listRegions;
2798
3677
  exports.lt = lt;
2799
3678
  exports.lte = lte;
2800
3679
  exports.mergeMigrationRequest = mergeMigrationRequest;
2801
3680
  exports.notExists = notExists;
2802
3681
  exports.operationsByTag = operationsByTag;
2803
3682
  exports.parseProviderString = parseProviderString;
3683
+ exports.parseWorkspacesUrlParts = parseWorkspacesUrlParts;
2804
3684
  exports.pattern = pattern;
3685
+ exports.pgRollJobStatus = pgRollJobStatus;
3686
+ exports.pgRollMigrationHistory = pgRollMigrationHistory;
3687
+ exports.pgRollStatus = pgRollStatus;
2805
3688
  exports.previewBranchSchemaEdit = previewBranchSchemaEdit;
3689
+ exports.pushBranchMigrations = pushBranchMigrations;
3690
+ exports.putFile = putFile;
3691
+ exports.putFileItem = putFileItem;
2806
3692
  exports.queryMigrationRequests = queryMigrationRequests;
2807
3693
  exports.queryTable = queryTable;
2808
3694
  exports.removeGitBranchesEntry = removeGitBranchesEntry;
2809
3695
  exports.removeWorkspaceMember = removeWorkspaceMember;
3696
+ exports.renameDatabase = renameDatabase;
2810
3697
  exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite;
2811
3698
  exports.resolveBranch = resolveBranch;
2812
3699
  exports.searchBranch = searchBranch;
2813
3700
  exports.searchTable = searchTable;
2814
3701
  exports.serialize = serialize;
2815
3702
  exports.setTableSchema = setTableSchema;
3703
+ exports.sqlQuery = sqlQuery;
2816
3704
  exports.startsWith = startsWith;
2817
3705
  exports.summarizeTable = summarizeTable;
3706
+ exports.transformImage = transformImage;
2818
3707
  exports.updateBranchMetadata = updateBranchMetadata;
2819
3708
  exports.updateBranchSchema = updateBranchSchema;
3709
+ exports.updateCluster = updateCluster;
2820
3710
  exports.updateColumn = updateColumn;
3711
+ exports.updateDatabaseGithubSettings = updateDatabaseGithubSettings;
2821
3712
  exports.updateDatabaseMetadata = updateDatabaseMetadata;
2822
3713
  exports.updateMigrationRequest = updateMigrationRequest;
3714
+ exports.updateOAuthAccessToken = updateOAuthAccessToken;
2823
3715
  exports.updateRecordWithID = updateRecordWithID;
2824
3716
  exports.updateTable = updateTable;
2825
3717
  exports.updateUser = updateUser;
@@ -2827,4 +3719,5 @@ exports.updateWorkspace = updateWorkspace;
2827
3719
  exports.updateWorkspaceMemberInvite = updateWorkspaceMemberInvite;
2828
3720
  exports.updateWorkspaceMemberRole = updateWorkspaceMemberRole;
2829
3721
  exports.upsertRecordWithID = upsertRecordWithID;
3722
+ exports.vectorSearchTable = vectorSearchTable;
2830
3723
  //# sourceMappingURL=index.cjs.map