@xata.io/client 0.0.0-alpha.vfe4a947 → 0.0.0-alpha.vfe896b3

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