@xata.io/client 0.0.0-alpha.vfee45b2 → 0.0.0-alpha.vff43566

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