@xata.io/client 0.0.0-alpha.vf1de7db → 0.0.0-alpha.vf1f4a0ec9618ca20e1909d6f4c7de0b61531b7e1

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.vf1de7db";
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,58 +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
- trace
709
+ trace,
710
+ signal,
711
+ clientID,
712
+ sessionID,
713
+ clientName,
714
+ xataAgentExtra,
715
+ fetchOptions = {},
716
+ rawResponse = false
237
717
  }) {
238
- return trace(
718
+ pool.setFetch(fetch2);
719
+ return await trace(
239
720
  `${method.toUpperCase()} ${path}`,
240
721
  async ({ setAttributes }) => {
241
- const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
722
+ const baseUrl = buildBaseUrl({ method, endpoint, path, workspacesApiUrl, pathParams, apiUrl });
242
723
  const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
243
- const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
724
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\.[^.]+\./, "http://") : fullUrl;
244
725
  setAttributes({
245
726
  [TraceAttributes.HTTP_URL]: url,
246
727
  [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
247
728
  });
248
- const response = await fetchImpl(url, {
729
+ const xataAgent = compact([
730
+ ["client", "TS_SDK"],
731
+ ["version", VERSION],
732
+ isDefined(clientName) ? ["service", clientName] : void 0,
733
+ ...Object.entries(xataAgentExtra ?? {})
734
+ ]).map(([key, value]) => `${key}=${value}`).join("; ");
735
+ const headers = compactObject({
736
+ "Accept-Encoding": "identity",
737
+ "Content-Type": "application/json",
738
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
739
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
740
+ "X-Xata-Agent": xataAgent,
741
+ // 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,
249
749
  method: method.toUpperCase(),
250
- body: body ? JSON.stringify(body) : void 0,
251
- headers: {
252
- "Content-Type": "application/json",
253
- "User-Agent": `Xata client-ts/${VERSION}`,
254
- ...headers,
255
- ...hostHeader(fullUrl),
256
- Authorization: `Bearer ${apiKey}`
257
- }
750
+ body: await parseBody(body, headers),
751
+ headers,
752
+ signal
258
753
  });
259
- if (response.status === 204) {
260
- return {};
261
- }
262
754
  const { host, protocol } = parseUrl(response.url);
263
755
  const requestId = response.headers?.get("x-request-id") ?? void 0;
264
756
  setAttributes({
@@ -266,10 +758,20 @@ async function fetch$1({
266
758
  [TraceAttributes.HTTP_REQUEST_ID]: requestId,
267
759
  [TraceAttributes.HTTP_STATUS_CODE]: response.status,
268
760
  [TraceAttributes.HTTP_HOST]: host,
269
- [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
761
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", ""),
762
+ [TraceAttributes.CLOUDFLARE_RAY_ID]: response.headers?.get("cf-ray") ?? void 0
270
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
+ }
271
773
  try {
272
- const jsonResponse = await response.json();
774
+ const jsonResponse = rawResponse ? await response.blob() : await response.json();
273
775
  if (response.ok) {
274
776
  return jsonResponse;
275
777
  }
@@ -281,6 +783,59 @@ async function fetch$1({
281
783
  { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
282
784
  );
283
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
+ }
284
839
  function parseUrl(url) {
285
840
  try {
286
841
  const { host, protocol } = new URL(url);
@@ -290,303 +845,277 @@ function parseUrl(url) {
290
845
  }
291
846
  }
292
847
 
293
- const getUser = (variables) => fetch$1({ url: "/user", method: "get", ...variables });
294
- const updateUser = (variables) => fetch$1({ url: "/user", method: "put", ...variables });
295
- const deleteUser = (variables) => fetch$1({ url: "/user", method: "delete", ...variables });
296
- const getUserAPIKeys = (variables) => fetch$1({
297
- url: "/user/keys",
298
- method: "get",
299
- ...variables
300
- });
301
- const createUserAPIKey = (variables) => fetch$1({
302
- url: "/user/keys/{keyName}",
303
- method: "post",
304
- ...variables
305
- });
306
- const deleteUserAPIKey = (variables) => fetch$1({
307
- url: "/user/keys/{keyName}",
308
- method: "delete",
309
- ...variables
310
- });
311
- const createWorkspace = (variables) => fetch$1({
312
- url: "/workspaces",
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}",
313
853
  method: "post",
314
- ...variables
854
+ ...variables,
855
+ signal
315
856
  });
316
- const getWorkspacesList = (variables) => fetch$1({
317
- url: "/workspaces",
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}",
318
862
  method: "get",
319
- ...variables
863
+ ...variables,
864
+ signal
320
865
  });
321
- const getWorkspace = (variables) => fetch$1({
322
- url: "/workspaces/{workspaceId}",
866
+ const getDatabaseSettings = (variables, signal) => dataPlaneFetch({
867
+ url: "/dbs/{dbName}/settings",
323
868
  method: "get",
324
- ...variables
325
- });
326
- const updateWorkspace = (variables) => fetch$1({
327
- url: "/workspaces/{workspaceId}",
328
- method: "put",
329
- ...variables
869
+ ...variables,
870
+ signal
330
871
  });
331
- const deleteWorkspace = (variables) => fetch$1({
332
- url: "/workspaces/{workspaceId}",
333
- method: "delete",
334
- ...variables
335
- });
336
- const getWorkspaceMembersList = (variables) => fetch$1({
337
- url: "/workspaces/{workspaceId}/members",
872
+ const updateDatabaseSettings = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/settings", method: "patch", ...variables, signal });
873
+ const getBranchDetails = (variables, signal) => dataPlaneFetch({
874
+ url: "/db/{dbBranchName}",
338
875
  method: "get",
339
- ...variables
876
+ ...variables,
877
+ signal
340
878
  });
341
- const updateWorkspaceMemberRole = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/members/{userId}", method: "put", ...variables });
342
- const removeWorkspaceMember = (variables) => fetch$1({
343
- url: "/workspaces/{workspaceId}/members/{userId}",
344
- method: "delete",
345
- ...variables
346
- });
347
- const inviteWorkspaceMember = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables });
348
- const updateWorkspaceMemberInvite = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables });
349
- const cancelWorkspaceMemberInvite = (variables) => fetch$1({
350
- url: "/workspaces/{workspaceId}/invites/{inviteId}",
879
+ const createBranch = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}", method: "put", ...variables, signal });
880
+ const deleteBranch = (variables, signal) => dataPlaneFetch({
881
+ url: "/db/{dbBranchName}",
351
882
  method: "delete",
352
- ...variables
883
+ ...variables,
884
+ signal
353
885
  });
354
- const resendWorkspaceMemberInvite = (variables) => fetch$1({
355
- url: "/workspaces/{workspaceId}/invites/{inviteId}/resend",
356
- method: "post",
357
- ...variables
358
- });
359
- const acceptWorkspaceMemberInvite = (variables) => fetch$1({
360
- url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept",
361
- method: "post",
362
- ...variables
363
- });
364
- const getDatabaseList = (variables) => fetch$1({
365
- url: "/dbs",
886
+ const getSchema = (variables, signal) => dataPlaneFetch({
887
+ url: "/db/{dbBranchName}/schema",
366
888
  method: "get",
367
- ...variables
889
+ ...variables,
890
+ signal
368
891
  });
369
- const getBranchList = (variables) => fetch$1({
370
- url: "/dbs/{dbName}",
371
- method: "get",
372
- ...variables
892
+ const copyBranch = (variables, signal) => dataPlaneFetch({
893
+ url: "/db/{dbBranchName}/copy",
894
+ method: "post",
895
+ ...variables,
896
+ signal
373
897
  });
374
- const createDatabase = (variables) => fetch$1({
375
- url: "/dbs/{dbName}",
898
+ const updateBranchMetadata = (variables, signal) => dataPlaneFetch({
899
+ url: "/db/{dbBranchName}/metadata",
376
900
  method: "put",
377
- ...variables
378
- });
379
- const deleteDatabase = (variables) => fetch$1({
380
- url: "/dbs/{dbName}",
381
- method: "delete",
382
- ...variables
901
+ ...variables,
902
+ signal
383
903
  });
384
- const getDatabaseMetadata = (variables) => fetch$1({
385
- url: "/dbs/{dbName}/metadata",
904
+ const getBranchMetadata = (variables, signal) => dataPlaneFetch({
905
+ url: "/db/{dbBranchName}/metadata",
386
906
  method: "get",
387
- ...variables
907
+ ...variables,
908
+ signal
388
909
  });
389
- const updateDatabaseMetadata = (variables) => fetch$1({ url: "/dbs/{dbName}/metadata", method: "patch", ...variables });
390
- const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
391
- const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
392
- const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
393
- const resolveBranch = (variables) => fetch$1({
394
- url: "/dbs/{dbName}/resolveBranch",
910
+ const getBranchStats = (variables, signal) => dataPlaneFetch({
911
+ url: "/db/{dbBranchName}/stats",
395
912
  method: "get",
396
- ...variables
913
+ ...variables,
914
+ signal
397
915
  });
398
- const queryMigrationRequests = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/query", method: "post", ...variables });
399
- const createMigrationRequest = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations", method: "post", ...variables });
400
- const getMigrationRequest = (variables) => fetch$1({
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({
401
926
  url: "/dbs/{dbName}/migrations/{mrNumber}",
402
927
  method: "get",
403
- ...variables
928
+ ...variables,
929
+ signal
404
930
  });
405
- const updateMigrationRequest = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}", method: "patch", ...variables });
406
- const listMigrationRequestsCommits = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/commits", method: "post", ...variables });
407
- const compareMigrationRequest = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/compare", method: "post", ...variables });
408
- const getMigrationRequestIsMerged = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/merge", method: "get", ...variables });
409
- const mergeMigrationRequest = (variables) => fetch$1({
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({
410
936
  url: "/dbs/{dbName}/migrations/{mrNumber}/merge",
411
937
  method: "post",
412
- ...variables
413
- });
414
- const getBranchDetails = (variables) => fetch$1({
415
- url: "/db/{dbBranchName}",
416
- method: "get",
417
- ...variables
418
- });
419
- const createBranch = (variables) => fetch$1({ url: "/db/{dbBranchName}", method: "put", ...variables });
420
- const deleteBranch = (variables) => fetch$1({
421
- url: "/db/{dbBranchName}",
422
- method: "delete",
423
- ...variables
424
- });
425
- const updateBranchMetadata = (variables) => fetch$1({
426
- url: "/db/{dbBranchName}/metadata",
427
- method: "put",
428
- ...variables
429
- });
430
- const getBranchMetadata = (variables) => fetch$1({
431
- url: "/db/{dbBranchName}/metadata",
432
- method: "get",
433
- ...variables
434
- });
435
- const getBranchMigrationHistory = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables });
436
- const executeBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables });
437
- const getBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables });
438
- const compareBranchWithUserSchema = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/compare", method: "post", ...variables });
439
- const compareBranchSchemas = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/compare/{branchName}", method: "post", ...variables });
440
- const updateBranchSchema = (variables) => fetch$1({
441
- url: "/db/{dbBranchName}/schema/update",
442
- method: "post",
443
- ...variables
444
- });
445
- const previewBranchSchemaEdit = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables });
446
- const applyBranchSchemaEdit = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables });
447
- const getBranchSchemaHistory = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/history", method: "post", ...variables });
448
- const getBranchStats = (variables) => fetch$1({
449
- url: "/db/{dbBranchName}/stats",
450
- method: "get",
451
- ...variables
938
+ ...variables,
939
+ signal
452
940
  });
453
- const createTable = (variables) => fetch$1({
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({
454
949
  url: "/db/{dbBranchName}/tables/{tableName}",
455
950
  method: "put",
456
- ...variables
951
+ ...variables,
952
+ signal
457
953
  });
458
- const deleteTable = (variables) => fetch$1({
954
+ const deleteTable = (variables, signal) => dataPlaneFetch({
459
955
  url: "/db/{dbBranchName}/tables/{tableName}",
460
956
  method: "delete",
461
- ...variables
957
+ ...variables,
958
+ signal
462
959
  });
463
- const updateTable = (variables) => fetch$1({
464
- url: "/db/{dbBranchName}/tables/{tableName}",
465
- method: "patch",
466
- ...variables
467
- });
468
- const getTableSchema = (variables) => fetch$1({
960
+ const updateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}", method: "patch", ...variables, signal });
961
+ const getTableSchema = (variables, signal) => dataPlaneFetch({
469
962
  url: "/db/{dbBranchName}/tables/{tableName}/schema",
470
963
  method: "get",
471
- ...variables
472
- });
473
- const setTableSchema = (variables) => fetch$1({
474
- url: "/db/{dbBranchName}/tables/{tableName}/schema",
475
- method: "put",
476
- ...variables
964
+ ...variables,
965
+ signal
477
966
  });
478
- const getTableColumns = (variables) => fetch$1({
967
+ const setTableSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/schema", method: "put", ...variables, signal });
968
+ const getTableColumns = (variables, signal) => dataPlaneFetch({
479
969
  url: "/db/{dbBranchName}/tables/{tableName}/columns",
480
970
  method: "get",
481
- ...variables
482
- });
483
- const addTableColumn = (variables) => fetch$1({
484
- url: "/db/{dbBranchName}/tables/{tableName}/columns",
485
- method: "post",
486
- ...variables
971
+ ...variables,
972
+ signal
487
973
  });
488
- const getColumn = (variables) => fetch$1({
974
+ const addTableColumn = (variables, signal) => dataPlaneFetch(
975
+ { url: "/db/{dbBranchName}/tables/{tableName}/columns", method: "post", ...variables, signal }
976
+ );
977
+ const getColumn = (variables, signal) => dataPlaneFetch({
489
978
  url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
490
979
  method: "get",
491
- ...variables
980
+ ...variables,
981
+ signal
492
982
  });
493
- const deleteColumn = (variables) => fetch$1({
983
+ const updateColumn = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}", method: "patch", ...variables, signal });
984
+ const deleteColumn = (variables, signal) => dataPlaneFetch({
494
985
  url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
495
986
  method: "delete",
496
- ...variables
987
+ ...variables,
988
+ signal
497
989
  });
498
- const updateColumn = (variables) => fetch$1({
499
- url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
500
- method: "patch",
501
- ...variables
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}",
994
+ method: "get",
995
+ ...variables,
996
+ signal
502
997
  });
503
- const insertRecord = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables });
504
- const insertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables });
505
- const updateRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables });
506
- const upsertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables });
507
- const deleteRecord = (variables) => fetch$1({
508
- url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
998
+ const putFileItem = (variables, signal) => dataPlaneFetch({
999
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
1000
+ method: "put",
1001
+ ...variables,
1002
+ signal
1003
+ });
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",
1012
+ method: "get",
1013
+ ...variables,
1014
+ signal
1015
+ });
1016
+ const putFile = (variables, signal) => dataPlaneFetch({
1017
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
1018
+ method: "put",
1019
+ ...variables,
1020
+ signal
1021
+ });
1022
+ const deleteFile = (variables, signal) => dataPlaneFetch({
1023
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
509
1024
  method: "delete",
510
- ...variables
1025
+ ...variables,
1026
+ signal
511
1027
  });
512
- const getRecord = (variables) => fetch$1({
1028
+ const getRecord = (variables, signal) => dataPlaneFetch({
513
1029
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
514
1030
  method: "get",
515
- ...variables
1031
+ ...variables,
1032
+ signal
516
1033
  });
517
- const bulkInsertTableRecords = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/bulk", method: "post", ...variables });
518
- const queryTable = (variables) => fetch$1({
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({
519
1040
  url: "/db/{dbBranchName}/tables/{tableName}/query",
520
1041
  method: "post",
521
- ...variables
1042
+ ...variables,
1043
+ signal
522
1044
  });
523
- const searchTable = (variables) => fetch$1({
524
- url: "/db/{dbBranchName}/tables/{tableName}/search",
1045
+ const searchBranch = (variables, signal) => dataPlaneFetch({
1046
+ url: "/db/{dbBranchName}/search",
525
1047
  method: "post",
526
- ...variables
1048
+ ...variables,
1049
+ signal
527
1050
  });
528
- const searchBranch = (variables) => fetch$1({
529
- url: "/db/{dbBranchName}/search",
1051
+ const searchTable = (variables, signal) => dataPlaneFetch({
1052
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
530
1053
  method: "post",
531
- ...variables
1054
+ ...variables,
1055
+ signal
532
1056
  });
533
- const summarizeTable = (variables) => fetch$1({
534
- url: "/db/{dbBranchName}/tables/{tableName}/summarize",
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",
535
1060
  method: "post",
536
- ...variables
1061
+ ...variables,
1062
+ signal
537
1063
  });
538
- const cPgetDatabaseList = (variables) => fetch$1({
539
- url: "/workspaces/{workspaceId}/dbs",
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}",
540
1069
  method: "get",
541
- ...variables
1070
+ ...variables,
1071
+ signal
542
1072
  });
543
- const cPcreateDatabase = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "put", ...variables });
544
- const cPdeleteDatabase = (variables) => fetch$1({
545
- url: "/workspaces/{workspaceId}/dbs/{dbName}",
546
- method: "delete",
547
- ...variables
1073
+ const fileUpload = (variables, signal) => dataPlaneFetch({
1074
+ url: "/file/{fileId}",
1075
+ method: "put",
1076
+ ...variables,
1077
+ signal
548
1078
  });
549
- const cPgetCPDatabaseMetadata = (variables) => fetch$1(
550
- { url: "/workspaces/{workspaceId}/dbs/{dbName}/metadata", method: "get", ...variables }
551
- );
552
- const cPupdateCPDatabaseMetadata = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/dbs/{dbName}/metadata", method: "patch", ...variables });
553
- const operationsByTag = {
554
- users: { getUser, updateUser, deleteUser, getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
555
- workspaces: {
556
- createWorkspace,
557
- getWorkspacesList,
558
- getWorkspace,
559
- updateWorkspace,
560
- deleteWorkspace,
561
- getWorkspaceMembersList,
562
- updateWorkspaceMemberRole,
563
- removeWorkspaceMember,
564
- inviteWorkspaceMember,
565
- updateWorkspaceMemberInvite,
566
- cancelWorkspaceMemberInvite,
567
- resendWorkspaceMemberInvite,
568
- acceptWorkspaceMemberInvite
569
- },
570
- database: {
571
- getDatabaseList,
572
- createDatabase,
573
- deleteDatabase,
574
- getDatabaseMetadata,
575
- updateDatabaseMetadata,
576
- getGitBranchesMapping,
577
- addGitBranchesEntry,
578
- removeGitBranchesEntry,
579
- resolveBranch
1079
+ const sqlQuery = (variables, signal) => dataPlaneFetch({
1080
+ url: "/db/{dbBranchName}/sql",
1081
+ method: "post",
1082
+ ...variables,
1083
+ signal
1084
+ });
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
580
1103
  },
581
1104
  branch: {
582
1105
  getBranchList,
583
1106
  getBranchDetails,
584
1107
  createBranch,
585
1108
  deleteBranch,
1109
+ copyBranch,
586
1110
  updateBranchMetadata,
587
1111
  getBranchMetadata,
588
- getBranchStats
1112
+ getBranchStats,
1113
+ getGitBranchesMapping,
1114
+ addGitBranchesEntry,
1115
+ removeGitBranchesEntry,
1116
+ resolveBranch
589
1117
  },
1118
+ database: { getDatabaseSettings, updateDatabaseSettings },
590
1119
  migrationRequests: {
591
1120
  queryMigrationRequests,
592
1121
  createMigrationRequest,
@@ -597,17 +1126,6 @@ const operationsByTag = {
597
1126
  getMigrationRequestIsMerged,
598
1127
  mergeMigrationRequest
599
1128
  },
600
- branchSchema: {
601
- getBranchMigrationHistory,
602
- executeBranchMigrationPlan,
603
- getBranchMigrationPlan,
604
- compareBranchWithUserSchema,
605
- compareBranchSchemas,
606
- updateBranchSchema,
607
- previewBranchSchemaEdit,
608
- applyBranchSchemaEdit,
609
- getBranchSchemaHistory
610
- },
611
1129
  table: {
612
1130
  createTable,
613
1131
  deleteTable,
@@ -617,717 +1135,554 @@ const operationsByTag = {
617
1135
  getTableColumns,
618
1136
  addTableColumn,
619
1137
  getColumn,
620
- deleteColumn,
621
- updateColumn
1138
+ updateColumn,
1139
+ deleteColumn
622
1140
  },
623
1141
  records: {
1142
+ branchTransaction,
624
1143
  insertRecord,
1144
+ getRecord,
625
1145
  insertRecordWithID,
626
1146
  updateRecordWithID,
627
1147
  upsertRecordWithID,
628
1148
  deleteRecord,
629
- getRecord,
630
- bulkInsertTableRecords,
1149
+ bulkInsertTableRecords
1150
+ },
1151
+ files: { getFileItem, putFileItem, deleteFileItem, getFile, putFile, deleteFile, fileAccess, fileUpload },
1152
+ searchAndFilter: {
631
1153
  queryTable,
632
- searchTable,
633
1154
  searchBranch,
634
- summarizeTable
1155
+ searchTable,
1156
+ vectorSearchTable,
1157
+ askTable,
1158
+ askTableSession,
1159
+ summarizeTable,
1160
+ aggregateTable
635
1161
  },
636
- databases: {
637
- cPgetDatabaseList,
638
- cPcreateDatabase,
639
- cPdeleteDatabase,
640
- cPgetCPDatabaseMetadata,
641
- cPupdateCPDatabaseMetadata
642
- }
1162
+ sql: { sqlQuery }
643
1163
  };
644
1164
 
645
- function getHostUrl(provider, type) {
646
- if (isHostProviderAlias(provider)) {
647
- return providers[provider][type];
648
- } else if (isHostProviderBuilder(provider)) {
649
- return provider[type];
650
- }
651
- throw new Error("Invalid API provider");
652
- }
653
- const providers = {
654
- production: {
655
- main: "https://api.xata.io",
656
- workspaces: "https://{workspaceId}.xata.sh"
657
- },
658
- staging: {
659
- main: "https://staging.xatabase.co",
660
- workspaces: "https://{workspaceId}.staging.xatabase.co"
661
- }
662
- };
663
- function isHostProviderAlias(alias) {
664
- return isString(alias) && Object.keys(providers).includes(alias);
665
- }
666
- function isHostProviderBuilder(builder) {
667
- return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
668
- }
1165
+ const controlPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "controlPlane" });
669
1166
 
670
- var __accessCheck$7 = (obj, member, msg) => {
671
- if (!member.has(obj))
672
- throw TypeError("Cannot " + msg);
673
- };
674
- var __privateGet$7 = (obj, member, getter) => {
675
- __accessCheck$7(obj, member, "read from private field");
676
- return getter ? getter.call(obj) : member.get(obj);
677
- };
678
- var __privateAdd$7 = (obj, member, value) => {
679
- if (member.has(obj))
680
- throw TypeError("Cannot add the same private member more than once");
681
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
682
- };
683
- var __privateSet$7 = (obj, member, value, setter) => {
684
- __accessCheck$7(obj, member, "write to private field");
685
- setter ? setter.call(obj, value) : member.set(obj, value);
686
- return value;
687
- };
688
- var _extraProps, _namespaces;
689
- class XataApiClient {
690
- constructor(options = {}) {
691
- __privateAdd$7(this, _extraProps, void 0);
692
- __privateAdd$7(this, _namespaces, {});
693
- const provider = options.host ?? "production";
694
- const apiKey = options.apiKey ?? getAPIKey();
695
- const trace = options.trace ?? defaultTrace;
696
- if (!apiKey) {
697
- throw new Error("Could not resolve a valid apiKey");
698
- }
699
- __privateSet$7(this, _extraProps, {
700
- apiUrl: getHostUrl(provider, "main"),
701
- workspacesApiUrl: getHostUrl(provider, "workspaces"),
702
- fetchImpl: getFetchImplementation(options.fetch),
703
- apiKey,
704
- trace
705
- });
706
- }
707
- get user() {
708
- if (!__privateGet$7(this, _namespaces).user)
709
- __privateGet$7(this, _namespaces).user = new UserApi(__privateGet$7(this, _extraProps));
710
- return __privateGet$7(this, _namespaces).user;
711
- }
712
- get workspaces() {
713
- if (!__privateGet$7(this, _namespaces).workspaces)
714
- __privateGet$7(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$7(this, _extraProps));
715
- return __privateGet$7(this, _namespaces).workspaces;
716
- }
717
- get databases() {
718
- if (!__privateGet$7(this, _namespaces).databases)
719
- __privateGet$7(this, _namespaces).databases = new DatabaseApi(__privateGet$7(this, _extraProps));
720
- return __privateGet$7(this, _namespaces).databases;
721
- }
722
- get branches() {
723
- if (!__privateGet$7(this, _namespaces).branches)
724
- __privateGet$7(this, _namespaces).branches = new BranchApi(__privateGet$7(this, _extraProps));
725
- return __privateGet$7(this, _namespaces).branches;
726
- }
727
- get tables() {
728
- if (!__privateGet$7(this, _namespaces).tables)
729
- __privateGet$7(this, _namespaces).tables = new TableApi(__privateGet$7(this, _extraProps));
730
- return __privateGet$7(this, _namespaces).tables;
731
- }
732
- get records() {
733
- if (!__privateGet$7(this, _namespaces).records)
734
- __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
735
- return __privateGet$7(this, _namespaces).records;
736
- }
737
- get migrationRequests() {
738
- if (!__privateGet$7(this, _namespaces).migrationRequests)
739
- __privateGet$7(this, _namespaces).migrationRequests = new MigrationRequestsApi(__privateGet$7(this, _extraProps));
740
- return __privateGet$7(this, _namespaces).migrationRequests;
741
- }
742
- get branchSchema() {
743
- if (!__privateGet$7(this, _namespaces).branchSchema)
744
- __privateGet$7(this, _namespaces).branchSchema = new BranchSchemaApi(__privateGet$7(this, _extraProps));
745
- return __privateGet$7(this, _namespaces).branchSchema;
746
- }
747
- }
748
- _extraProps = new WeakMap();
749
- _namespaces = new WeakMap();
750
- class UserApi {
751
- constructor(extraProps) {
752
- this.extraProps = extraProps;
753
- }
754
- getUser() {
755
- return operationsByTag.users.getUser({ ...this.extraProps });
756
- }
757
- updateUser(user) {
758
- return operationsByTag.users.updateUser({ body: user, ...this.extraProps });
759
- }
760
- deleteUser() {
761
- return operationsByTag.users.deleteUser({ ...this.extraProps });
762
- }
763
- getUserAPIKeys() {
764
- return operationsByTag.users.getUserAPIKeys({ ...this.extraProps });
765
- }
766
- createUserAPIKey(keyName) {
767
- return operationsByTag.users.createUserAPIKey({
768
- pathParams: { keyName },
769
- ...this.extraProps
770
- });
771
- }
772
- deleteUserAPIKey(keyName) {
773
- return operationsByTag.users.deleteUserAPIKey({
774
- pathParams: { keyName },
775
- ...this.extraProps
776
- });
777
- }
778
- }
779
- class WorkspaceApi {
780
- constructor(extraProps) {
781
- this.extraProps = extraProps;
782
- }
783
- createWorkspace(workspaceMeta) {
784
- return operationsByTag.workspaces.createWorkspace({
785
- body: workspaceMeta,
786
- ...this.extraProps
787
- });
788
- }
789
- getWorkspacesList() {
790
- return operationsByTag.workspaces.getWorkspacesList({ ...this.extraProps });
791
- }
792
- getWorkspace(workspaceId) {
793
- return operationsByTag.workspaces.getWorkspace({
794
- pathParams: { workspaceId },
795
- ...this.extraProps
796
- });
797
- }
798
- updateWorkspace(workspaceId, workspaceMeta) {
799
- return operationsByTag.workspaces.updateWorkspace({
800
- pathParams: { workspaceId },
801
- body: workspaceMeta,
802
- ...this.extraProps
803
- });
804
- }
805
- deleteWorkspace(workspaceId) {
806
- return operationsByTag.workspaces.deleteWorkspace({
807
- pathParams: { workspaceId },
808
- ...this.extraProps
809
- });
810
- }
811
- getWorkspaceMembersList(workspaceId) {
812
- return operationsByTag.workspaces.getWorkspaceMembersList({
813
- pathParams: { workspaceId },
814
- ...this.extraProps
815
- });
816
- }
817
- updateWorkspaceMemberRole(workspaceId, userId, role) {
818
- return operationsByTag.workspaces.updateWorkspaceMemberRole({
819
- pathParams: { workspaceId, userId },
820
- body: { role },
821
- ...this.extraProps
822
- });
823
- }
824
- removeWorkspaceMember(workspaceId, userId) {
825
- return operationsByTag.workspaces.removeWorkspaceMember({
826
- pathParams: { workspaceId, userId },
827
- ...this.extraProps
828
- });
829
- }
830
- inviteWorkspaceMember(workspaceId, email, role) {
831
- return operationsByTag.workspaces.inviteWorkspaceMember({
832
- pathParams: { workspaceId },
833
- body: { email, role },
834
- ...this.extraProps
835
- });
836
- }
837
- updateWorkspaceMemberInvite(workspaceId, inviteId, role) {
838
- return operationsByTag.workspaces.updateWorkspaceMemberInvite({
839
- pathParams: { workspaceId, inviteId },
840
- body: { role },
841
- ...this.extraProps
842
- });
843
- }
844
- cancelWorkspaceMemberInvite(workspaceId, inviteId) {
845
- return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
846
- pathParams: { workspaceId, inviteId },
847
- ...this.extraProps
848
- });
849
- }
850
- resendWorkspaceMemberInvite(workspaceId, inviteId) {
851
- return operationsByTag.workspaces.resendWorkspaceMemberInvite({
852
- pathParams: { workspaceId, inviteId },
853
- ...this.extraProps
854
- });
855
- }
856
- acceptWorkspaceMemberInvite(workspaceId, inviteKey) {
857
- return operationsByTag.workspaces.acceptWorkspaceMemberInvite({
858
- pathParams: { workspaceId, inviteKey },
859
- ...this.extraProps
860
- });
861
- }
862
- }
863
- class DatabaseApi {
864
- constructor(extraProps) {
865
- this.extraProps = extraProps;
866
- }
867
- getDatabaseList(workspace) {
868
- return operationsByTag.database.getDatabaseList({
869
- pathParams: { workspace },
870
- ...this.extraProps
871
- });
872
- }
873
- createDatabase(workspace, dbName, options = {}) {
874
- return operationsByTag.database.createDatabase({
875
- pathParams: { workspace, dbName },
876
- body: options,
877
- ...this.extraProps
878
- });
879
- }
880
- deleteDatabase(workspace, dbName) {
881
- return operationsByTag.database.deleteDatabase({
882
- pathParams: { workspace, dbName },
883
- ...this.extraProps
884
- });
885
- }
886
- getDatabaseMetadata(workspace, dbName) {
887
- return operationsByTag.database.getDatabaseMetadata({
888
- pathParams: { workspace, dbName },
889
- ...this.extraProps
890
- });
891
- }
892
- updateDatabaseMetadata(workspace, dbName, options = {}) {
893
- return operationsByTag.database.updateDatabaseMetadata({
894
- pathParams: { workspace, dbName },
895
- body: options,
896
- ...this.extraProps
897
- });
898
- }
899
- getGitBranchesMapping(workspace, dbName) {
900
- return operationsByTag.database.getGitBranchesMapping({
901
- pathParams: { workspace, dbName },
902
- ...this.extraProps
903
- });
904
- }
905
- addGitBranchesEntry(workspace, dbName, body) {
906
- return operationsByTag.database.addGitBranchesEntry({
907
- pathParams: { workspace, dbName },
908
- body,
909
- ...this.extraProps
910
- });
911
- }
912
- removeGitBranchesEntry(workspace, dbName, gitBranch) {
913
- return operationsByTag.database.removeGitBranchesEntry({
914
- pathParams: { workspace, dbName },
915
- queryParams: { gitBranch },
916
- ...this.extraProps
917
- });
918
- }
919
- resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
920
- return operationsByTag.database.resolveBranch({
921
- pathParams: { workspace, dbName },
922
- queryParams: { gitBranch, fallbackBranch },
923
- ...this.extraProps
924
- });
925
- }
926
- }
927
- class BranchApi {
928
- constructor(extraProps) {
929
- this.extraProps = extraProps;
930
- }
931
- getBranchList(workspace, dbName) {
932
- return operationsByTag.branch.getBranchList({
933
- pathParams: { workspace, dbName },
934
- ...this.extraProps
935
- });
936
- }
937
- getBranchDetails(workspace, database, branch) {
938
- return operationsByTag.branch.getBranchDetails({
939
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
940
- ...this.extraProps
941
- });
942
- }
943
- createBranch(workspace, database, branch, from, options = {}) {
944
- return operationsByTag.branch.createBranch({
945
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
946
- queryParams: isString(from) ? { from } : void 0,
947
- body: options,
948
- ...this.extraProps
949
- });
950
- }
951
- deleteBranch(workspace, database, branch) {
952
- return operationsByTag.branch.deleteBranch({
953
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
954
- ...this.extraProps
955
- });
956
- }
957
- updateBranchMetadata(workspace, database, branch, metadata = {}) {
958
- return operationsByTag.branch.updateBranchMetadata({
959
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
960
- body: metadata,
961
- ...this.extraProps
962
- });
963
- }
964
- getBranchMetadata(workspace, database, branch) {
965
- return operationsByTag.branch.getBranchMetadata({
966
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
967
- ...this.extraProps
968
- });
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",
1172
+ ...variables,
1173
+ signal
1174
+ });
1175
+ const updateUser = (variables, signal) => controlPlaneFetch({
1176
+ url: "/user",
1177
+ method: "put",
1178
+ ...variables,
1179
+ signal
1180
+ });
1181
+ const deleteUser = (variables, signal) => controlPlaneFetch({
1182
+ url: "/user",
1183
+ method: "delete",
1184
+ ...variables,
1185
+ signal
1186
+ });
1187
+ const getUserAPIKeys = (variables, signal) => controlPlaneFetch({
1188
+ url: "/user/keys",
1189
+ method: "get",
1190
+ ...variables,
1191
+ signal
1192
+ });
1193
+ const createUserAPIKey = (variables, signal) => controlPlaneFetch({
1194
+ url: "/user/keys/{keyName}",
1195
+ method: "post",
1196
+ ...variables,
1197
+ signal
1198
+ });
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",
1207
+ method: "get",
1208
+ ...variables,
1209
+ signal
1210
+ });
1211
+ const deleteUserOAuthClient = (variables, signal) => controlPlaneFetch({
1212
+ url: "/user/oauth/clients/{clientId}",
1213
+ method: "delete",
1214
+ ...variables,
1215
+ signal
1216
+ });
1217
+ const getUserOAuthAccessTokens = (variables, signal) => controlPlaneFetch({
1218
+ url: "/user/oauth/tokens",
1219
+ method: "get",
1220
+ ...variables,
1221
+ signal
1222
+ });
1223
+ const deleteOAuthAccessToken = (variables, signal) => controlPlaneFetch({
1224
+ url: "/user/oauth/tokens/{token}",
1225
+ method: "delete",
1226
+ ...variables,
1227
+ signal
1228
+ });
1229
+ const updateOAuthAccessToken = (variables, signal) => controlPlaneFetch({ url: "/user/oauth/tokens/{token}", method: "patch", ...variables, signal });
1230
+ const getWorkspacesList = (variables, signal) => controlPlaneFetch({
1231
+ url: "/workspaces",
1232
+ method: "get",
1233
+ ...variables,
1234
+ signal
1235
+ });
1236
+ const createWorkspace = (variables, signal) => controlPlaneFetch({
1237
+ url: "/workspaces",
1238
+ method: "post",
1239
+ ...variables,
1240
+ signal
1241
+ });
1242
+ const getWorkspace = (variables, signal) => controlPlaneFetch({
1243
+ url: "/workspaces/{workspaceId}",
1244
+ method: "get",
1245
+ ...variables,
1246
+ signal
1247
+ });
1248
+ const updateWorkspace = (variables, signal) => controlPlaneFetch({
1249
+ url: "/workspaces/{workspaceId}",
1250
+ method: "put",
1251
+ ...variables,
1252
+ signal
1253
+ });
1254
+ const deleteWorkspace = (variables, signal) => controlPlaneFetch({
1255
+ url: "/workspaces/{workspaceId}",
1256
+ method: "delete",
1257
+ ...variables,
1258
+ signal
1259
+ });
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
1280
+ });
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 },
1319
+ workspaces: {
1320
+ getWorkspacesList,
1321
+ createWorkspace,
1322
+ getWorkspace,
1323
+ updateWorkspace,
1324
+ deleteWorkspace,
1325
+ getWorkspaceMembersList,
1326
+ updateWorkspaceMemberRole,
1327
+ removeWorkspaceMember
1328
+ },
1329
+ invites: {
1330
+ inviteWorkspaceMember,
1331
+ updateWorkspaceMemberInvite,
1332
+ cancelWorkspaceMemberInvite,
1333
+ acceptWorkspaceMemberInvite,
1334
+ resendWorkspaceMemberInvite
1335
+ },
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
969
1348
  }
970
- getBranchStats(workspace, database, branch) {
971
- return operationsByTag.branch.getBranchStats({
972
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
973
- ...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
+ }
974
1392
  });
975
1393
  }
1394
+ };
1395
+ class XataApiClient extends buildApiClient() {
976
1396
  }
977
- class TableApi {
978
- constructor(extraProps) {
979
- this.extraProps = extraProps;
980
- }
981
- createTable(workspace, database, branch, tableName) {
982
- return operationsByTag.table.createTable({
983
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
984
- ...this.extraProps
985
- });
986
- }
987
- deleteTable(workspace, database, branch, tableName) {
988
- return operationsByTag.table.deleteTable({
989
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
990
- ...this.extraProps
991
- });
992
- }
993
- updateTable(workspace, database, branch, tableName, options) {
994
- return operationsByTag.table.updateTable({
995
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
996
- body: options,
997
- ...this.extraProps
998
- });
999
- }
1000
- getTableSchema(workspace, database, branch, tableName) {
1001
- return operationsByTag.table.getTableSchema({
1002
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1003
- ...this.extraProps
1004
- });
1005
- }
1006
- setTableSchema(workspace, database, branch, tableName, options) {
1007
- return operationsByTag.table.setTableSchema({
1008
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1009
- body: options,
1010
- ...this.extraProps
1011
- });
1012
- }
1013
- getTableColumns(workspace, database, branch, tableName) {
1014
- return operationsByTag.table.getTableColumns({
1015
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1016
- ...this.extraProps
1017
- });
1018
- }
1019
- addTableColumn(workspace, database, branch, tableName, column) {
1020
- return operationsByTag.table.addTableColumn({
1021
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1022
- body: column,
1023
- ...this.extraProps
1024
- });
1025
- }
1026
- getColumn(workspace, database, branch, tableName, columnName) {
1027
- return operationsByTag.table.getColumn({
1028
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, columnName },
1029
- ...this.extraProps
1030
- });
1031
- }
1032
- deleteColumn(workspace, database, branch, tableName, columnName) {
1033
- return operationsByTag.table.deleteColumn({
1034
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, columnName },
1035
- ...this.extraProps
1036
- });
1037
- }
1038
- updateColumn(workspace, database, branch, tableName, columnName, options) {
1039
- return operationsByTag.table.updateColumn({
1040
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, columnName },
1041
- body: options,
1042
- ...this.extraProps
1043
- });
1397
+
1398
+ class XataApiPlugin {
1399
+ build(options) {
1400
+ return new XataApiClient(options);
1044
1401
  }
1045
1402
  }
1046
- class RecordsApi {
1047
- constructor(extraProps) {
1048
- this.extraProps = extraProps;
1049
- }
1050
- insertRecord(workspace, database, branch, tableName, record, options = {}) {
1051
- return operationsByTag.records.insertRecord({
1052
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1053
- queryParams: options,
1054
- body: record,
1055
- ...this.extraProps
1056
- });
1057
- }
1058
- insertRecordWithID(workspace, database, branch, tableName, recordId, record, options = {}) {
1059
- return operationsByTag.records.insertRecordWithID({
1060
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1061
- queryParams: options,
1062
- body: record,
1063
- ...this.extraProps
1064
- });
1065
- }
1066
- updateRecordWithID(workspace, database, branch, tableName, recordId, record, options = {}) {
1067
- return operationsByTag.records.updateRecordWithID({
1068
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1069
- queryParams: options,
1070
- body: record,
1071
- ...this.extraProps
1072
- });
1073
- }
1074
- upsertRecordWithID(workspace, database, branch, tableName, recordId, record, options = {}) {
1075
- return operationsByTag.records.upsertRecordWithID({
1076
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1077
- queryParams: options,
1078
- body: record,
1079
- ...this.extraProps
1080
- });
1081
- }
1082
- deleteRecord(workspace, database, branch, tableName, recordId, options = {}) {
1083
- return operationsByTag.records.deleteRecord({
1084
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1085
- queryParams: options,
1086
- ...this.extraProps
1087
- });
1088
- }
1089
- getRecord(workspace, database, branch, tableName, recordId, options = {}) {
1090
- return operationsByTag.records.getRecord({
1091
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1092
- queryParams: options,
1093
- ...this.extraProps
1094
- });
1095
- }
1096
- bulkInsertTableRecords(workspace, database, branch, tableName, records, options = {}) {
1097
- return operationsByTag.records.bulkInsertTableRecords({
1098
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1099
- queryParams: options,
1100
- body: { records },
1101
- ...this.extraProps
1102
- });
1103
- }
1104
- queryTable(workspace, database, branch, tableName, query) {
1105
- return operationsByTag.records.queryTable({
1106
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1107
- body: query,
1108
- ...this.extraProps
1109
- });
1110
- }
1111
- searchTable(workspace, database, branch, tableName, query) {
1112
- return operationsByTag.records.searchTable({
1113
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1114
- body: query,
1115
- ...this.extraProps
1116
- });
1117
- }
1118
- searchBranch(workspace, database, branch, query) {
1119
- return operationsByTag.records.searchBranch({
1120
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1121
- body: query,
1122
- ...this.extraProps
1123
- });
1124
- }
1125
- summarizeTable(workspace, database, branch, tableName, query) {
1126
- return operationsByTag.records.summarizeTable({
1127
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1128
- body: query,
1129
- ...this.extraProps
1130
- });
1131
- }
1403
+
1404
+ class XataPlugin {
1132
1405
  }
1133
- class MigrationRequestsApi {
1134
- constructor(extraProps) {
1135
- this.extraProps = extraProps;
1136
- }
1137
- queryMigrationRequests(workspace, database, options = {}) {
1138
- return operationsByTag.migrationRequests.queryMigrationRequests({
1139
- pathParams: { workspace, dbName: database },
1140
- body: options,
1141
- ...this.extraProps
1142
- });
1143
- }
1144
- createMigrationRequest(workspace, database, options) {
1145
- return operationsByTag.migrationRequests.createMigrationRequest({
1146
- pathParams: { workspace, dbName: database },
1147
- body: options,
1148
- ...this.extraProps
1149
- });
1150
- }
1151
- getMigrationRequest(workspace, database, migrationRequest) {
1152
- return operationsByTag.migrationRequests.getMigrationRequest({
1153
- pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1154
- ...this.extraProps
1155
- });
1156
- }
1157
- updateMigrationRequest(workspace, database, migrationRequest, options) {
1158
- return operationsByTag.migrationRequests.updateMigrationRequest({
1159
- pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1160
- body: options,
1161
- ...this.extraProps
1162
- });
1163
- }
1164
- listMigrationRequestsCommits(workspace, database, migrationRequest, options = {}) {
1165
- return operationsByTag.migrationRequests.listMigrationRequestsCommits({
1166
- pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1167
- body: options,
1168
- ...this.extraProps
1169
- });
1170
- }
1171
- compareMigrationRequest(workspace, database, migrationRequest) {
1172
- return operationsByTag.migrationRequests.compareMigrationRequest({
1173
- pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1174
- ...this.extraProps
1175
- });
1176
- }
1177
- getMigrationRequestIsMerged(workspace, database, migrationRequest) {
1178
- return operationsByTag.migrationRequests.getMigrationRequestIsMerged({
1179
- pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1180
- ...this.extraProps
1181
- });
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");
1182
1460
  }
1183
- mergeMigrationRequest(workspace, database, migrationRequest) {
1184
- return operationsByTag.migrationRequests.mergeMigrationRequest({
1185
- pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1186
- ...this.extraProps
1187
- });
1461
+ static fromArrayBuffer(arrayBuffer, options = {}) {
1462
+ const uint8Array = new Uint8Array(arrayBuffer);
1463
+ return this.fromUint8Array(uint8Array, options);
1188
1464
  }
1189
- }
1190
- class BranchSchemaApi {
1191
- constructor(extraProps) {
1192
- 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);
1193
1471
  }
1194
- getBranchMigrationHistory(workspace, database, branch, options = {}) {
1195
- return operationsByTag.branchSchema.getBranchMigrationHistory({
1196
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1197
- body: options,
1198
- ...this.extraProps
1199
- });
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 });
1200
1479
  }
1201
- executeBranchMigrationPlan(workspace, database, branch, migrationPlan) {
1202
- return operationsByTag.branchSchema.executeBranchMigrationPlan({
1203
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1204
- body: migrationPlan,
1205
- ...this.extraProps
1206
- });
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;
1207
1490
  }
1208
- getBranchMigrationPlan(workspace, database, branch, schema) {
1209
- return operationsByTag.branchSchema.getBranchMigrationPlan({
1210
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1211
- body: schema,
1212
- ...this.extraProps
1213
- });
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 });
1214
1496
  }
1215
- compareBranchWithUserSchema(workspace, database, branch, schema) {
1216
- return operationsByTag.branchSchema.compareBranchWithUserSchema({
1217
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1218
- body: { schema },
1219
- ...this.extraProps
1220
- });
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 });
1221
1507
  }
1222
- compareBranchSchemas(workspace, database, branch, branchName, schema) {
1223
- return operationsByTag.branchSchema.compareBranchSchemas({
1224
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, branchName },
1225
- body: { schema },
1226
- ...this.extraProps
1227
- });
1508
+ static fromString(string, options = {}) {
1509
+ const base64Content = btoa(string);
1510
+ return new XataFile({ ...options, base64Content });
1228
1511
  }
1229
- updateBranchSchema(workspace, database, branch, migration) {
1230
- return operationsByTag.branchSchema.updateBranchSchema({
1231
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1232
- body: migration,
1233
- ...this.extraProps
1234
- });
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);
1235
1517
  }
1236
- previewBranchSchemaEdit(workspace, database, branch, migration) {
1237
- return operationsByTag.branchSchema.previewBranchSchemaEdit({
1238
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1239
- body: migration,
1240
- ...this.extraProps
1241
- });
1518
+ static fromBase64(base64Content, options = {}) {
1519
+ return new XataFile({ ...options, base64Content });
1242
1520
  }
1243
- applyBranchSchemaEdit(workspace, database, branch, edits) {
1244
- return operationsByTag.branchSchema.applyBranchSchemaEdit({
1245
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1246
- body: { edits },
1247
- ...this.extraProps
1248
- });
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;
1249
1526
  }
1250
- getBranchSchemaHistory(workspace, database, branch, options = {}) {
1251
- return operationsByTag.branchSchema.getBranchSchemaHistory({
1252
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1253
- body: options,
1254
- ...this.extraProps
1255
- });
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
+ };
1256
1534
  }
1257
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
+ };
1551
+
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;
1577
+ }
1258
1578
 
1259
- class XataApiPlugin {
1260
- async build(options) {
1261
- const { fetchImpl, apiKey } = await options.getFetchProps();
1262
- return new XataApiClient({ fetch: fetchImpl, apiKey });
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;
1263
1588
  }
1264
1589
  }
1265
-
1266
- class XataPlugin {
1590
+ function parseJson(value) {
1591
+ try {
1592
+ return JSON.parse(value);
1593
+ } catch (e) {
1594
+ return value;
1595
+ }
1267
1596
  }
1268
1597
 
1269
- var __accessCheck$6 = (obj, member, msg) => {
1598
+ var __accessCheck$5 = (obj, member, msg) => {
1270
1599
  if (!member.has(obj))
1271
1600
  throw TypeError("Cannot " + msg);
1272
1601
  };
1273
- var __privateGet$6 = (obj, member, getter) => {
1274
- __accessCheck$6(obj, member, "read from private field");
1602
+ var __privateGet$4 = (obj, member, getter) => {
1603
+ __accessCheck$5(obj, member, "read from private field");
1275
1604
  return getter ? getter.call(obj) : member.get(obj);
1276
1605
  };
1277
- var __privateAdd$6 = (obj, member, value) => {
1606
+ var __privateAdd$5 = (obj, member, value) => {
1278
1607
  if (member.has(obj))
1279
1608
  throw TypeError("Cannot add the same private member more than once");
1280
1609
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1281
1610
  };
1282
- var __privateSet$6 = (obj, member, value, setter) => {
1283
- __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");
1284
1613
  setter ? setter.call(obj, value) : member.set(obj, value);
1285
1614
  return value;
1286
1615
  };
1287
1616
  var _query, _page;
1288
1617
  class Page {
1289
1618
  constructor(query, meta, records = []) {
1290
- __privateAdd$6(this, _query, void 0);
1291
- __privateSet$6(this, _query, query);
1619
+ __privateAdd$5(this, _query, void 0);
1620
+ __privateSet$3(this, _query, query);
1292
1621
  this.meta = meta;
1293
- this.records = new RecordArray(this, records);
1294
- }
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
+ */
1295
1630
  async nextPage(size, offset) {
1296
- return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
1297
- }
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
+ */
1298
1639
  async previousPage(size, offset) {
1299
- return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
1300
- }
1301
- async firstPage(size, offset) {
1302
- return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
1303
- }
1304
- async lastPage(size, offset) {
1305
- return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
1306
- }
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
+ */
1307
1664
  hasNextPage() {
1308
1665
  return this.meta.page.more;
1309
1666
  }
1310
1667
  }
1311
1668
  _query = new WeakMap();
1312
- const PAGINATION_MAX_SIZE = 200;
1669
+ const PAGINATION_MAX_SIZE = 1e3;
1313
1670
  const PAGINATION_DEFAULT_SIZE = 20;
1314
- const PAGINATION_MAX_OFFSET = 800;
1671
+ const PAGINATION_MAX_OFFSET = 49e3;
1315
1672
  const PAGINATION_DEFAULT_OFFSET = 0;
1316
1673
  function isCursorPaginationOptions(options) {
1317
- 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));
1318
1675
  }
1319
- const _RecordArray = class extends Array {
1676
+ class RecordArray extends Array {
1320
1677
  constructor(...args) {
1321
- super(..._RecordArray.parseConstructorParams(...args));
1322
- __privateAdd$6(this, _page, void 0);
1323
- __privateSet$6(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
1678
+ super(...RecordArray.parseConstructorParams(...args));
1324
1679
  }
1325
1680
  static parseConstructorParams(...args) {
1326
1681
  if (args.length === 1 && typeof args[0] === "number") {
1327
1682
  return new Array(args[0]);
1328
1683
  }
1329
- if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
1330
- const result = args[1] ?? args[0].records ?? [];
1684
+ if (args.length <= 1 && Array.isArray(args[0] ?? [])) {
1685
+ const result = args[0] ?? [];
1331
1686
  return new Array(...result);
1332
1687
  }
1333
1688
  return new Array(...args);
@@ -1335,79 +1690,139 @@ const _RecordArray = class extends Array {
1335
1690
  toArray() {
1336
1691
  return new Array(...this);
1337
1692
  }
1693
+ toSerializable() {
1694
+ return JSON.parse(this.toString());
1695
+ }
1696
+ toString() {
1697
+ return JSON.stringify(this.toArray());
1698
+ }
1338
1699
  map(callbackfn, thisArg) {
1339
1700
  return this.toArray().map(callbackfn, thisArg);
1340
1701
  }
1341
- async nextPage(size, offset) {
1342
- const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1343
- 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: [] });
1344
1708
  }
1345
- async previousPage(size, offset) {
1346
- const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1347
- 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);
1348
1718
  }
1349
- async firstPage(size, offset) {
1350
- const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1351
- return new _RecordArray(newPage);
1719
+ toArray() {
1720
+ return new Array(...this);
1721
+ }
1722
+ toSerializable() {
1723
+ return JSON.parse(this.toString());
1724
+ }
1725
+ toString() {
1726
+ return JSON.stringify(this.toArray());
1352
1727
  }
1353
- async lastPage(size, offset) {
1354
- const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1355
- return new _RecordArray(newPage);
1728
+ map(callbackfn, thisArg) {
1729
+ return this.toArray().map(callbackfn, thisArg);
1356
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
+ */
1357
1770
  hasNextPage() {
1358
- return __privateGet$6(this, _page).meta.page.more;
1771
+ return __privateGet$4(this, _page).meta.page.more;
1359
1772
  }
1360
1773
  };
1361
- let RecordArray = _RecordArray;
1362
1774
  _page = new WeakMap();
1775
+ let PageRecordArray = _PageRecordArray;
1363
1776
 
1364
- var __accessCheck$5 = (obj, member, msg) => {
1777
+ var __accessCheck$4 = (obj, member, msg) => {
1365
1778
  if (!member.has(obj))
1366
1779
  throw TypeError("Cannot " + msg);
1367
1780
  };
1368
- var __privateGet$5 = (obj, member, getter) => {
1369
- __accessCheck$5(obj, member, "read from private field");
1781
+ var __privateGet$3 = (obj, member, getter) => {
1782
+ __accessCheck$4(obj, member, "read from private field");
1370
1783
  return getter ? getter.call(obj) : member.get(obj);
1371
1784
  };
1372
- var __privateAdd$5 = (obj, member, value) => {
1785
+ var __privateAdd$4 = (obj, member, value) => {
1373
1786
  if (member.has(obj))
1374
1787
  throw TypeError("Cannot add the same private member more than once");
1375
1788
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1376
1789
  };
1377
- var __privateSet$5 = (obj, member, value, setter) => {
1378
- __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");
1379
1792
  setter ? setter.call(obj, value) : member.set(obj, value);
1380
1793
  return value;
1381
1794
  };
1382
1795
  var __privateMethod$3 = (obj, member, method) => {
1383
- __accessCheck$5(obj, member, "access private method");
1796
+ __accessCheck$4(obj, member, "access private method");
1384
1797
  return method;
1385
1798
  };
1386
1799
  var _table$1, _repository, _data, _cleanFilterConstraint, cleanFilterConstraint_fn;
1387
- const _Query = class {
1800
+ const _Query = class _Query {
1388
1801
  constructor(repository, table, data, rawParent) {
1389
- __privateAdd$5(this, _cleanFilterConstraint);
1390
- __privateAdd$5(this, _table$1, void 0);
1391
- __privateAdd$5(this, _repository, void 0);
1392
- __privateAdd$5(this, _data, { filter: {} });
1393
- this.meta = { page: { cursor: "start", more: true } };
1394
- this.records = new RecordArray(this, []);
1395
- __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);
1396
1810
  if (repository) {
1397
- __privateSet$5(this, _repository, repository);
1811
+ __privateSet$2(this, _repository, repository);
1398
1812
  } else {
1399
- __privateSet$5(this, _repository, this);
1813
+ __privateSet$2(this, _repository, this);
1400
1814
  }
1401
1815
  const parent = cleanParent(data, rawParent);
1402
- __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
1403
- __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
1404
- __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
1405
- __privateGet$5(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
1406
- __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1407
- __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1408
- __privateGet$5(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
1409
- __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1410
- __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;
1411
1826
  this.any = this.any.bind(this);
1412
1827
  this.all = this.all.bind(this);
1413
1828
  this.not = this.not.bind(this);
@@ -1418,59 +1833,90 @@ const _Query = class {
1418
1833
  Object.defineProperty(this, "repository", { enumerable: false });
1419
1834
  }
1420
1835
  getQueryOptions() {
1421
- return __privateGet$5(this, _data);
1836
+ return __privateGet$3(this, _data);
1422
1837
  }
1423
1838
  key() {
1424
- const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$5(this, _data);
1839
+ const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$3(this, _data);
1425
1840
  const key = JSON.stringify({ columns, filter, sort, pagination });
1426
1841
  return toBase64(key);
1427
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
+ */
1428
1848
  any(...queries) {
1429
1849
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
1430
- 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));
1431
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
+ */
1432
1857
  all(...queries) {
1433
1858
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
1434
- 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));
1435
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
+ */
1436
1866
  not(...queries) {
1437
1867
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
1438
- 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));
1439
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
+ */
1440
1875
  none(...queries) {
1441
1876
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
1442
- 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));
1443
1878
  }
1444
1879
  filter(a, b) {
1445
1880
  if (arguments.length === 1) {
1446
1881
  const constraints = Object.entries(a ?? {}).map(([column, constraint]) => ({
1447
1882
  [column]: __privateMethod$3(this, _cleanFilterConstraint, cleanFilterConstraint_fn).call(this, column, constraint)
1448
1883
  }));
1449
- const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1450
- 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));
1451
1886
  } else {
1452
1887
  const constraints = isDefined(a) && isDefined(b) ? [{ [a]: __privateMethod$3(this, _cleanFilterConstraint, cleanFilterConstraint_fn).call(this, a, b) }] : void 0;
1453
- const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1454
- 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));
1455
1890
  }
1456
1891
  }
1457
1892
  sort(column, direction = "asc") {
1458
- const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
1893
+ const originalSort = [__privateGet$3(this, _data).sort ?? []].flat();
1459
1894
  const sort = [...originalSort, { column, direction }];
1460
- 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));
1461
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
+ */
1462
1902
  select(columns) {
1463
1903
  return new _Query(
1464
- __privateGet$5(this, _repository),
1465
- __privateGet$5(this, _table$1),
1904
+ __privateGet$3(this, _repository),
1905
+ __privateGet$3(this, _table$1),
1466
1906
  { columns },
1467
- __privateGet$5(this, _data)
1907
+ __privateGet$3(this, _data)
1468
1908
  );
1469
1909
  }
1470
1910
  getPaginated(options = {}) {
1471
- const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
1472
- return __privateGet$5(this, _repository).query(query);
1473
- }
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
+ */
1474
1920
  async *[Symbol.asyncIterator]() {
1475
1921
  for await (const [record] of this.getIterator({ batchSize: 1 })) {
1476
1922
  yield record;
@@ -1500,7 +1946,7 @@ const _Query = class {
1500
1946
  if (page.hasNextPage() && options.pagination?.size === void 0) {
1501
1947
  console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1502
1948
  }
1503
- const array = new RecordArray(page, results.slice(0, size));
1949
+ const array = new PageRecordArray(page, results.slice(0, size));
1504
1950
  return array;
1505
1951
  }
1506
1952
  async getAll(options = {}) {
@@ -1509,7 +1955,7 @@ const _Query = class {
1509
1955
  for await (const page of this.getIterator({ ...rest, batchSize })) {
1510
1956
  results.push(...page);
1511
1957
  }
1512
- return results;
1958
+ return new RecordArray(results);
1513
1959
  }
1514
1960
  async getFirst(options = {}) {
1515
1961
  const records = await this.getMany({ ...options, pagination: { size: 1 } });
@@ -1521,32 +1967,61 @@ const _Query = class {
1521
1967
  throw new Error("No results found.");
1522
1968
  return records[0];
1523
1969
  }
1524
- cache(ttl) {
1525
- 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);
1526
1979
  }
1980
+ /**
1981
+ * Retrieve next page of records
1982
+ *
1983
+ * @returns A new page object.
1984
+ */
1527
1985
  nextPage(size, offset) {
1528
- return this.firstPage(size, offset);
1986
+ return this.startPage(size, offset);
1529
1987
  }
1988
+ /**
1989
+ * Retrieve previous page of records
1990
+ *
1991
+ * @returns A new page object
1992
+ */
1530
1993
  previousPage(size, offset) {
1531
- return this.firstPage(size, offset);
1532
- }
1533
- 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) {
1534
2002
  return this.getPaginated({ pagination: { size, offset } });
1535
2003
  }
1536
- lastPage(size, offset) {
2004
+ /**
2005
+ * Retrieve last page of records
2006
+ *
2007
+ * @returns A new page object
2008
+ */
2009
+ endPage(size, offset) {
1537
2010
  return this.getPaginated({ pagination: { size, offset, before: "end" } });
1538
2011
  }
2012
+ /**
2013
+ * @returns Boolean indicating if there is a next page
2014
+ */
1539
2015
  hasNextPage() {
1540
2016
  return this.meta.page.more;
1541
2017
  }
1542
2018
  };
1543
- let Query = _Query;
1544
2019
  _table$1 = new WeakMap();
1545
2020
  _repository = new WeakMap();
1546
2021
  _data = new WeakMap();
1547
2022
  _cleanFilterConstraint = new WeakSet();
1548
2023
  cleanFilterConstraint_fn = function(column, value) {
1549
- 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;
1550
2025
  if (columnType === "multiple" && (isString(value) || isStringArray(value))) {
1551
2026
  return { $includes: value };
1552
2027
  }
@@ -1555,27 +2030,60 @@ cleanFilterConstraint_fn = function(column, value) {
1555
2030
  }
1556
2031
  return value;
1557
2032
  };
2033
+ let Query = _Query;
1558
2034
  function cleanParent(data, parent) {
1559
2035
  if (isCursorPaginationOptions(data.pagination)) {
1560
- return { ...parent, sorting: void 0, filter: void 0 };
2036
+ return { ...parent, sort: void 0, filter: void 0 };
1561
2037
  }
1562
2038
  return parent;
1563
2039
  }
1564
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
+ ];
1565
2056
  function isIdentifiable(x) {
1566
- return isObject(x) && isString(x?.id);
2057
+ return isObject(x) && isString(x?.xata_id);
2058
+ }
2059
+
2060
+ function isValidExpandedColumn(column) {
2061
+ return isObject(column) && isString(column.name);
1567
2062
  }
1568
- function isXataRecord(x) {
1569
- const record = x;
1570
- const metadata = record?.getMetadata();
1571
- return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
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
+ });
1572
2076
  }
1573
2077
 
1574
2078
  function isSortFilterString(value) {
1575
2079
  return isString(value);
1576
2080
  }
1577
2081
  function isSortFilterBase(filter) {
1578
- 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
+ });
1579
2087
  }
1580
2088
  function isSortFilterObject(filter) {
1581
2089
  return isObject(filter) && !isSortFilterBase(filter) && filter.column !== void 0;
@@ -1594,29 +2102,30 @@ function buildSortFilter(filter) {
1594
2102
  }
1595
2103
  }
1596
2104
 
1597
- var __accessCheck$4 = (obj, member, msg) => {
2105
+ var __accessCheck$3 = (obj, member, msg) => {
1598
2106
  if (!member.has(obj))
1599
2107
  throw TypeError("Cannot " + msg);
1600
2108
  };
1601
- var __privateGet$4 = (obj, member, getter) => {
1602
- __accessCheck$4(obj, member, "read from private field");
2109
+ var __privateGet$2 = (obj, member, getter) => {
2110
+ __accessCheck$3(obj, member, "read from private field");
1603
2111
  return getter ? getter.call(obj) : member.get(obj);
1604
2112
  };
1605
- var __privateAdd$4 = (obj, member, value) => {
2113
+ var __privateAdd$3 = (obj, member, value) => {
1606
2114
  if (member.has(obj))
1607
2115
  throw TypeError("Cannot add the same private member more than once");
1608
2116
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1609
2117
  };
1610
- var __privateSet$4 = (obj, member, value, setter) => {
1611
- __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");
1612
2120
  setter ? setter.call(obj, value) : member.set(obj, value);
1613
2121
  return value;
1614
2122
  };
1615
2123
  var __privateMethod$2 = (obj, member, method) => {
1616
- __accessCheck$4(obj, member, "access private method");
2124
+ __accessCheck$3(obj, member, "access private method");
1617
2125
  return method;
1618
2126
  };
1619
- 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;
1620
2129
  class Repository extends Query {
1621
2130
  }
1622
2131
  class RestRepository extends Query {
@@ -1626,93 +2135,104 @@ class RestRepository extends Query {
1626
2135
  { name: options.table, schema: options.schemaTables?.find((table) => table.name === options.table) },
1627
2136
  {}
1628
2137
  );
1629
- __privateAdd$4(this, _insertRecordWithoutId);
1630
- __privateAdd$4(this, _insertRecordWithId);
1631
- __privateAdd$4(this, _bulkInsertTableRecords);
1632
- __privateAdd$4(this, _updateRecordWithID);
1633
- __privateAdd$4(this, _upsertRecordWithID);
1634
- __privateAdd$4(this, _deleteRecord);
1635
- __privateAdd$4(this, _setCacheQuery);
1636
- __privateAdd$4(this, _getCacheQuery);
1637
- __privateAdd$4(this, _getSchemaTables$1);
1638
- __privateAdd$4(this, _table, void 0);
1639
- __privateAdd$4(this, _getFetchProps, void 0);
1640
- __privateAdd$4(this, _db, void 0);
1641
- __privateAdd$4(this, _cache, void 0);
1642
- __privateAdd$4(this, _schemaTables$2, void 0);
1643
- __privateAdd$4(this, _trace, void 0);
1644
- __privateSet$4(this, _table, options.table);
1645
- __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1646
- __privateSet$4(this, _db, options.db);
1647
- __privateSet$4(this, _cache, options.pluginOptions.cache);
1648
- __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() }));
1649
2157
  const trace = options.pluginOptions.trace ?? defaultTrace;
1650
- __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
2158
+ __privateSet$1(this, _trace, async (name, fn, options2 = {}) => {
1651
2159
  return trace(name, fn, {
1652
2160
  ...options2,
1653
- [TraceAttributes.TABLE]: __privateGet$4(this, _table),
2161
+ [TraceAttributes.TABLE]: __privateGet$2(this, _table),
1654
2162
  [TraceAttributes.KIND]: "sdk-operation",
1655
2163
  [TraceAttributes.VERSION]: VERSION
1656
2164
  });
1657
2165
  });
1658
2166
  }
1659
- async create(a, b, c) {
1660
- 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);
1661
2170
  if (Array.isArray(a)) {
1662
2171
  if (a.length === 0)
1663
2172
  return [];
1664
- const columns = isStringArray(b) ? b : void 0;
1665
- 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;
1666
2177
  }
1667
2178
  if (isString(a) && isObject(b)) {
1668
2179
  if (a === "")
1669
2180
  throw new Error("The id can't be empty");
1670
- const columns = isStringArray(c) ? c : void 0;
1671
- 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 });
1672
2183
  }
1673
- if (isObject(a) && isString(a.id)) {
1674
- if (a.id === "")
2184
+ if (isObject(a) && isString(a.xata_id)) {
2185
+ if (a.xata_id === "")
1675
2186
  throw new Error("The id can't be empty");
1676
- const columns = isStringArray(b) ? b : void 0;
1677
- 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
+ });
1678
2192
  }
1679
2193
  if (isObject(a)) {
1680
- const columns = isStringArray(b) ? b : void 0;
2194
+ const columns = isValidSelectableColumns(b) ? b : void 0;
1681
2195
  return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
1682
2196
  }
1683
2197
  throw new Error("Invalid arguments for create method");
1684
2198
  });
1685
2199
  }
