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

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