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

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