1686
2200
  async read(a, b) {
1687
- return __privateGet$4(this, _trace).call(this, "read", async () => {
1688
- const columns = isStringArray(b) ? b : ["*"];
2201
+ return __privateGet$2(this, _trace).call(this, "read", async () => {
2202
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
1689
2203
  if (Array.isArray(a)) {
1690
2204
  if (a.length === 0)
1691
2205
  return [];
1692
2206
  const ids = a.map((item) => extractId(item));
1693
- const finalObjects = await this.getAll({ filter: { id: { $any: compact(ids) } }, columns });
2207
+ const finalObjects = await this.getAll({ filter: { xata_id: { $any: compact(ids) } }, columns });
1694
2208
  const dictionary = finalObjects.reduce((acc, object) => {
1695
- acc[object.id] = object;
2209
+ acc[object.xata_id] = object;
1696
2210
  return acc;
1697
2211
  }, {});
1698
2212
  return ids.map((id2) => dictionary[id2 ?? ""] ?? null);
1699
2213
  }
1700
2214
  const id = extractId(a);
1701
2215
  if (id) {
1702
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1703
2216
  try {
1704
2217
  const response = await getRecord({
1705
2218
  pathParams: {
1706
2219
  workspace: "{workspaceId}",
1707
2220
  dbBranchName: "{dbBranch}",
1708
- tableName: __privateGet$4(this, _table),
2221
+ region: "{region}",
2222
+ tableName: __privateGet$2(this, _table),
1709
2223
  recordId: id
1710
2224
  },
1711
2225
  queryParams: { columns },
1712
- ...fetchProps
2226
+ ...__privateGet$2(this, _getFetchProps).call(this)
1713
2227
  });
1714
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1715
- 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
+ );
1716
2236
  } catch (e) {
1717
2237
  if (isObject(e) && e.status === 404) {
1718
2238
  return null;
@@ -1724,7 +2244,7 @@ class RestRepository extends Query {
1724
2244
  });
1725
2245
  }
1726
2246
  async readOrThrow(a, b) {
1727
- return __privateGet$4(this, _trace).call(this, "readOrThrow", async () => {
2247
+ return __privateGet$2(this, _trace).call(this, "readOrThrow", async () => {
1728
2248
  const result = await this.read(a, b);
1729
2249
  if (Array.isArray(result)) {
1730
2250
  const missingIds = compact(
@@ -1742,31 +2262,42 @@ class RestRepository extends Query {
1742
2262
  return result;
1743
2263
  });
1744
2264
  }
1745
- async update(a, b, c) {
1746
- 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);
1747
2268
  if (Array.isArray(a)) {
1748
2269
  if (a.length === 0)
1749
2270
  return [];
1750
- if (a.length > 100) {
1751
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1752
- }
1753
- const columns = isStringArray(b) ? b : ["*"];
1754
- return Promise.all(a.map((object) => this.update(object, columns)));
1755
- }
1756
- if (isString(a) && isObject(b)) {
1757
- const columns = isStringArray(c) ? c : void 0;
1758
- 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;
1759
2280
  }
1760
- if (isObject(a) && isString(a.id)) {
1761
- const columns = isStringArray(b) ? b : void 0;
1762
- 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;
1763
2294
  }
1764
2295
  throw new Error("Invalid arguments for update method");
1765
2296
  });
1766
2297
  }
1767
- async updateOrThrow(a, b, c) {
1768
- return __privateGet$4(this, _trace).call(this, "updateOrThrow", async () => {
1769
- 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);
1770
2301
  if (Array.isArray(result)) {
1771
2302
  const missingIds = compact(
1772
2303
  a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
@@ -1780,52 +2311,107 @@ class RestRepository extends Query {
1780
2311
  const id = extractId(a) ?? "unknown";
1781
2312
  throw new Error(`Record with id ${id} not found`);
1782
2313
  }
1783
- return result;
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 });
2342
+ }
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");
1784
2350
  });
1785
2351
  }
1786
- async createOrUpdate(a, b, c) {
1787
- 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);
1788
2355
  if (Array.isArray(a)) {
1789
2356
  if (a.length === 0)
1790
2357
  return [];
1791
- if (a.length > 100) {
1792
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1793
- }
1794
- const columns = isStringArray(b) ? b : ["*"];
1795
- 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;
1796
2362
  }
1797
2363
  if (isString(a) && isObject(b)) {
1798
- const columns = isStringArray(c) ? c : void 0;
1799
- 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 });
1800
2368
  }
1801
- if (isObject(a) && isString(a.id)) {
1802
- const columns = isStringArray(c) ? c : void 0;
1803
- 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
+ });
1804
2377
  }
1805
- 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");
1806
2385
  });
