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