@xata.io/client 0.0.0-alpha.vfd1a215 → 0.0.0-alpha.vfd609764793466374d6519edeb1be8debc9a83d5

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