1807
2386
  }
1808
2387
  async delete(a, b) {
1809
- return __privateGet$4(this, _trace).call(this, "delete", async () => {
2388
+ return __privateGet$2(this, _trace).call(this, "delete", async () => {
1810
2389
  if (Array.isArray(a)) {
1811
2390
  if (a.length === 0)
1812
2391
  return [];
1813
- if (a.length > 100) {
1814
- console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1815
- }
1816
- 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;
1817
2403
  }
1818
2404
  if (isString(a)) {
1819
2405
  return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
1820
2406
  }
1821
- if (isObject(a) && isString(a.id)) {
1822
- 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);
1823
2409
  }
1824
2410
  throw new Error("Invalid arguments for delete method");
1825
2411
  });
1826
2412
  }
1827
2413
  async deleteOrThrow(a, b) {
1828
- return __privateGet$4(this, _trace).call(this, "deleteOrThrow", async () => {
2414
+ return __privateGet$2(this, _trace).call(this, "deleteOrThrow", async () => {
1829
2415
  const result = await this.delete(a, b);
1830
2416
  if (Array.isArray(result)) {
1831
2417
  const missingIds = compact(
@@ -1843,121 +2429,261 @@ class RestRepository extends Query {
1843
2429
  });
1844
2430
  }
1845
2431
  async search(query, options = {}) {
1846
- return __privateGet$4(this, _trace).call(this, "search", async () => {
1847
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1848
- const { records } = await searchTable({
1849
- 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
+ },
1850
2440
  body: {
1851
2441
  query,
1852
2442
  fuzziness: options.fuzziness,
1853
2443
  prefix: options.prefix,
1854
2444
  highlight: options.highlight,
1855
2445
  filter: options.filter,
1856
- 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
2474
+ },
2475
+ ...__privateGet$2(this, _getFetchProps).call(this)
2476
+ });
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
+ };
2482
+ });
2483
+ }
2484
+ async aggregate(aggs, filter) {
2485
+ return __privateGet$2(this, _trace).call(this, "aggregate", async () => {
2486
+ const result = await aggregateTable({
2487
+ pathParams: {
2488
+ workspace: "{workspaceId}",
2489
+ dbBranchName: "{dbBranch}",
2490
+ region: "{region}",
2491
+ tableName: __privateGet$2(this, _table)
1857
2492
  },
1858
- ...fetchProps
2493
+ body: { aggs, filter },
2494
+ ...__privateGet$2(this, _getFetchProps).call(this)
1859
2495
  });
1860
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1861
- return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
2496
+ return result;
1862
2497
  });
1863
2498
  }
1864
2499
  async query(query) {
1865
- return __privateGet$4(this, _trace).call(this, "query", async () => {
1866
- const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1867
- if (cacheQuery)
1868
- return new Page(query, cacheQuery.meta, cacheQuery.records);
2500
+ return __privateGet$2(this, _trace).call(this, "query", async () => {
1869
2501
  const data = query.getQueryOptions();
1870
- const body = {
1871
- filter: cleanFilter(data.filter),
1872
- sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1873
- page: data.pagination,
1874
- columns: data.columns
1875
- };
1876
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1877
2502
  const { meta, records: objects } = await queryTable({
1878
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1879
- body,
1880
- ...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)
1881
2518
  });
1882
- 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);
1883
2520
  const records = objects.map(
1884
- (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
+ )
1885
2528
  );
1886
- await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1887
2529
  return new Page(query, meta, records);
1888
2530
  });
1889
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
+ }
1890
2595
  }
1891
2596
  _table = new WeakMap();
1892
2597
  _getFetchProps = new WeakMap();
1893
2598
  _db = new WeakMap();
1894
- _cache = new WeakMap();
1895
- _schemaTables$2 = new WeakMap();
2599
+ _schemaTables = new WeakMap();
1896
2600
  _trace = new WeakMap();
1897
2601
  _insertRecordWithoutId = new WeakSet();
1898
2602
  insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1899
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1900
- const record = transformObjectLinks(object);
2603
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2604
+ console.log("record", record);
1901
2605
  const response = await insertRecord({
1902
2606
  pathParams: {
1903
2607
  workspace: "{workspaceId}",
1904
2608
  dbBranchName: "{dbBranch}",
1905
- tableName: __privateGet$4(this, _table)
2609
+ region: "{region}",
2610
+ tableName: __privateGet$2(this, _table)
1906
2611
  },
1907
2612
  queryParams: { columns },
1908
2613
  body: record,
1909
- ...fetchProps
2614
+ ...__privateGet$2(this, _getFetchProps).call(this)
1910
2615
  });
1911
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1912
- 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);
1913
2618
  };
1914
2619
  _insertRecordWithId = new WeakSet();
1915
- insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
1916
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1917
- 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);
1918
2624
  const response = await insertRecordWithID({
1919
2625
  pathParams: {
1920
2626
  workspace: "{workspaceId}",
1921
2627
  dbBranchName: "{dbBranch}",
1922
- tableName: __privateGet$4(this, _table),
2628
+ region: "{region}",
2629
+ tableName: __privateGet$2(this, _table),
1923
2630
  recordId
1924
2631
  },
1925
2632
  body: record,
1926
- queryParams: { createOnly: true, columns },
1927
- ...fetchProps
2633
+ queryParams: { createOnly, columns, ifVersion },
2634
+ ...__privateGet$2(this, _getFetchProps).call(this)
1928
2635
  });
1929
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1930
- 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);
1931
2638
  };
1932
- _bulkInsertTableRecords = new WeakSet();
1933
- bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
1934
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1935
- const records = objects.map((object) => transformObjectLinks(object));
1936
- const response = await bulkInsertTableRecords({
1937
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1938
- queryParams: { columns },
1939
- body: { records },
1940
- ...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 } };
1941
2644
  });
1942
- if (!isResponseWithRecords(response)) {
1943
- 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
+ }
1944
2664
  }
1945
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1946
- return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, columns));
2665
+ return ids;
1947
2666
  };
1948
2667
  _updateRecordWithID = new WeakSet();
1949
- updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1950
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1951
- 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);
1952
2672
  try {
1953
2673
  const response = await updateRecordWithID({
1954
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1955
- 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 },
1956
2682
  body: record,
1957
- ...fetchProps
2683
+ ...__privateGet$2(this, _getFetchProps).call(this)
1958
2684
  });
1959
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1960
- 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);
1961
2687
  } catch (e) {
1962
2688
  if (isObject(e) && e.status === 404) {
1963
2689
  return null;
@@ -1965,29 +2691,71 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1965
2691
  throw e;
1966
2692
  }
1967
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
+ };
1968
2722
  _upsertRecordWithID = new WeakSet();
1969
- upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1970
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2723
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2724
+ if (!recordId)
2725
+ return null;
1971
2726
  const response = await upsertRecordWithID({
1972
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1973
- 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 },
1974
2735
  body: object,
1975
- ...fetchProps
2736
+ ...__privateGet$2(this, _getFetchProps).call(this)
1976
2737
  });
1977
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1978
- 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);
1979
2740
  };
1980
2741
  _deleteRecord = new WeakSet();
1981
2742
  deleteRecord_fn = async function(recordId, columns = ["*"]) {
1982
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2743
+ if (!recordId)
2744
+ return null;
1983
2745
  try {
1984
2746
  const response = await deleteRecord({
1985
- 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
+ },
1986
2754
  queryParams: { columns },
1987
- ...fetchProps
2755
+ ...__privateGet$2(this, _getFetchProps).call(this)
1988
2756
  });
1989
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1990
- 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);
1991
2759
  } catch (e) {
1992
2760
  if (isObject(e) && e.status === 404) {
1993
2761
  return null;
@@ -1995,59 +2763,87 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
1995
2763
  throw e;
1996
2764
  }
1997
2765
  };
1998
- _setCacheQuery = new WeakSet();
1999
- setCacheQuery_fn = async function(query, meta, records) {
2000
- await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
2001
- };
2002
- _getCacheQuery = new WeakSet();
2003
- getCacheQuery_fn = async function(query) {
2004
- const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
2005
- const result = await __privateGet$4(this, _cache).get(key);
2006
- if (!result)
2007
- return null;
2008
- const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
2009
- if (ttl < 0)
2010
- return null;
2011
- const hasExpired = result.date.getTime() + ttl < Date.now();
2012
- 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
+ }
2013
2783
  };
2014
- _getSchemaTables$1 = new WeakSet();
2015
- getSchemaTables_fn$1 = async function() {
2016
- if (__privateGet$4(this, _schemaTables$2))
2017
- return __privateGet$4(this, _schemaTables$2);
2018
- 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);
2019
2788
  const { schema } = await getBranchDetails({
2020
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
2021
- ...fetchProps
2789
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
2790
+ ...__privateGet$2(this, _getFetchProps).call(this)
2022
2791
  });
2023
- __privateSet$4(this, _schemaTables$2, schema.tables);
2792
+ __privateSet$1(this, _schemaTables, schema.tables);
2024
2793
  return schema.tables;
2025
2794
  };
2026
- const transformObjectLinks = (object) => {
2027
- return Object.entries(object).reduce((acc, [key, value]) => {
2028
- if (key === "xata")
2029
- return acc;
2030
- return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
2031
- }, {});
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;
2032
2829
  };
2033
2830
  const initObject = (db, schemaTables, table, object, selectedColumns) => {
2034
- const result = {};
2035
- const { xata, ...rest } = object ?? {};
2036
- Object.assign(result, rest);
2831
+ const data = {};
2832
+ Object.assign(data, { ...object });
2037
2833
  const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
2038
2834
  if (!columns)
2039
2835
  console.error(`Table ${table} not found in schema`);
2040
2836
  for (const column of columns ?? []) {
2041
2837
  if (!isValidColumn(selectedColumns, column))
2042
2838
  continue;
2043
- const value = result[column.name];
2839
+ const value = data[column.name];
2044
2840
  switch (column.type) {
2045
2841
  case "datetime": {
2046
- const date = value !== void 0 ? new Date(value) : void 0;
2047
- if (date && isNaN(date.getTime())) {
2842
+ const date = value !== void 0 ? new Date(value) : null;
2843
+ if (date !== null && isNaN(date.getTime())) {
2048
2844
  console.error(`Failed to parse date ${value} for field ${column.name}`);
2049
- } else if (date) {
2050
- result[column.name] = date;
2845
+ } else {
2846
+ data[column.name] = date;
2051
2847
  }
2052
2848
  break;
2053
2849
  }
@@ -2060,118 +2856,90 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
2060
2856
  if (item === column.name) {
2061
2857
  return [...acc, "*"];
2062
2858
  }
2063
- if (item.startsWith(`${column.name}.`)) {
2859
+ if (isString(item) && item.startsWith(`${column.name}.`)) {
2064
2860
  const [, ...path] = item.split(".");
2065
2861
  return [...acc, path.join(".")];
2066
2862
  }
2067
2863
  return acc;
2068
2864
  }, []);
2069
- 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
+ );
2070
2872
  } else {
2071
- result[column.name] = null;
2873
+ data[column.name] = null;
2072
2874
  }
2073
2875
  break;
2074
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;
2075
2886
  default:
2076
- result[column.name] = value ?? null;
2887
+ data[column.name] = value ?? null;
2077
2888
  if (column.notNull === true && value === null) {
2078
2889
  console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
2079
2890
  }
2080
2891
  break;
2081
2892
  }
2082
2893
  }
2083
- result.read = function(columns2) {
2084
- 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 });
2085
2902
  };
2086
- result.update = function(data, columns2) {
2087
- 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 });
2088
2907
  };
2089
- result.delete = function() {
2090
- return db[table].delete(result["id"]);
2908
+ record.delete = function() {
2909
+ return db[table].delete(record["xata_id"]);
2091
2910
  };
2092
- result.getMetadata = function() {
2093
- return xata;
2911
+ record.toSerializable = function() {
2912
+ return JSON.parse(JSON.stringify(record));
2094
2913
  };
2095
- for (const prop of ["read", "update", "delete", "getMetadata"]) {
2096
- 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 });
2097
2919
  }
2098
- Object.freeze(result);
2099
- return result;
2920
+ Object.freeze(record);
2921
+ return record;
2100
2922
  };
2101
- function isResponseWithRecords(value) {
2102
- return isObject(value) && Array.isArray(value.records);
2103
- }
2104
2923
  function extractId(value) {
2105
2924
  if (isString(value))
2106
2925
  return value;
2107
- if (isObject(value) && isString(value.id))
2108
- return value.id;
2926
+ if (isObject(value) && isString(value.xata_id))
2927
+ return value.xata_id;
2109
2928
  return void 0;
2110
2929
  }
2111
- function cleanFilter(filter) {
2112
- if (!filter)
2113
- return void 0;
2114
- const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
2115
- return values.length > 0 ? filter : void 0;
2116
- }
2117
2930
  function isValidColumn(columns, column) {
2118
2931
  if (columns.includes("*"))
2119
2932
  return true;
2120
- if (column.type === "link") {
2121
- const linkColumns = columns.filter((item) => item.startsWith(column.name));
2122
- return linkColumns.length > 0;
2123
- }
2124
- return columns.includes(column.name);
2933
+ return columns.filter((item) => isString(item) && item.startsWith(column.name)).length > 0;
2125
2934
  }
2126
-
2127
- var __accessCheck$3 = (obj, member, msg) => {
2128
- if (!member.has(obj))
2129
- throw TypeError("Cannot " + msg);
2130
- };
2131
- var __privateGet$3 = (obj, member, getter) => {
2132
- __accessCheck$3(obj, member, "read from private field");
2133
- return getter ? getter.call(obj) : member.get(obj);
2134
- };
2135
- var __privateAdd$3 = (obj, member, value) => {
2136
- if (member.has(obj))
2137
- throw TypeError("Cannot add the same private member more than once");
2138
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
2139
- };
2140
- var __privateSet$3 = (obj, member, value, setter) => {
2141
- __accessCheck$3(obj, member, "write to private field");
2142
- setter ? setter.call(obj, value) : member.set(obj, value);
2143
- return value;
2144
- };
2145
- var _map;
2146
- class SimpleCache {
2147
- constructor(options = {}) {
2148
- __privateAdd$3(this, _map, void 0);
2149
- __privateSet$3(this, _map, /* @__PURE__ */ new Map());
2150
- this.capacity = options.max ?? 500;
2151
- this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
2152
- }
2153
- async getAll() {
2154
- return Object.fromEntries(__privateGet$3(this, _map));
2155
- }
2156
- async get(key) {
2157
- return __privateGet$3(this, _map).get(key) ?? null;
2158
- }
2159
- async set(key, value) {
2160
- await this.delete(key);
2161
- __privateGet$3(this, _map).set(key, value);
2162
- if (__privateGet$3(this, _map).size > this.capacity) {
2163
- const leastRecentlyUsed = __privateGet$3(this, _map).keys().next().value;
2164
- 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;
2165
2939
  }
2166
2940
  }
2167
- async delete(key) {
2168
- __privateGet$3(this, _map).delete(key);
2169
- }
2170
- async clear() {
2171
- return __privateGet$3(this, _map).clear();
2172
- }
2941
+ return void 0;
2173
2942
  }
2174
- _map = new WeakMap();
2175
2943
 
2176
2944
  const greaterThan = (value) => ({ $gt: value });
2177
2945
  const gt = greaterThan;
@@ -2190,10 +2958,12 @@ const notExists = (column) => ({ $notExists: column });
2190
2958
  const startsWith = (value) => ({ $startsWith: value });
2191
2959
  const endsWith = (value) => ({ $endsWith: value });
2192
2960
  const pattern = (value) => ({ $pattern: value });
2961
+ const iPattern = (value) => ({ $iPattern: value });
2193
2962
  const is = (value) => ({ $is: value });
2194
2963
  const equals = is;
2195
2964
  const isNot = (value) => ({ $isNot: value });
2196
2965
  const contains = (value) => ({ $contains: value });
2966
+ const iContains = (value) => ({ $iContains: value });
2197
2967
  const includes = (value) => ({ $includes: value });
2198
2968
  const includesAll = (value) => ({ $includesAll: value });
2199
2969
  const includesNone = (value) => ({ $includesNone: value });
@@ -2203,7 +2973,7 @@ var __accessCheck$2 = (obj, member, msg) => {
2203
2973
  if (!member.has(obj))
2204
2974
  throw TypeError("Cannot " + msg);
2205
2975
  };
2206
- var __privateGet$2 = (obj, member, getter) => {
2976
+ var __privateGet$1 = (obj, member, getter) => {
2207
2977
  __accessCheck$2(obj, member, "read from private field");
2208
2978
  return getter ? getter.call(obj) : member.get(obj);
2209
2979
  };
@@ -2212,18 +2982,11 @@ var __privateAdd$2 = (obj, member, value) => {
2212
2982
  throw TypeError("Cannot add the same private member more than once");
2213
2983
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
2214
2984
  };
2215
- var __privateSet$2 = (obj, member, value, setter) => {
2216
- __accessCheck$2(obj, member, "write to private field");
2217
- setter ? setter.call(obj, value) : member.set(obj, value);
2218
- return value;
2219
- };
2220
- var _tables, _schemaTables$1;
2985
+ var _tables;
2221
2986
  class SchemaPlugin extends XataPlugin {
2222
- constructor(schemaTables) {
2987
+ constructor() {
2223
2988
  super();
2224
2989
  __privateAdd$2(this, _tables, {});
2225
- __privateAdd$2(this, _schemaTables$1, void 0);
2226
- __privateSet$2(this, _schemaTables$1, schemaTables);
2227
2990
  }
2228
2991
  build(pluginOptions) {
2229
2992
  const db = new Proxy(
@@ -2232,182 +2995,251 @@ class SchemaPlugin extends XataPlugin {
2232
2995
  get: (_target, table) => {
2233
2996
  if (!isString(table))
2234
2997
  throw new Error("Invalid table name");
2235
- if (__privateGet$2(this, _tables)[table] === void 0) {
2236
- __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 });
2237
3000
  }
2238
- return __privateGet$2(this, _tables)[table];
3001
+ return __privateGet$1(this, _tables)[table];
2239
3002
  }
2240
3003
  }
2241
3004
  );
2242
- const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
3005
+ const tableNames = pluginOptions.tables?.map(({ name }) => name) ?? [];
2243
3006
  for (const table of tableNames) {
2244
- db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
3007
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: pluginOptions.tables });
2245
3008
  }
2246
3009
  return db;
2247
3010
  }
2248
3011
  }
2249
3012
  _tables = new WeakMap();
2250
- _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
+ }
2251
3087
 
2252
3088
  var __accessCheck$1 = (obj, member, msg) => {
2253
3089
  if (!member.has(obj))
2254
3090
  throw TypeError("Cannot " + msg);
2255
3091
  };
2256
- var __privateGet$1 = (obj, member, getter) => {
2257
- __accessCheck$1(obj, member, "read from private field");
2258
- return getter ? getter.call(obj) : member.get(obj);
2259
- };
2260
3092
  var __privateAdd$1 = (obj, member, value) => {
2261
3093
  if (member.has(obj))
2262
3094
  throw TypeError("Cannot add the same private member more than once");
2263
3095
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
2264
3096
  };
2265
- var __privateSet$1 = (obj, member, value, setter) => {
2266
- __accessCheck$1(obj, member, "write to private field");
2267
- setter ? setter.call(obj, value) : member.set(obj, value);
2268
- return value;
2269
- };
2270
3097
  var __privateMethod$1 = (obj, member, method) => {
2271
3098
  __accessCheck$1(obj, member, "access private method");
2272
3099
  return method;
2273
3100
  };
2274
- var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
3101
+ var _search, search_fn;
2275
3102
  class SearchPlugin extends XataPlugin {
2276
- constructor(db, schemaTables) {
3103
+ constructor(db) {
2277
3104
  super();
2278
3105
  this.db = db;
2279
3106
  __privateAdd$1(this, _search);
2280
- __privateAdd$1(this, _getSchemaTables);
2281
- __privateAdd$1(this, _schemaTables, void 0);
2282
- __privateSet$1(this, _schemaTables, schemaTables);
2283
3107
  }
2284
- build({ getFetchProps }) {
3108
+ build(pluginOptions) {
2285
3109
  return {
2286
3110
  all: async (query, options = {}) => {
2287
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
2288
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
2289
- return records.map((record) => {
2290
- const { table = "orphan" } = record.xata;
2291
- return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
2292
- });
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
+ };
2293
3119
  },
2294
3120
  byTable: async (query, options = {}) => {
2295
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
2296
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
2297
- 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) => {
2298
3123
  const { table = "orphan" } = record.xata;
2299
3124
  const items = acc[table] ?? [];
2300
- const item = initObject(this.db, schemaTables, table, record, ["*"]);
3125
+ const item = initObject(this.db, pluginOptions.tables, table, record, ["*"]);
2301
3126
  return { ...acc, [table]: [...items, item] };
2302
3127
  }, {});
3128
+ return { totalCount, records };
2303
3129
  }
2304
3130
  };
2305
3131
  }
2306
3132
  }
2307
- _schemaTables = new WeakMap();
2308
3133
  _search = new WeakSet();
2309
- search_fn = async function(query, options, getFetchProps) {
2310
- const fetchProps = await getFetchProps();
2311
- const { tables, fuzziness, highlight, prefix } = options ?? {};
2312
- const { records } = await searchBranch({
2313
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
2314
- body: { tables, query, fuzziness, prefix, highlight },
2315
- ...fetchProps
2316
- });
2317
- return records;
2318
- };
2319
- _getSchemaTables = new WeakSet();
2320
- getSchemaTables_fn = async function(getFetchProps) {
2321
- if (__privateGet$1(this, _schemaTables))
2322
- return __privateGet$1(this, _schemaTables);
2323
- const fetchProps = await getFetchProps();
2324
- const { schema } = await getBranchDetails({
2325
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
2326
- ...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
2327
3141
  });
2328
- __privateSet$1(this, _schemaTables, schema.tables);
2329
- return schema.tables;
3142
+ return { records, totalCount };
2330
3143
  };
2331
3144
 
2332
- const isBranchStrategyBuilder = (strategy) => {
2333
- return typeof strategy === "function";
2334
- };
2335
-
2336
- async function getCurrentBranchName(options) {
2337
- const { branch, envBranch } = getEnvironment();
2338
- if (branch) {
2339
- const details = await getDatabaseBranch(branch, options);
2340
- if (details)
2341
- return branch;
2342
- console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
2343
- }
2344
- const gitBranch = envBranch || await getGitBranch();
2345
- return resolveXataBranch(gitBranch, options);
2346
- }
2347
- async function getCurrentBranchDetails(options) {
2348
- const branch = await getCurrentBranchName(options);
2349
- return getDatabaseBranch(branch, options);
2350
- }
2351
- async function resolveXataBranch(gitBranch, options) {
2352
- const databaseURL = options?.databaseURL || getDatabaseURL();
2353
- const apiKey = options?.apiKey || getAPIKey();
2354
- if (!databaseURL)
2355
- throw new Error(
2356
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2357
- );
2358
- if (!apiKey)
2359
- throw new Error(
2360
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2361
- );
2362
- const [protocol, , host, , dbName] = databaseURL.split("/");
2363
- const [workspace] = host.split(".");
2364
- const { fallbackBranch } = getEnvironment();
2365
- const { branch } = await resolveBranch({
2366
- apiKey,
2367
- apiUrl: databaseURL,
2368
- fetchImpl: getFetchImplementation(options?.fetchImpl),
2369
- workspacesApiUrl: `${protocol}//${host}`,
2370
- pathParams: { dbName, workspace },
2371
- queryParams: { gitBranch, fallbackBranch },
2372
- trace: defaultTrace
2373
- });
2374
- return branch;
2375
- }
2376
- async function getDatabaseBranch(branch, options) {
2377
- const databaseURL = options?.databaseURL || getDatabaseURL();
2378
- const apiKey = options?.apiKey || getAPIKey();
2379
- if (!databaseURL)
2380
- throw new Error(
2381
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2382
- );
2383
- if (!apiKey)
2384
- throw new Error(
2385
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2386
- );
2387
- const [protocol, , host, , database] = databaseURL.split("/");
2388
- const [workspace] = host.split(".");
2389
- const dbBranchName = `${database}:${branch}`;
2390
- try {
2391
- return await getBranchDetails({
2392
- apiKey,
2393
- apiUrl: databaseURL,
2394
- fetchImpl: getFetchImplementation(options?.fetchImpl),
2395
- workspacesApiUrl: `${protocol}//${host}`,
2396
- pathParams: { dbBranchName, workspace },
2397
- trace: defaultTrace
2398
- });
2399
- } catch (err) {
2400
- if (isObject(err) && err.status === 404)
2401
- return null;
2402
- 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
+ }
2403
3164
  }
3165
+ result = result + "}";
3166
+ return result;
2404
3167
  }
2405
- 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
+ }
2406
3180
  try {
2407
- const { databaseURL } = getEnvironment();
2408
- return databaseURL;
2409
- } catch (err) {
2410
- 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
+ };
2411
3243
  }
2412
3244
  }
2413
3245
 
@@ -2434,88 +3266,119 @@ var __privateMethod = (obj, member, method) => {
2434
3266
  return method;
2435
3267
  };
2436
3268
  const buildClient = (plugins) => {
2437
- var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
3269
+ var _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _a;
2438
3270
  return _a = class {
2439
- constructor(options = {}, schemaTables) {
3271
+ constructor(options = {}, tables) {
2440
3272
  __privateAdd(this, _parseOptions);
2441
3273
  __privateAdd(this, _getFetchProps);
2442
- __privateAdd(this, _evaluateBranch);
2443
- __privateAdd(this, _branch, void 0);
2444
3274
  __privateAdd(this, _options, void 0);
2445
3275
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
2446
3276
  __privateSet(this, _options, safeOptions);
2447
3277
  const pluginOptions = {
2448
- getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
2449
- cache: safeOptions.cache,
2450
- trace: safeOptions.trace
3278
+ ...__privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
3279
+ host: safeOptions.host,
3280
+ tables
2451
3281
  };
2452
- const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2453
- 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 };
2454
3288
  this.db = db;
2455
3289
  this.search = search;
3290
+ this.transactions = transactions;
3291
+ this.sql = sql;
3292
+ this.files = files;
2456
3293
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
2457
3294
  if (namespace === void 0)
2458
3295
  continue;
2459
- const result = namespace.build(pluginOptions);
2460
- if (result instanceof Promise) {
2461
- void result.then((namespace2) => {
2462
- this[key] = namespace2;
2463
- });
2464
- } else {
2465
- this[key] = result;
2466
- }
3296
+ this[key] = namespace.build(pluginOptions);
2467
3297
  }
2468
3298
  }
2469
3299
  async getConfig() {
2470
3300
  const databaseURL = __privateGet(this, _options).databaseURL;
2471
- const branch = await __privateGet(this, _options).branch();
3301
+ const branch = __privateGet(this, _options).branch;
2472
3302
  return { databaseURL, branch };
2473
3303
  }
2474
- }, _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
+ }
2475
3312
  const fetch = getFetchImplementation(options?.fetch);
2476
3313
  const databaseURL = options?.databaseURL || getDatabaseURL();
2477
3314
  const apiKey = options?.apiKey || getAPIKey();
2478
- const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
2479
3315
  const trace = options?.trace ?? defaultTrace;
2480
- 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;
2481
3319
  if (!apiKey) {
2482
3320
  throw new Error("Option apiKey is required");
2483
3321
  }
2484
3322
  if (!databaseURL) {
2485
3323
  throw new Error("Option databaseURL is required");
2486
3324
  }
2487
- return { fetch, databaseURL, apiKey, branch, cache, trace };
2488
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace }) {
2489
- const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
2490
- if (!branchValue)
2491
- 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
+ }) {
2492
3367
  return {
2493
- fetchImpl: fetch,
3368
+ fetch,
2494
3369
  apiKey,
2495
3370
  apiUrl: "",
3371
+ // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
2496
3372
  workspacesApiUrl: (path, params) => {
2497
3373
  const hasBranch = params.dbBranchName ?? params.branch;
2498
- const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branchValue}` : "");
3374
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branch}` : "");
2499
3375
  return databaseURL + newPath;
2500
3376
  },
2501
- trace
2502
- };
2503
- }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
2504
- if (__privateGet(this, _branch))
2505
- return __privateGet(this, _branch);
2506
- if (param === void 0)
2507
- return void 0;
2508
- const strategies = Array.isArray(param) ? [...param] : [param];
2509
- const evaluateBranch = async (strategy) => {
2510
- return isBranchStrategyBuilder(strategy) ? await strategy() : strategy;
3377
+ trace,
3378
+ clientID,
3379
+ clientName,
3380
+ xataAgentExtra
2511
3381
  };
2512
- for await (const strategy of strategies) {
2513
- const branch = await evaluateBranch(strategy);
2514
- if (branch) {
2515
- __privateSet(this, _branch, branch);
2516
- return branch;
2517
- }
2518
- }
2519
3382
  }, _a;
2520
3383
  };
2521
3384
  class BaseClient extends buildClient() {
@@ -2588,21 +3451,6 @@ const deserialize = (json) => {
2588
3451
  return defaultSerializer.fromJSON(json);
2589
3452
  };
2590
3453
 
2591
- function buildWorkerRunner(config) {
2592
- return function xataWorker(name, _worker) {
2593
- return async (...args) => {
2594
- const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
2595
- const result = await fetch(url, {
2596
- method: "POST",
2597
- headers: { "Content-Type": "application/json" },
2598
- body: serialize({ args })
2599
- });
2600
- const text = await result.text();
2601
- return deserialize(text);
2602
- };
2603
- };
2604
- }
2605
-
2606
3454
  class XataError extends Error {
2607
3455
  constructor(message, status) {
2608
3456
  super(message);
@@ -2610,5 +3458,5 @@ class XataError extends Error {
2610
3458
  }
2611
3459
  }
2612
3460
 
2613
- export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, Serializer, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, applyBranchSchemaEdit, buildClient, buildWorkerRunner, bulkInsertTableRecords, cPcreateDatabase, cPdeleteDatabase, cPgetCPDatabaseMetadata, cPgetDatabaseList, cPupdateCPDatabaseMetadata, cancelWorkspaceMemberInvite, compareBranchSchemas, compareBranchWithUserSchema, compareMigrationRequest, contains, createBranch, createDatabase, createMigrationRequest, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, deserialize, endsWith, equals, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchSchemaHistory, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseMetadata, getDatabaseURL, getGitBranchesMapping, getMigrationRequest, getMigrationRequestIsMerged, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, greaterEquals, greaterThan, greaterThanEquals, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isIdentifiable, isNot, isXataRecord, le, lessEquals, lessThan, lessThanEquals, listMigrationRequestsCommits, lt, lte, mergeMigrationRequest, notExists, operationsByTag, 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 };
2614
3462
  //# sourceMappingURL=index.mjs.map