@xata.io/client 0.0.0-alpha.vfa22996 → 0.0.0-alpha.vfa36696

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,7 +1,8 @@
1
1
  'use strict';
2
2
 
3
- const defaultTrace = async (_name, fn, _options) => {
3
+ const defaultTrace = async (name, fn, _options) => {
4
4
  return await fn({
5
+ name,
5
6
  setAttributes: () => {
6
7
  return;
7
8
  }
@@ -28,8 +29,11 @@ function notEmpty(value) {
28
29
  function compact(arr) {
29
30
  return arr.filter(notEmpty);
30
31
  }
32
+ function compactObject(obj) {
33
+ return Object.fromEntries(Object.entries(obj).filter(([, value]) => notEmpty(value)));
34
+ }
31
35
  function isObject(value) {
32
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
36
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date);
33
37
  }
34
38
  function isDefined(value) {
35
39
  return value !== null && value !== void 0;
@@ -84,6 +88,15 @@ function chunk(array, chunkSize) {
84
88
  async function timeout(ms) {
85
89
  return new Promise((resolve) => setTimeout(resolve, ms));
86
90
  }
91
+ function promiseMap(inputValues, mapper) {
92
+ const reducer = (acc$, inputValue) => acc$.then(
93
+ (acc) => mapper(inputValue).then((result) => {
94
+ acc.push(result);
95
+ return acc;
96
+ })
97
+ );
98
+ return inputValues.reduce(reducer, Promise.resolve([]));
99
+ }
87
100
 
88
101
  function getEnvironment() {
89
102
  try {
@@ -92,8 +105,10 @@ function getEnvironment() {
92
105
  apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
93
106
  databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
94
107
  branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
95
- envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
96
- fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
108
+ deployPreview: process.env.XATA_PREVIEW,
109
+ deployPreviewBranch: process.env.XATA_PREVIEW_BRANCH,
110
+ vercelGitCommitRef: process.env.VERCEL_GIT_COMMIT_REF,
111
+ vercelGitRepoOwner: process.env.VERCEL_GIT_REPO_OWNER
97
112
  };
98
113
  }
99
114
  } catch (err) {
@@ -104,8 +119,10 @@ function getEnvironment() {
104
119
  apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
105
120
  databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
106
121
  branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
107
- envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
108
- fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
122
+ deployPreview: Deno.env.get("XATA_PREVIEW"),
123
+ deployPreviewBranch: Deno.env.get("XATA_PREVIEW_BRANCH"),
124
+ vercelGitCommitRef: Deno.env.get("VERCEL_GIT_COMMIT_REF"),
125
+ vercelGitRepoOwner: Deno.env.get("VERCEL_GIT_REPO_OWNER")
109
126
  };
110
127
  }
111
128
  } catch (err) {
@@ -114,8 +131,10 @@ function getEnvironment() {
114
131
  apiKey: getGlobalApiKey(),
115
132
  databaseURL: getGlobalDatabaseURL(),
116
133
  branch: getGlobalBranch(),
117
- envBranch: void 0,
118
- fallbackBranch: getGlobalFallbackBranch()
134
+ deployPreview: void 0,
135
+ deployPreviewBranch: void 0,
136
+ vercelGitCommitRef: void 0,
137
+ vercelGitRepoOwner: void 0
119
138
  };
120
139
  }
121
140
  function getEnableBrowserVariable() {
@@ -158,44 +177,59 @@ function getGlobalBranch() {
158
177
  return void 0;
159
178
  }
160
179
  }
161
- function getGlobalFallbackBranch() {
180
+ function getDatabaseURL() {
162
181
  try {
163
- return XATA_FALLBACK_BRANCH;
182
+ const { databaseURL } = getEnvironment();
183
+ return databaseURL;
164
184
  } catch (err) {
165
185
  return void 0;
166
186
  }
167
187
  }
168
- async function getGitBranch() {
169
- const cmd = ["git", "branch", "--show-current"];
170
- const fullCmd = cmd.join(" ");
171
- const nodeModule = ["child", "process"].join("_");
172
- const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
188
+ function getAPIKey() {
173
189
  try {
174
- if (typeof require === "function") {
175
- return require(nodeModule).execSync(fullCmd, execOptions).trim();
176
- }
177
- const { execSync } = await import(nodeModule);
178
- return execSync(fullCmd, execOptions).toString().trim();
190
+ const { apiKey } = getEnvironment();
191
+ return apiKey;
179
192
  } catch (err) {
193
+ return void 0;
180
194
  }
195
+ }
196
+ function getBranch() {
181
197
  try {
182
- if (isObject(Deno)) {
183
- const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
184
- return new TextDecoder().decode(await process2.output()).trim();
185
- }
198
+ const { branch } = getEnvironment();
199
+ return branch ?? "main";
186
200
  } catch (err) {
201
+ return void 0;
187
202
  }
188
203
  }
189
-
190
- function getAPIKey() {
204
+ function buildPreviewBranchName({ org, branch }) {
205
+ return `preview-${org}-${branch}`;
206
+ }
207
+ function getPreviewBranch() {
191
208
  try {
192
- const { apiKey } = getEnvironment();
193
- return apiKey;
209
+ const { deployPreview, deployPreviewBranch, vercelGitCommitRef, vercelGitRepoOwner } = getEnvironment();
210
+ if (deployPreviewBranch)
211
+ return deployPreviewBranch;
212
+ switch (deployPreview) {
213
+ case "vercel": {
214
+ if (!vercelGitCommitRef || !vercelGitRepoOwner) {
215
+ console.warn("XATA_PREVIEW=vercel but VERCEL_GIT_COMMIT_REF or VERCEL_GIT_REPO_OWNER is not valid");
216
+ return void 0;
217
+ }
218
+ return buildPreviewBranchName({ org: vercelGitRepoOwner, branch: vercelGitCommitRef });
219
+ }
220
+ }
221
+ return void 0;
194
222
  } catch (err) {
195
223
  return void 0;
196
224
  }
197
225
  }
198
226
 
227
+ var __defProp$8 = Object.defineProperty;
228
+ var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
229
+ var __publicField$8 = (obj, key, value) => {
230
+ __defNormalProp$8(obj, typeof key !== "symbol" ? key + "" : key, value);
231
+ return value;
232
+ };
199
233
  var __accessCheck$8 = (obj, member, msg) => {
200
234
  if (!member.has(obj))
201
235
  throw TypeError("Cannot " + msg);
@@ -219,6 +253,7 @@ var __privateMethod$4 = (obj, member, method) => {
219
253
  return method;
220
254
  };
221
255
  var _fetch, _queue, _concurrency, _enqueue, enqueue_fn;
256
+ const REQUEST_TIMEOUT = 3e4;
222
257
  function getFetchImplementation(userFetch) {
223
258
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
224
259
  const fetchImpl = userFetch ?? globalFetch;
@@ -235,6 +270,8 @@ class ApiRequestPool {
235
270
  __privateAdd$8(this, _fetch, void 0);
236
271
  __privateAdd$8(this, _queue, void 0);
237
272
  __privateAdd$8(this, _concurrency, void 0);
273
+ __publicField$8(this, "running");
274
+ __publicField$8(this, "started");
238
275
  __privateSet$8(this, _queue, []);
239
276
  __privateSet$8(this, _concurrency, concurrency);
240
277
  this.running = 0;
@@ -250,17 +287,20 @@ class ApiRequestPool {
250
287
  return __privateGet$8(this, _fetch);
251
288
  }
252
289
  request(url, options) {
253
- const start = new Date();
290
+ const start = /* @__PURE__ */ new Date();
254
291
  const fetch2 = this.getFetch();
255
292
  const runRequest = async (stalled = false) => {
256
- const response = await fetch2(url, options);
293
+ const response = await Promise.race([fetch2(url, options), timeout(REQUEST_TIMEOUT).then(() => null)]);
294
+ if (!response) {
295
+ throw new Error("Request timed out");
296
+ }
257
297
  if (response.status === 429) {
258
298
  const rateLimitReset = parseNumber(response.headers?.get("x-ratelimit-reset")) ?? 1;
259
299
  await timeout(rateLimitReset * 1e3);
260
300
  return await runRequest(true);
261
301
  }
262
302
  if (stalled) {
263
- const stalledTime = new Date().getTime() - start.getTime();
303
+ const stalledTime = (/* @__PURE__ */ new Date()).getTime() - start.getTime();
264
304
  console.warn(`A request to Xata hit your workspace limits, was retried and stalled for ${stalledTime}ms`);
265
305
  }
266
306
  return response;
@@ -296,18 +336,208 @@ enqueue_fn = function(task) {
296
336
  return promise;
297
337
  };
298
338
 
299
- const VERSION = "0.0.0-alpha.vfa22996";
339
+ function generateUUID() {
340
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
341
+ const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
342
+ return v.toString(16);
343
+ });
344
+ }
345
+
346
+ async function getBytes(stream, onChunk) {
347
+ const reader = stream.getReader();
348
+ let result;
349
+ while (!(result = await reader.read()).done) {
350
+ onChunk(result.value);
351
+ }
352
+ }
353
+ function getLines(onLine) {
354
+ let buffer;
355
+ let position;
356
+ let fieldLength;
357
+ let discardTrailingNewline = false;
358
+ return function onChunk(arr) {
359
+ if (buffer === void 0) {
360
+ buffer = arr;
361
+ position = 0;
362
+ fieldLength = -1;
363
+ } else {
364
+ buffer = concat(buffer, arr);
365
+ }
366
+ const bufLength = buffer.length;
367
+ let lineStart = 0;
368
+ while (position < bufLength) {
369
+ if (discardTrailingNewline) {
370
+ if (buffer[position] === 10 /* NewLine */) {
371
+ lineStart = ++position;
372
+ }
373
+ discardTrailingNewline = false;
374
+ }
375
+ let lineEnd = -1;
376
+ for (; position < bufLength && lineEnd === -1; ++position) {
377
+ switch (buffer[position]) {
378
+ case 58 /* Colon */:
379
+ if (fieldLength === -1) {
380
+ fieldLength = position - lineStart;
381
+ }
382
+ break;
383
+ case 13 /* CarriageReturn */:
384
+ discardTrailingNewline = true;
385
+ case 10 /* NewLine */:
386
+ lineEnd = position;
387
+ break;
388
+ }
389
+ }
390
+ if (lineEnd === -1) {
391
+ break;
392
+ }
393
+ onLine(buffer.subarray(lineStart, lineEnd), fieldLength);
394
+ lineStart = position;
395
+ fieldLength = -1;
396
+ }
397
+ if (lineStart === bufLength) {
398
+ buffer = void 0;
399
+ } else if (lineStart !== 0) {
400
+ buffer = buffer.subarray(lineStart);
401
+ position -= lineStart;
402
+ }
403
+ };
404
+ }
405
+ function getMessages(onId, onRetry, onMessage) {
406
+ let message = newMessage();
407
+ const decoder = new TextDecoder();
408
+ return function onLine(line, fieldLength) {
409
+ if (line.length === 0) {
410
+ onMessage?.(message);
411
+ message = newMessage();
412
+ } else if (fieldLength > 0) {
413
+ const field = decoder.decode(line.subarray(0, fieldLength));
414
+ const valueOffset = fieldLength + (line[fieldLength + 1] === 32 /* Space */ ? 2 : 1);
415
+ const value = decoder.decode(line.subarray(valueOffset));
416
+ switch (field) {
417
+ case "data":
418
+ message.data = message.data ? message.data + "\n" + value : value;
419
+ break;
420
+ case "event":
421
+ message.event = value;
422
+ break;
423
+ case "id":
424
+ onId(message.id = value);
425
+ break;
426
+ case "retry":
427
+ const retry = parseInt(value, 10);
428
+ if (!isNaN(retry)) {
429
+ onRetry(message.retry = retry);
430
+ }
431
+ break;
432
+ }
433
+ }
434
+ };
435
+ }
436
+ function concat(a, b) {
437
+ const res = new Uint8Array(a.length + b.length);
438
+ res.set(a);
439
+ res.set(b, a.length);
440
+ return res;
441
+ }
442
+ function newMessage() {
443
+ return {
444
+ data: "",
445
+ event: "",
446
+ id: "",
447
+ retry: void 0
448
+ };
449
+ }
450
+ const EventStreamContentType = "text/event-stream";
451
+ const LastEventId = "last-event-id";
452
+ function fetchEventSource(input, {
453
+ signal: inputSignal,
454
+ headers: inputHeaders,
455
+ onopen: inputOnOpen,
456
+ onmessage,
457
+ onclose,
458
+ onerror,
459
+ fetch: inputFetch,
460
+ ...rest
461
+ }) {
462
+ return new Promise((resolve, reject) => {
463
+ const headers = { ...inputHeaders };
464
+ if (!headers.accept) {
465
+ headers.accept = EventStreamContentType;
466
+ }
467
+ let curRequestController;
468
+ function dispose() {
469
+ curRequestController.abort();
470
+ }
471
+ inputSignal?.addEventListener("abort", () => {
472
+ dispose();
473
+ resolve();
474
+ });
475
+ const fetchImpl = inputFetch ?? fetch;
476
+ const onopen = inputOnOpen ?? defaultOnOpen;
477
+ async function create() {
478
+ curRequestController = new AbortController();
479
+ try {
480
+ const response = await fetchImpl(input, {
481
+ ...rest,
482
+ headers,
483
+ signal: curRequestController.signal
484
+ });
485
+ await onopen(response);
486
+ await getBytes(
487
+ response.body,
488
+ getLines(
489
+ getMessages(
490
+ (id) => {
491
+ if (id) {
492
+ headers[LastEventId] = id;
493
+ } else {
494
+ delete headers[LastEventId];
495
+ }
496
+ },
497
+ (_retry) => {
498
+ },
499
+ onmessage
500
+ )
501
+ )
502
+ );
503
+ onclose?.();
504
+ dispose();
505
+ resolve();
506
+ } catch (err) {
507
+ }
508
+ }
509
+ create();
510
+ });
511
+ }
512
+ function defaultOnOpen(response) {
513
+ const contentType = response.headers?.get("content-type");
514
+ if (!contentType?.startsWith(EventStreamContentType)) {
515
+ throw new Error(`Expected content-type to be ${EventStreamContentType}, Actual: ${contentType}`);
516
+ }
517
+ }
518
+
519
+ const VERSION = "0.24.3";
300
520
 
521
+ var __defProp$7 = Object.defineProperty;
522
+ var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
523
+ var __publicField$7 = (obj, key, value) => {
524
+ __defNormalProp$7(obj, typeof key !== "symbol" ? key + "" : key, value);
525
+ return value;
526
+ };
301
527
  class ErrorWithCause extends Error {
302
528
  constructor(message, options) {
303
529
  super(message, options);
530
+ __publicField$7(this, "cause");
304
531
  }
305
532
  }
306
533
  class FetcherError extends ErrorWithCause {
307
534
  constructor(status, data, requestId) {
308
535
  super(getMessage(data));
536
+ __publicField$7(this, "status");
537
+ __publicField$7(this, "requestId");
538
+ __publicField$7(this, "errors");
309
539
  this.status = status;
310
- this.errors = isBulkError(data) ? data.errors : void 0;
540
+ this.errors = isBulkError(data) ? data.errors : [{ message: getMessage(data), status }];
311
541
  this.requestId = requestId;
312
542
  if (data instanceof Error) {
313
543
  this.stack = data.stack;
@@ -372,14 +602,24 @@ function hostHeader(url) {
372
602
  const { groups } = pattern.exec(url) ?? {};
373
603
  return groups?.host ? { Host: groups.host } : {};
374
604
  }
605
+ function parseBody(body, headers) {
606
+ if (!isDefined(body))
607
+ return void 0;
608
+ const { "Content-Type": contentType } = headers ?? {};
609
+ if (String(contentType).toLowerCase() === "application/json") {
610
+ return JSON.stringify(body);
611
+ }
612
+ return body;
613
+ }
614
+ const defaultClientID = generateUUID();
375
615
  async function fetch$1({
376
616
  url: path,
377
617
  method,
378
618
  body,
379
- headers,
619
+ headers: customHeaders,
380
620
  pathParams,
381
621
  queryParams,
382
- fetchImpl,
622
+ fetch: fetch2,
383
623
  apiKey,
384
624
  endpoint,
385
625
  apiUrl,
@@ -388,9 +628,12 @@ async function fetch$1({
388
628
  signal,
389
629
  clientID,
390
630
  sessionID,
391
- fetchOptions = {}
631
+ clientName,
632
+ xataAgentExtra,
633
+ fetchOptions = {},
634
+ rawResponse = false
392
635
  }) {
393
- pool.setFetch(fetchImpl);
636
+ pool.setFetch(fetch2);
394
637
  return await trace(
395
638
  `${method.toUpperCase()} ${path}`,
396
639
  async ({ setAttributes }) => {
@@ -401,19 +644,27 @@ async function fetch$1({
401
644
  [TraceAttributes.HTTP_URL]: url,
402
645
  [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
403
646
  });
647
+ const xataAgent = compact([
648
+ ["client", "TS_SDK"],
649
+ ["version", VERSION],
650
+ isDefined(clientName) ? ["service", clientName] : void 0,
651
+ ...Object.entries(xataAgentExtra ?? {})
652
+ ]).map(([key, value]) => `${key}=${value}`).join("; ");
653
+ const headers = compactObject({
654
+ "Accept-Encoding": "identity",
655
+ "Content-Type": "application/json",
656
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
657
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
658
+ "X-Xata-Agent": xataAgent,
659
+ ...customHeaders,
660
+ ...hostHeader(fullUrl),
661
+ Authorization: `Bearer ${apiKey}`
662
+ });
404
663
  const response = await pool.request(url, {
405
664
  ...fetchOptions,
406
665
  method: method.toUpperCase(),
407
- body: body ? JSON.stringify(body) : void 0,
408
- headers: {
409
- "Content-Type": "application/json",
410
- "User-Agent": `Xata client-ts/${VERSION}`,
411
- "X-Xata-Client-ID": clientID ?? "",
412
- "X-Xata-Session-ID": sessionID ?? "",
413
- ...headers,
414
- ...hostHeader(fullUrl),
415
- Authorization: `Bearer ${apiKey}`
416
- },
666
+ body: parseBody(body, headers),
667
+ headers,
417
668
  signal
418
669
  });
419
670
  const { host, protocol } = parseUrl(response.url);
@@ -425,6 +676,9 @@ async function fetch$1({
425
676
  [TraceAttributes.HTTP_HOST]: host,
426
677
  [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
427
678
  });
679
+ const message = response.headers?.get("x-xata-message");
680
+ if (message)
681
+ console.warn(message);
428
682
  if (response.status === 204) {
429
683
  return {};
430
684
  }
@@ -432,7 +686,7 @@ async function fetch$1({
432
686
  throw new FetcherError(response.status, "Rate limit exceeded", requestId);
433
687
  }
434
688
  try {
435
- const jsonResponse = await response.json();
689
+ const jsonResponse = rawResponse ? await response.blob() : await response.json();
436
690
  if (response.ok) {
437
691
  return jsonResponse;
438
692
  }
@@ -444,6 +698,59 @@ async function fetch$1({
444
698
  { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
445
699
  );
446
700
  }
701
+ function fetchSSERequest({
702
+ url: path,
703
+ method,
704
+ body,
705
+ headers: customHeaders,
706
+ pathParams,
707
+ queryParams,
708
+ fetch: fetch2,
709
+ apiKey,
710
+ endpoint,
711
+ apiUrl,
712
+ workspacesApiUrl,
713
+ onMessage,
714
+ onError,
715
+ onClose,
716
+ signal,
717
+ clientID,
718
+ sessionID,
719
+ clientName,
720
+ xataAgentExtra
721
+ }) {
722
+ const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
723
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
724
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
725
+ void fetchEventSource(url, {
726
+ method,
727
+ body: JSON.stringify(body),
728
+ fetch: fetch2,
729
+ signal,
730
+ headers: {
731
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
732
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
733
+ "X-Xata-Agent": compact([
734
+ ["client", "TS_SDK"],
735
+ ["version", VERSION],
736
+ isDefined(clientName) ? ["service", clientName] : void 0,
737
+ ...Object.entries(xataAgentExtra ?? {})
738
+ ]).map(([key, value]) => `${key}=${value}`).join("; "),
739
+ ...customHeaders,
740
+ Authorization: `Bearer ${apiKey}`,
741
+ "Content-Type": "application/json"
742
+ },
743
+ onmessage(ev) {
744
+ onMessage?.(JSON.parse(ev.data));
745
+ },
746
+ onerror(ev) {
747
+ onError?.(JSON.parse(ev.data));
748
+ },
749
+ onclose() {
750
+ onClose?.();
751
+ }
752
+ });
753
+ }
447
754
  function parseUrl(url) {
448
755
  try {
449
756
  const { host, protocol } = new URL(url);
@@ -455,17 +762,12 @@ function parseUrl(url) {
455
762
 
456
763
  const dataPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "dataPlane" });
457
764
 
458
- const dEPRECATEDgetDatabaseList = (variables, signal) => dataPlaneFetch({ url: "/dbs", method: "get", ...variables, signal });
459
765
  const getBranchList = (variables, signal) => dataPlaneFetch({
460
766
  url: "/dbs/{dbName}",
461
767
  method: "get",
462
768
  ...variables,
463
769
  signal
464
770
  });
465
- const dEPRECATEDcreateDatabase = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}", method: "put", ...variables, signal });
466
- const dEPRECATEDdeleteDatabase = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}", method: "delete", ...variables, signal });
467
- const dEPRECATEDgetDatabaseMetadata = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/metadata", method: "get", ...variables, signal });
468
- const dEPRECATEDupdateDatabaseMetadata = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/metadata", method: "patch", ...variables, signal });
469
771
  const getBranchDetails = (variables, signal) => dataPlaneFetch({
470
772
  url: "/db/{dbBranchName}",
471
773
  method: "get",
@@ -479,6 +781,12 @@ const deleteBranch = (variables, signal) => dataPlaneFetch({
479
781
  ...variables,
480
782
  signal
481
783
  });
784
+ const copyBranch = (variables, signal) => dataPlaneFetch({
785
+ url: "/db/{dbBranchName}/copy",
786
+ method: "post",
787
+ ...variables,
788
+ signal
789
+ });
482
790
  const updateBranchMetadata = (variables, signal) => dataPlaneFetch({
483
791
  url: "/db/{dbBranchName}/metadata",
484
792
  method: "put",
@@ -504,7 +812,6 @@ const resolveBranch = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName
504
812
  const getBranchMigrationHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables, signal });
505
813
  const getBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables, signal });
506
814
  const executeBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables, signal });
507
- const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
508
815
  const queryMigrationRequests = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/query", method: "post", ...variables, signal });
509
816
  const createMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations", method: "post", ...variables, signal });
510
817
  const getMigrationRequest = (variables, signal) => dataPlaneFetch({
@@ -529,6 +836,7 @@ const compareBranchSchemas = (variables, signal) => dataPlaneFetch({ url: "/db/{
529
836
  const updateBranchSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/update", method: "post", ...variables, signal });
530
837
  const previewBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables, signal });
531
838
  const applyBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables, signal });
839
+ const pushBranchMigrations = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/push", method: "post", ...variables, signal });
532
840
  const createTable = (variables, signal) => dataPlaneFetch({
533
841
  url: "/db/{dbBranchName}/tables/{tableName}",
534
842
  method: "put",
@@ -571,7 +879,44 @@ const deleteColumn = (variables, signal) => dataPlaneFetch({
571
879
  ...variables,
572
880
  signal
573
881
  });
882
+ const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
574
883
  const insertRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
884
+ const getFileItem = (variables, signal) => dataPlaneFetch({
885
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
886
+ method: "get",
887
+ ...variables,
888
+ signal
889
+ });
890
+ const putFileItem = (variables, signal) => dataPlaneFetch({
891
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
892
+ method: "put",
893
+ ...variables,
894
+ signal
895
+ });
896
+ const deleteFileItem = (variables, signal) => dataPlaneFetch({
897
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
898
+ method: "delete",
899
+ ...variables,
900
+ signal
901
+ });
902
+ const getFile = (variables, signal) => dataPlaneFetch({
903
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
904
+ method: "get",
905
+ ...variables,
906
+ signal
907
+ });
908
+ const putFile = (variables, signal) => dataPlaneFetch({
909
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
910
+ method: "put",
911
+ ...variables,
912
+ signal
913
+ });
914
+ const deleteFile = (variables, signal) => dataPlaneFetch({
915
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
916
+ method: "delete",
917
+ ...variables,
918
+ signal
919
+ });
575
920
  const getRecord = (variables, signal) => dataPlaneFetch({
576
921
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
577
922
  method: "get",
@@ -601,21 +946,35 @@ const searchTable = (variables, signal) => dataPlaneFetch({
601
946
  ...variables,
602
947
  signal
603
948
  });
949
+ const sqlQuery = (variables, signal) => dataPlaneFetch({
950
+ url: "/db/{dbBranchName}/sql",
951
+ method: "post",
952
+ ...variables,
953
+ signal
954
+ });
955
+ const vectorSearchTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/vectorSearch", method: "post", ...variables, signal });
956
+ const askTable = (variables, signal) => dataPlaneFetch({
957
+ url: "/db/{dbBranchName}/tables/{tableName}/ask",
958
+ method: "post",
959
+ ...variables,
960
+ signal
961
+ });
962
+ const askTableSession = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}", method: "post", ...variables, signal });
604
963
  const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
605
964
  const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
965
+ const fileAccess = (variables, signal) => dataPlaneFetch({
966
+ url: "/file/{fileId}",
967
+ method: "get",
968
+ ...variables,
969
+ signal
970
+ });
606
971
  const operationsByTag$2 = {
607
- database: {
608
- dEPRECATEDgetDatabaseList,
609
- dEPRECATEDcreateDatabase,
610
- dEPRECATEDdeleteDatabase,
611
- dEPRECATEDgetDatabaseMetadata,
612
- dEPRECATEDupdateDatabaseMetadata
613
- },
614
972
  branch: {
615
973
  getBranchList,
616
974
  getBranchDetails,
617
975
  createBranch,
618
976
  deleteBranch,
977
+ copyBranch,
619
978
  updateBranchMetadata,
620
979
  getBranchMetadata,
621
980
  getBranchStats,
@@ -633,17 +992,8 @@ const operationsByTag$2 = {
633
992
  compareBranchSchemas,
634
993
  updateBranchSchema,
635
994
  previewBranchSchemaEdit,
636
- applyBranchSchemaEdit
637
- },
638
- records: {
639
- branchTransaction,
640
- insertRecord,
641
- getRecord,
642
- insertRecordWithID,
643
- updateRecordWithID,
644
- upsertRecordWithID,
645
- deleteRecord,
646
- bulkInsertTableRecords
995
+ applyBranchSchemaEdit,
996
+ pushBranchMigrations
647
997
  },
648
998
  migrationRequests: {
649
999
  queryMigrationRequests,
@@ -667,11 +1017,39 @@ const operationsByTag$2 = {
667
1017
  updateColumn,
668
1018
  deleteColumn
669
1019
  },
670
- searchAndFilter: { queryTable, searchBranch, searchTable, summarizeTable, aggregateTable }
1020
+ records: {
1021
+ branchTransaction,
1022
+ insertRecord,
1023
+ getRecord,
1024
+ insertRecordWithID,
1025
+ updateRecordWithID,
1026
+ upsertRecordWithID,
1027
+ deleteRecord,
1028
+ bulkInsertTableRecords
1029
+ },
1030
+ files: { getFileItem, putFileItem, deleteFileItem, getFile, putFile, deleteFile, fileAccess },
1031
+ searchAndFilter: {
1032
+ queryTable,
1033
+ searchBranch,
1034
+ searchTable,
1035
+ sqlQuery,
1036
+ vectorSearchTable,
1037
+ askTable,
1038
+ askTableSession,
1039
+ summarizeTable,
1040
+ aggregateTable
1041
+ }
671
1042
  };
672
1043
 
673
1044
  const controlPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "controlPlane" });
674
1045
 
1046
+ const grantAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "post", ...variables, signal });
1047
+ const generateAccessToken = (variables, signal) => controlPlaneFetch({
1048
+ url: "/oauth/token",
1049
+ method: "post",
1050
+ ...variables,
1051
+ signal
1052
+ });
675
1053
  const getUser = (variables, signal) => controlPlaneFetch({
676
1054
  url: "/user",
677
1055
  method: "get",
@@ -766,6 +1144,10 @@ const deleteDatabase = (variables, signal) => controlPlaneFetch({
766
1144
  });
767
1145
  const getDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "get", ...variables, signal });
768
1146
  const updateDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "patch", ...variables, signal });
1147
+ const renameDatabase = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/rename", method: "post", ...variables, signal });
1148
+ const getDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "get", ...variables, signal });
1149
+ const updateDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "put", ...variables, signal });
1150
+ const deleteDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "delete", ...variables, signal });
769
1151
  const listRegions = (variables, signal) => controlPlaneFetch({
770
1152
  url: "/workspaces/{workspaceId}/regions",
771
1153
  method: "get",
@@ -773,6 +1155,7 @@ const listRegions = (variables, signal) => controlPlaneFetch({
773
1155
  signal
774
1156
  });
775
1157
  const operationsByTag$1 = {
1158
+ authOther: { grantAuthorizationCode, generateAccessToken },
776
1159
  users: { getUser, updateUser, deleteUser },
777
1160
  authentication: { getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
778
1161
  workspaces: {
@@ -798,6 +1181,10 @@ const operationsByTag$1 = {
798
1181
  deleteDatabase,
799
1182
  getDatabaseMetadata,
800
1183
  updateDatabaseMetadata,
1184
+ renameDatabase,
1185
+ getDatabaseGithubSettings,
1186
+ updateDatabaseGithubSettings,
1187
+ deleteDatabaseGithubSettings,
801
1188
  listRegions
802
1189
  }
803
1190
  };
@@ -818,8 +1205,12 @@ const providers = {
818
1205
  workspaces: "https://{workspaceId}.{region}.xata.sh"
819
1206
  },
820
1207
  staging: {
821
- main: "https://staging.xatabase.co",
822
- workspaces: "https://{workspaceId}.staging.{region}.xatabase.co"
1208
+ main: "https://api.staging-xata.dev",
1209
+ workspaces: "https://{workspaceId}.{region}.staging-xata.dev"
1210
+ },
1211
+ dev: {
1212
+ main: "https://api.dev-xata.dev",
1213
+ workspaces: "https://{workspaceId}.{region}.dev-xata.dev"
823
1214
  }
824
1215
  };
825
1216
  function isHostProviderAlias(alias) {
@@ -837,15 +1228,22 @@ function parseProviderString(provider = "production") {
837
1228
  return null;
838
1229
  return { main, workspaces };
839
1230
  }
1231
+ function buildProviderString(provider) {
1232
+ if (isHostProviderAlias(provider))
1233
+ return provider;
1234
+ return `${provider.main},${provider.workspaces}`;
1235
+ }
840
1236
  function parseWorkspacesUrlParts(url) {
841
1237
  if (!isString(url))
842
1238
  return null;
843
- const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))?\.xata\.sh.*/;
844
- const regexStaging = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))?\.xatabase\.co.*/;
845
- const match = url.match(regex) || url.match(regexStaging);
1239
+ const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/;
1240
+ const regexDev = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.dev-xata\.dev.*/;
1241
+ const regexStaging = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.staging-xata\.dev.*/;
1242
+ const regexProdTesting = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.tech.*/;
1243
+ const match = url.match(regex) || url.match(regexDev) || url.match(regexStaging) || url.match(regexProdTesting);
846
1244
  if (!match)
847
1245
  return null;
848
- return { workspace: match[1], region: match[2] ?? "eu-west-1" };
1246
+ return { workspace: match[1], region: match[2] };
849
1247
  }
850
1248
 
851
1249
  var __accessCheck$7 = (obj, member, msg) => {
@@ -874,15 +1272,19 @@ class XataApiClient {
874
1272
  const provider = options.host ?? "production";
875
1273
  const apiKey = options.apiKey ?? getAPIKey();
876
1274
  const trace = options.trace ?? defaultTrace;
1275
+ const clientID = generateUUID();
877
1276
  if (!apiKey) {
878
1277
  throw new Error("Could not resolve a valid apiKey");
879
1278
  }
880
1279
  __privateSet$7(this, _extraProps, {
881
1280
  apiUrl: getHostUrl(provider, "main"),
882
1281
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
883
- fetchImpl: getFetchImplementation(options.fetch),
1282
+ fetch: getFetchImplementation(options.fetch),
884
1283
  apiKey,
885
- trace
1284
+ trace,
1285
+ clientName: options.clientName,
1286
+ xataAgentExtra: options.xataAgentExtra,
1287
+ clientID
886
1288
  });
887
1289
  }
888
1290
  get user() {
@@ -935,6 +1337,11 @@ class XataApiClient {
935
1337
  __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
936
1338
  return __privateGet$7(this, _namespaces).records;
937
1339
  }
1340
+ get files() {
1341
+ if (!__privateGet$7(this, _namespaces).files)
1342
+ __privateGet$7(this, _namespaces).files = new FilesApi(__privateGet$7(this, _extraProps));
1343
+ return __privateGet$7(this, _namespaces).files;
1344
+ }
938
1345
  get searchAndFilter() {
939
1346
  if (!__privateGet$7(this, _namespaces).searchAndFilter)
940
1347
  __privateGet$7(this, _namespaces).searchAndFilter = new SearchAndFilterApi(__privateGet$7(this, _extraProps));
@@ -1143,6 +1550,20 @@ class BranchApi {
1143
1550
  ...this.extraProps
1144
1551
  });
1145
1552
  }
1553
+ copyBranch({
1554
+ workspace,
1555
+ region,
1556
+ database,
1557
+ branch,
1558
+ destinationBranch,
1559
+ limit
1560
+ }) {
1561
+ return operationsByTag.branch.copyBranch({
1562
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1563
+ body: { destinationBranch, limit },
1564
+ ...this.extraProps
1565
+ });
1566
+ }
1146
1567
  updateBranchMetadata({
1147
1568
  workspace,
1148
1569
  region,
@@ -1498,6 +1919,164 @@ class RecordsApi {
1498
1919
  });
1499
1920
  }
1500
1921
  }
1922
+ class FilesApi {
1923
+ constructor(extraProps) {
1924
+ this.extraProps = extraProps;
1925
+ }
1926
+ getFileItem({
1927
+ workspace,
1928
+ region,
1929
+ database,
1930
+ branch,
1931
+ table,
1932
+ record,
1933
+ column,
1934
+ fileId
1935
+ }) {
1936
+ return operationsByTag.files.getFileItem({
1937
+ pathParams: {
1938
+ workspace,
1939
+ region,
1940
+ dbBranchName: `${database}:${branch}`,
1941
+ tableName: table,
1942
+ recordId: record,
1943
+ columnName: column,
1944
+ fileId
1945
+ },
1946
+ ...this.extraProps
1947
+ });
1948
+ }
1949
+ putFileItem({
1950
+ workspace,
1951
+ region,
1952
+ database,
1953
+ branch,
1954
+ table,
1955
+ record,
1956
+ column,
1957
+ fileId,
1958
+ file
1959
+ }) {
1960
+ return operationsByTag.files.putFileItem({
1961
+ pathParams: {
1962
+ workspace,
1963
+ region,
1964
+ dbBranchName: `${database}:${branch}`,
1965
+ tableName: table,
1966
+ recordId: record,
1967
+ columnName: column,
1968
+ fileId
1969
+ },
1970
+ // @ts-ignore
1971
+ body: file,
1972
+ ...this.extraProps
1973
+ });
1974
+ }
1975
+ deleteFileItem({
1976
+ workspace,
1977
+ region,
1978
+ database,
1979
+ branch,
1980
+ table,
1981
+ record,
1982
+ column,
1983
+ fileId
1984
+ }) {
1985
+ return operationsByTag.files.deleteFileItem({
1986
+ pathParams: {
1987
+ workspace,
1988
+ region,
1989
+ dbBranchName: `${database}:${branch}`,
1990
+ tableName: table,
1991
+ recordId: record,
1992
+ columnName: column,
1993
+ fileId
1994
+ },
1995
+ ...this.extraProps
1996
+ });
1997
+ }
1998
+ getFile({
1999
+ workspace,
2000
+ region,
2001
+ database,
2002
+ branch,
2003
+ table,
2004
+ record,
2005
+ column
2006
+ }) {
2007
+ return operationsByTag.files.getFile({
2008
+ pathParams: {
2009
+ workspace,
2010
+ region,
2011
+ dbBranchName: `${database}:${branch}`,
2012
+ tableName: table,
2013
+ recordId: record,
2014
+ columnName: column
2015
+ },
2016
+ ...this.extraProps
2017
+ });
2018
+ }
2019
+ putFile({
2020
+ workspace,
2021
+ region,
2022
+ database,
2023
+ branch,
2024
+ table,
2025
+ record,
2026
+ column,
2027
+ file
2028
+ }) {
2029
+ return operationsByTag.files.putFile({
2030
+ pathParams: {
2031
+ workspace,
2032
+ region,
2033
+ dbBranchName: `${database}:${branch}`,
2034
+ tableName: table,
2035
+ recordId: record,
2036
+ columnName: column
2037
+ },
2038
+ body: file,
2039
+ ...this.extraProps
2040
+ });
2041
+ }
2042
+ deleteFile({
2043
+ workspace,
2044
+ region,
2045
+ database,
2046
+ branch,
2047
+ table,
2048
+ record,
2049
+ column
2050
+ }) {
2051
+ return operationsByTag.files.deleteFile({
2052
+ pathParams: {
2053
+ workspace,
2054
+ region,
2055
+ dbBranchName: `${database}:${branch}`,
2056
+ tableName: table,
2057
+ recordId: record,
2058
+ columnName: column
2059
+ },
2060
+ ...this.extraProps
2061
+ });
2062
+ }
2063
+ fileAccess({
2064
+ workspace,
2065
+ region,
2066
+ fileId,
2067
+ verify
2068
+ }) {
2069
+ return operationsByTag.files.fileAccess({
2070
+ pathParams: {
2071
+ workspace,
2072
+ region,
2073
+ fileId
2074
+ },
2075
+ queryParams: { verify },
2076
+ ...this.extraProps
2077
+ });
2078
+ }
2079
+ }
1501
2080
  class SearchAndFilterApi {
1502
2081
  constructor(extraProps) {
1503
2082
  this.extraProps = extraProps;
@@ -1551,9 +2130,56 @@ class SearchAndFilterApi {
1551
2130
  prefix,
1552
2131
  highlight
1553
2132
  }) {
1554
- return operationsByTag.searchAndFilter.searchBranch({
1555
- pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1556
- body: { tables, query, fuzziness, prefix, highlight },
2133
+ return operationsByTag.searchAndFilter.searchBranch({
2134
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2135
+ body: { tables, query, fuzziness, prefix, highlight },
2136
+ ...this.extraProps
2137
+ });
2138
+ }
2139
+ vectorSearchTable({
2140
+ workspace,
2141
+ region,
2142
+ database,
2143
+ branch,
2144
+ table,
2145
+ queryVector,
2146
+ column,
2147
+ similarityFunction,
2148
+ size,
2149
+ filter
2150
+ }) {
2151
+ return operationsByTag.searchAndFilter.vectorSearchTable({
2152
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2153
+ body: { queryVector, column, similarityFunction, size, filter },
2154
+ ...this.extraProps
2155
+ });
2156
+ }
2157
+ askTable({
2158
+ workspace,
2159
+ region,
2160
+ database,
2161
+ branch,
2162
+ table,
2163
+ options
2164
+ }) {
2165
+ return operationsByTag.searchAndFilter.askTable({
2166
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2167
+ body: { ...options },
2168
+ ...this.extraProps
2169
+ });
2170
+ }
2171
+ askTableSession({
2172
+ workspace,
2173
+ region,
2174
+ database,
2175
+ branch,
2176
+ table,
2177
+ sessionId,
2178
+ message
2179
+ }) {
2180
+ return operationsByTag.searchAndFilter.askTableSession({
2181
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, sessionId },
2182
+ body: { message },
1557
2183
  ...this.extraProps
1558
2184
  });
1559
2185
  }
@@ -1757,11 +2383,13 @@ class MigrationsApi {
1757
2383
  region,
1758
2384
  database,
1759
2385
  branch,
1760
- schema
2386
+ schema,
2387
+ schemaOperations,
2388
+ branchOperations
1761
2389
  }) {
1762
2390
  return operationsByTag.migrations.compareBranchWithUserSchema({
1763
2391
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1764
- body: { schema },
2392
+ body: { schema, schemaOperations, branchOperations },
1765
2393
  ...this.extraProps
1766
2394
  });
1767
2395
  }
@@ -1771,11 +2399,12 @@ class MigrationsApi {
1771
2399
  database,
1772
2400
  branch,
1773
2401
  compare,
1774
- schema
2402
+ sourceBranchOperations,
2403
+ targetBranchOperations
1775
2404
  }) {
1776
2405
  return operationsByTag.migrations.compareBranchSchemas({
1777
2406
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, branchName: compare },
1778
- body: { schema },
2407
+ body: { sourceBranchOperations, targetBranchOperations },
1779
2408
  ...this.extraProps
1780
2409
  });
1781
2410
  }
@@ -1818,6 +2447,19 @@ class MigrationsApi {
1818
2447
  ...this.extraProps
1819
2448
  });
1820
2449
  }
2450
+ pushBranchMigrations({
2451
+ workspace,
2452
+ region,
2453
+ database,
2454
+ branch,
2455
+ migrations
2456
+ }) {
2457
+ return operationsByTag.migrations.pushBranchMigrations({
2458
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2459
+ body: { migrations },
2460
+ ...this.extraProps
2461
+ });
2462
+ }
1821
2463
  }
1822
2464
  class DatabaseApi {
1823
2465
  constructor(extraProps) {
@@ -1832,11 +2474,13 @@ class DatabaseApi {
1832
2474
  createDatabase({
1833
2475
  workspace,
1834
2476
  database,
1835
- data
2477
+ data,
2478
+ headers
1836
2479
  }) {
1837
2480
  return operationsByTag.databases.createDatabase({
1838
2481
  pathParams: { workspaceId: workspace, dbName: database },
1839
2482
  body: data,
2483
+ headers,
1840
2484
  ...this.extraProps
1841
2485
  });
1842
2486
  }
@@ -1869,6 +2513,46 @@ class DatabaseApi {
1869
2513
  ...this.extraProps
1870
2514
  });
1871
2515
  }
2516
+ renameDatabase({
2517
+ workspace,
2518
+ database,
2519
+ newName
2520
+ }) {
2521
+ return operationsByTag.databases.renameDatabase({
2522
+ pathParams: { workspaceId: workspace, dbName: database },
2523
+ body: { newName },
2524
+ ...this.extraProps
2525
+ });
2526
+ }
2527
+ getDatabaseGithubSettings({
2528
+ workspace,
2529
+ database
2530
+ }) {
2531
+ return operationsByTag.databases.getDatabaseGithubSettings({
2532
+ pathParams: { workspaceId: workspace, dbName: database },
2533
+ ...this.extraProps
2534
+ });
2535
+ }
2536
+ updateDatabaseGithubSettings({
2537
+ workspace,
2538
+ database,
2539
+ settings
2540
+ }) {
2541
+ return operationsByTag.databases.updateDatabaseGithubSettings({
2542
+ pathParams: { workspaceId: workspace, dbName: database },
2543
+ body: settings,
2544
+ ...this.extraProps
2545
+ });
2546
+ }
2547
+ deleteDatabaseGithubSettings({
2548
+ workspace,
2549
+ database
2550
+ }) {
2551
+ return operationsByTag.databases.deleteDatabaseGithubSettings({
2552
+ pathParams: { workspaceId: workspace, dbName: database },
2553
+ ...this.extraProps
2554
+ });
2555
+ }
1872
2556
  listRegions({ workspace }) {
1873
2557
  return operationsByTag.databases.listRegions({
1874
2558
  pathParams: { workspaceId: workspace },
@@ -1878,29 +2562,269 @@ class DatabaseApi {
1878
2562
  }
1879
2563
 
1880
2564
  class XataApiPlugin {
1881
- async build(options) {
1882
- const { fetchImpl, apiKey } = await options.getFetchProps();
1883
- return new XataApiClient({ fetch: fetchImpl, apiKey });
2565
+ build(options) {
2566
+ return new XataApiClient(options);
1884
2567
  }
1885
2568
  }
1886
2569
 
1887
2570
  class XataPlugin {
1888
2571
  }
1889
2572
 
1890
- function generateUUID() {
1891
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
1892
- const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
1893
- return v.toString(16);
1894
- });
2573
+ class FilesPlugin extends XataPlugin {
2574
+ build(pluginOptions) {
2575
+ return {
2576
+ download: async (location) => {
2577
+ const { table, record, column, fileId = "" } = location ?? {};
2578
+ return await getFileItem({
2579
+ pathParams: {
2580
+ workspace: "{workspaceId}",
2581
+ dbBranchName: "{dbBranch}",
2582
+ region: "{region}",
2583
+ tableName: table ?? "",
2584
+ recordId: record ?? "",
2585
+ columnName: column ?? "",
2586
+ fileId
2587
+ },
2588
+ ...pluginOptions,
2589
+ rawResponse: true
2590
+ });
2591
+ },
2592
+ upload: async (location, file) => {
2593
+ const { table, record, column, fileId = "" } = location ?? {};
2594
+ return await putFileItem({
2595
+ pathParams: {
2596
+ workspace: "{workspaceId}",
2597
+ dbBranchName: "{dbBranch}",
2598
+ region: "{region}",
2599
+ tableName: table ?? "",
2600
+ recordId: record ?? "",
2601
+ columnName: column ?? "",
2602
+ fileId
2603
+ },
2604
+ body: file,
2605
+ ...pluginOptions
2606
+ });
2607
+ },
2608
+ delete: async (location) => {
2609
+ const { table, record, column, fileId = "" } = location ?? {};
2610
+ return await deleteFileItem({
2611
+ pathParams: {
2612
+ workspace: "{workspaceId}",
2613
+ dbBranchName: "{dbBranch}",
2614
+ region: "{region}",
2615
+ tableName: table ?? "",
2616
+ recordId: record ?? "",
2617
+ columnName: column ?? "",
2618
+ fileId
2619
+ },
2620
+ ...pluginOptions
2621
+ });
2622
+ }
2623
+ };
2624
+ }
2625
+ }
2626
+
2627
+ function buildTransformString(transformations) {
2628
+ return transformations.flatMap(
2629
+ (t) => Object.entries(t).map(([key, value]) => {
2630
+ if (key === "trim") {
2631
+ const { left = 0, top = 0, right = 0, bottom = 0 } = value;
2632
+ return `${key}=${[top, right, bottom, left].join(";")}`;
2633
+ }
2634
+ if (key === "gravity" && typeof value === "object") {
2635
+ const { x = 0.5, y = 0.5 } = value;
2636
+ return `${key}=${[x, y].join("x")}`;
2637
+ }
2638
+ return `${key}=${value}`;
2639
+ })
2640
+ ).join(",");
2641
+ }
2642
+ function transformImage(url, transformations) {
2643
+ if (!isDefined(url))
2644
+ return void 0;
2645
+ const transformationsString = buildTransformString(transformations);
2646
+ const { hostname, pathname, search } = new URL(url);
2647
+ return `https://${hostname}/transform/${transformationsString}${pathname}${search}`;
2648
+ }
2649
+
2650
+ var __defProp$6 = Object.defineProperty;
2651
+ var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2652
+ var __publicField$6 = (obj, key, value) => {
2653
+ __defNormalProp$6(obj, typeof key !== "symbol" ? key + "" : key, value);
2654
+ return value;
2655
+ };
2656
+ class XataFile {
2657
+ constructor(file) {
2658
+ /**
2659
+ * Name of this file.
2660
+ */
2661
+ __publicField$6(this, "name");
2662
+ /**
2663
+ * Media type of this file.
2664
+ */
2665
+ __publicField$6(this, "mediaType");
2666
+ /**
2667
+ * Base64 encoded content of this file.
2668
+ */
2669
+ __publicField$6(this, "base64Content");
2670
+ /**
2671
+ * Whether to enable public url for this file.
2672
+ */
2673
+ __publicField$6(this, "enablePublicUrl");
2674
+ /**
2675
+ * Timeout for the signed url.
2676
+ */
2677
+ __publicField$6(this, "signedUrlTimeout");
2678
+ /**
2679
+ * Size of this file.
2680
+ */
2681
+ __publicField$6(this, "size");
2682
+ /**
2683
+ * Version of this file.
2684
+ */
2685
+ __publicField$6(this, "version");
2686
+ /**
2687
+ * Url of this file.
2688
+ */
2689
+ __publicField$6(this, "url");
2690
+ /**
2691
+ * Signed url of this file.
2692
+ */
2693
+ __publicField$6(this, "signedUrl");
2694
+ /**
2695
+ * Attributes of this file.
2696
+ */
2697
+ __publicField$6(this, "attributes");
2698
+ this.name = file.name;
2699
+ this.mediaType = file.mediaType || "application/octet-stream";
2700
+ this.base64Content = file.base64Content;
2701
+ this.enablePublicUrl = file.enablePublicUrl;
2702
+ this.signedUrlTimeout = file.signedUrlTimeout;
2703
+ this.size = file.size;
2704
+ this.version = file.version;
2705
+ this.url = file.url;
2706
+ this.signedUrl = file.signedUrl;
2707
+ this.attributes = file.attributes;
2708
+ }
2709
+ static fromBuffer(buffer, options = {}) {
2710
+ const base64Content = buffer.toString("base64");
2711
+ return new XataFile({ ...options, base64Content });
2712
+ }
2713
+ toBuffer() {
2714
+ if (!this.base64Content) {
2715
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2716
+ }
2717
+ return Buffer.from(this.base64Content, "base64");
2718
+ }
2719
+ static fromArrayBuffer(arrayBuffer, options = {}) {
2720
+ const uint8Array = new Uint8Array(arrayBuffer);
2721
+ return this.fromUint8Array(uint8Array, options);
2722
+ }
2723
+ toArrayBuffer() {
2724
+ if (!this.base64Content) {
2725
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2726
+ }
2727
+ const binary = atob(this.base64Content);
2728
+ return new ArrayBuffer(binary.length);
2729
+ }
2730
+ static fromUint8Array(uint8Array, options = {}) {
2731
+ let binary = "";
2732
+ for (let i = 0; i < uint8Array.byteLength; i++) {
2733
+ binary += String.fromCharCode(uint8Array[i]);
2734
+ }
2735
+ const base64Content = btoa(binary);
2736
+ return new XataFile({ ...options, base64Content });
2737
+ }
2738
+ toUint8Array() {
2739
+ if (!this.base64Content) {
2740
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2741
+ }
2742
+ const binary = atob(this.base64Content);
2743
+ const uint8Array = new Uint8Array(binary.length);
2744
+ for (let i = 0; i < binary.length; i++) {
2745
+ uint8Array[i] = binary.charCodeAt(i);
2746
+ }
2747
+ return uint8Array;
2748
+ }
2749
+ static async fromBlob(file, options = {}) {
2750
+ const name = options.name ?? file.name;
2751
+ const mediaType = file.type;
2752
+ const arrayBuffer = await file.arrayBuffer();
2753
+ return this.fromArrayBuffer(arrayBuffer, { ...options, name, mediaType });
2754
+ }
2755
+ toBlob() {
2756
+ if (!this.base64Content) {
2757
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2758
+ }
2759
+ const arrayBuffer = this.toArrayBuffer();
2760
+ return new Blob([arrayBuffer], { type: this.mediaType });
2761
+ }
2762
+ static fromString(string, options = {}) {
2763
+ const base64Content = btoa(string);
2764
+ return new XataFile({ ...options, base64Content });
2765
+ }
2766
+ toString() {
2767
+ if (!this.base64Content) {
2768
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2769
+ }
2770
+ return atob(this.base64Content);
2771
+ }
2772
+ static fromBase64(base64Content, options = {}) {
2773
+ return new XataFile({ ...options, base64Content });
2774
+ }
2775
+ toBase64() {
2776
+ if (!this.base64Content) {
2777
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2778
+ }
2779
+ return this.base64Content;
2780
+ }
2781
+ transform(...options) {
2782
+ return {
2783
+ url: transformImage(this.url, options),
2784
+ signedUrl: transformImage(this.signedUrl, options)
2785
+ };
2786
+ }
1895
2787
  }
2788
+ const parseInputFileEntry = async (entry) => {
2789
+ if (!isDefined(entry))
2790
+ return null;
2791
+ const { id, name, mediaType, base64Content, enablePublicUrl, signedUrlTimeout } = await entry;
2792
+ return compactObject({ id, name, mediaType, base64Content, enablePublicUrl, signedUrlTimeout });
2793
+ };
1896
2794
 
1897
2795
  function cleanFilter(filter) {
1898
- if (!filter)
2796
+ if (!isDefined(filter))
1899
2797
  return void 0;
1900
- const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
1901
- return values.length > 0 ? filter : void 0;
2798
+ if (!isObject(filter))
2799
+ return filter;
2800
+ const values = Object.fromEntries(
2801
+ Object.entries(filter).reduce((acc, [key, value]) => {
2802
+ if (!isDefined(value))
2803
+ return acc;
2804
+ if (Array.isArray(value)) {
2805
+ const clean = value.map((item) => cleanFilter(item)).filter((item) => isDefined(item));
2806
+ if (clean.length === 0)
2807
+ return acc;
2808
+ return [...acc, [key, clean]];
2809
+ }
2810
+ if (isObject(value)) {
2811
+ const clean = cleanFilter(value);
2812
+ if (!isDefined(clean))
2813
+ return acc;
2814
+ return [...acc, [key, clean]];
2815
+ }
2816
+ return [...acc, [key, value]];
2817
+ }, [])
2818
+ );
2819
+ return Object.keys(values).length > 0 ? values : void 0;
1902
2820
  }
1903
2821
 
2822
+ var __defProp$5 = Object.defineProperty;
2823
+ var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2824
+ var __publicField$5 = (obj, key, value) => {
2825
+ __defNormalProp$5(obj, typeof key !== "symbol" ? key + "" : key, value);
2826
+ return value;
2827
+ };
1904
2828
  var __accessCheck$6 = (obj, member, msg) => {
1905
2829
  if (!member.has(obj))
1906
2830
  throw TypeError("Cannot " + msg);
@@ -1923,22 +2847,58 @@ var _query, _page;
1923
2847
  class Page {
1924
2848
  constructor(query, meta, records = []) {
1925
2849
  __privateAdd$6(this, _query, void 0);
2850
+ /**
2851
+ * Page metadata, required to retrieve additional records.
2852
+ */
2853
+ __publicField$5(this, "meta");
2854
+ /**
2855
+ * The set of results for this page.
2856
+ */
2857
+ __publicField$5(this, "records");
1926
2858
  __privateSet$6(this, _query, query);
1927
2859
  this.meta = meta;
1928
2860
  this.records = new RecordArray(this, records);
1929
2861
  }
2862
+ /**
2863
+ * Retrieves the next page of results.
2864
+ * @param size Maximum number of results to be retrieved.
2865
+ * @param offset Number of results to skip when retrieving the results.
2866
+ * @returns The next page or results.
2867
+ */
1930
2868
  async nextPage(size, offset) {
1931
2869
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
1932
2870
  }
2871
+ /**
2872
+ * Retrieves the previous page of results.
2873
+ * @param size Maximum number of results to be retrieved.
2874
+ * @param offset Number of results to skip when retrieving the results.
2875
+ * @returns The previous page or results.
2876
+ */
1933
2877
  async previousPage(size, offset) {
1934
2878
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
1935
2879
  }
2880
+ /**
2881
+ * Retrieves the start page of results.
2882
+ * @param size Maximum number of results to be retrieved.
2883
+ * @param offset Number of results to skip when retrieving the results.
2884
+ * @returns The start page or results.
2885
+ */
1936
2886
  async startPage(size, offset) {
1937
2887
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, start: this.meta.page.cursor } });
1938
2888
  }
2889
+ /**
2890
+ * Retrieves the end page of results.
2891
+ * @param size Maximum number of results to be retrieved.
2892
+ * @param offset Number of results to skip when retrieving the results.
2893
+ * @returns The end page or results.
2894
+ */
1939
2895
  async endPage(size, offset) {
1940
2896
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, end: this.meta.page.cursor } });
1941
2897
  }
2898
+ /**
2899
+ * Shortcut method to check if there will be additional results if the next page of results is retrieved.
2900
+ * @returns Whether or not there will be additional results in the next page of results.
2901
+ */
1942
2902
  hasNextPage() {
1943
2903
  return this.meta.page.more;
1944
2904
  }
@@ -1951,7 +2911,7 @@ const PAGINATION_DEFAULT_OFFSET = 0;
1951
2911
  function isCursorPaginationOptions(options) {
1952
2912
  return isDefined(options) && (isDefined(options.start) || isDefined(options.end) || isDefined(options.after) || isDefined(options.before));
1953
2913
  }
1954
- const _RecordArray = class extends Array {
2914
+ const _RecordArray = class _RecordArray extends Array {
1955
2915
  constructor(...args) {
1956
2916
  super(..._RecordArray.parseConstructorParams(...args));
1957
2917
  __privateAdd$6(this, _page, void 0);
@@ -1970,32 +2930,67 @@ const _RecordArray = class extends Array {
1970
2930
  toArray() {
1971
2931
  return new Array(...this);
1972
2932
  }
2933
+ toSerializable() {
2934
+ return JSON.parse(this.toString());
2935
+ }
2936
+ toString() {
2937
+ return JSON.stringify(this.toArray());
2938
+ }
1973
2939
  map(callbackfn, thisArg) {
1974
2940
  return this.toArray().map(callbackfn, thisArg);
1975
2941
  }
2942
+ /**
2943
+ * Retrieve next page of records
2944
+ *
2945
+ * @returns A new array of objects
2946
+ */
1976
2947
  async nextPage(size, offset) {
1977
2948
  const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1978
2949
  return new _RecordArray(newPage);
1979
2950
  }
2951
+ /**
2952
+ * Retrieve previous page of records
2953
+ *
2954
+ * @returns A new array of objects
2955
+ */
1980
2956
  async previousPage(size, offset) {
1981
2957
  const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1982
2958
  return new _RecordArray(newPage);
1983
2959
  }
2960
+ /**
2961
+ * Retrieve start page of records
2962
+ *
2963
+ * @returns A new array of objects
2964
+ */
1984
2965
  async startPage(size, offset) {
1985
2966
  const newPage = await __privateGet$6(this, _page).startPage(size, offset);
1986
2967
  return new _RecordArray(newPage);
1987
2968
  }
2969
+ /**
2970
+ * Retrieve end page of records
2971
+ *
2972
+ * @returns A new array of objects
2973
+ */
1988
2974
  async endPage(size, offset) {
1989
2975
  const newPage = await __privateGet$6(this, _page).endPage(size, offset);
1990
2976
  return new _RecordArray(newPage);
1991
2977
  }
2978
+ /**
2979
+ * @returns Boolean indicating if there is a next page
2980
+ */
1992
2981
  hasNextPage() {
1993
2982
  return __privateGet$6(this, _page).meta.page.more;
1994
2983
  }
1995
2984
  };
1996
- let RecordArray = _RecordArray;
1997
2985
  _page = new WeakMap();
2986
+ let RecordArray = _RecordArray;
1998
2987
 
2988
+ var __defProp$4 = Object.defineProperty;
2989
+ var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2990
+ var __publicField$4 = (obj, key, value) => {
2991
+ __defNormalProp$4(obj, typeof key !== "symbol" ? key + "" : key, value);
2992
+ return value;
2993
+ };
1999
2994
  var __accessCheck$5 = (obj, member, msg) => {
2000
2995
  if (!member.has(obj))
2001
2996
  throw TypeError("Cannot " + msg);
@@ -2019,14 +3014,15 @@ var __privateMethod$3 = (obj, member, method) => {
2019
3014
  return method;
2020
3015
  };
2021
3016
  var _table$1, _repository, _data, _cleanFilterConstraint, cleanFilterConstraint_fn;
2022
- const _Query = class {
3017
+ const _Query = class _Query {
2023
3018
  constructor(repository, table, data, rawParent) {
2024
3019
  __privateAdd$5(this, _cleanFilterConstraint);
2025
3020
  __privateAdd$5(this, _table$1, void 0);
2026
3021
  __privateAdd$5(this, _repository, void 0);
2027
3022
  __privateAdd$5(this, _data, { filter: {} });
2028
- this.meta = { page: { cursor: "start", more: true } };
2029
- this.records = new RecordArray(this, []);
3023
+ // Implements pagination
3024
+ __publicField$4(this, "meta", { page: { cursor: "start", more: true, size: PAGINATION_DEFAULT_SIZE } });
3025
+ __publicField$4(this, "records", new RecordArray(this, []));
2030
3026
  __privateSet$5(this, _table$1, table);
2031
3027
  if (repository) {
2032
3028
  __privateSet$5(this, _repository, repository);
@@ -2041,6 +3037,7 @@ const _Query = class {
2041
3037
  __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
2042
3038
  __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
2043
3039
  __privateGet$5(this, _data).columns = data.columns ?? parent?.columns;
3040
+ __privateGet$5(this, _data).consistency = data.consistency ?? parent?.consistency;
2044
3041
  __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
2045
3042
  __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
2046
3043
  __privateGet$5(this, _data).fetchOptions = data.fetchOptions ?? parent?.fetchOptions;
@@ -2061,18 +3058,38 @@ const _Query = class {
2061
3058
  const key = JSON.stringify({ columns, filter, sort, pagination });
2062
3059
  return toBase64(key);
2063
3060
  }
3061
+ /**
3062
+ * Builds a new query object representing a logical OR between the given subqueries.
3063
+ * @param queries An array of subqueries.
3064
+ * @returns A new Query object.
3065
+ */
2064
3066
  any(...queries) {
2065
3067
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
2066
3068
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
2067
3069
  }
3070
+ /**
3071
+ * Builds a new query object representing a logical AND between the given subqueries.
3072
+ * @param queries An array of subqueries.
3073
+ * @returns A new Query object.
3074
+ */
2068
3075
  all(...queries) {
2069
3076
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
2070
3077
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
2071
3078
  }
3079
+ /**
3080
+ * Builds a new query object representing a logical OR negating each subquery. In pseudo-code: !q1 OR !q2
3081
+ * @param queries An array of subqueries.
3082
+ * @returns A new Query object.
3083
+ */
2072
3084
  not(...queries) {
2073
3085
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
2074
3086
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
2075
3087
  }
3088
+ /**
3089
+ * Builds a new query object representing a logical AND negating each subquery. In pseudo-code: !q1 AND !q2
3090
+ * @param queries An array of subqueries.
3091
+ * @returns A new Query object.
3092
+ */
2076
3093
  none(...queries) {
2077
3094
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
2078
3095
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
@@ -2095,6 +3112,11 @@ const _Query = class {
2095
3112
  const sort = [...originalSort, { column, direction }];
2096
3113
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
2097
3114
  }
3115
+ /**
3116
+ * Builds a new query specifying the set of columns to be returned in the query response.
3117
+ * @param columns Array of column names to be returned by the query.
3118
+ * @returns A new Query object.
3119
+ */
2098
3120
  select(columns) {
2099
3121
  return new _Query(
2100
3122
  __privateGet$5(this, _repository),
@@ -2107,6 +3129,12 @@ const _Query = class {
2107
3129
  const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
2108
3130
  return __privateGet$5(this, _repository).query(query);
2109
3131
  }
3132
+ /**
3133
+ * Get results in an iterator
3134
+ *
3135
+ * @async
3136
+ * @returns Async interable of results
3137
+ */
2110
3138
  async *[Symbol.asyncIterator]() {
2111
3139
  for await (const [record] of this.getIterator({ batchSize: 1 })) {
2112
3140
  yield record;
@@ -2167,26 +3195,53 @@ const _Query = class {
2167
3195
  );
2168
3196
  return __privateGet$5(this, _repository).summarizeTable(query, summaries, summariesFilter);
2169
3197
  }
3198
+ /**
3199
+ * Builds a new query object adding a cache TTL in milliseconds.
3200
+ * @param ttl The cache TTL in milliseconds.
3201
+ * @returns A new Query object.
3202
+ */
2170
3203
  cache(ttl) {
2171
3204
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
2172
3205
  }
3206
+ /**
3207
+ * Retrieve next page of records
3208
+ *
3209
+ * @returns A new page object.
3210
+ */
2173
3211
  nextPage(size, offset) {
2174
3212
  return this.startPage(size, offset);
2175
3213
  }
3214
+ /**
3215
+ * Retrieve previous page of records
3216
+ *
3217
+ * @returns A new page object
3218
+ */
2176
3219
  previousPage(size, offset) {
2177
3220
  return this.startPage(size, offset);
2178
3221
  }
3222
+ /**
3223
+ * Retrieve start page of records
3224
+ *
3225
+ * @returns A new page object
3226
+ */
2179
3227
  startPage(size, offset) {
2180
3228
  return this.getPaginated({ pagination: { size, offset } });
2181
3229
  }
3230
+ /**
3231
+ * Retrieve last page of records
3232
+ *
3233
+ * @returns A new page object
3234
+ */
2182
3235
  endPage(size, offset) {
2183
3236
  return this.getPaginated({ pagination: { size, offset, before: "end" } });
2184
3237
  }
3238
+ /**
3239
+ * @returns Boolean indicating if there is a next page
3240
+ */
2185
3241
  hasNextPage() {
2186
3242
  return this.meta.page.more;
2187
3243
  }
2188
3244
  };
2189
- let Query = _Query;
2190
3245
  _table$1 = new WeakMap();
2191
3246
  _repository = new WeakMap();
2192
3247
  _data = new WeakMap();
@@ -2201,6 +3256,7 @@ cleanFilterConstraint_fn = function(column, value) {
2201
3256
  }
2202
3257
  return value;
2203
3258
  };
3259
+ let Query = _Query;
2204
3260
  function cleanParent(data, parent) {
2205
3261
  if (isCursorPaginationOptions(data.pagination)) {
2206
3262
  return { ...parent, sort: void 0, filter: void 0 };
@@ -2208,6 +3264,21 @@ function cleanParent(data, parent) {
2208
3264
  return parent;
2209
3265
  }
2210
3266
 
3267
+ const RecordColumnTypes = [
3268
+ "bool",
3269
+ "int",
3270
+ "float",
3271
+ "string",
3272
+ "text",
3273
+ "email",
3274
+ "multiple",
3275
+ "link",
3276
+ "object",
3277
+ "datetime",
3278
+ "vector",
3279
+ "file[]",
3280
+ "file"
3281
+ ];
2211
3282
  function isIdentifiable(x) {
2212
3283
  return isObject(x) && isString(x?.id);
2213
3284
  }
@@ -2221,7 +3292,11 @@ function isSortFilterString(value) {
2221
3292
  return isString(value);
2222
3293
  }
2223
3294
  function isSortFilterBase(filter) {
2224
- return isObject(filter) && Object.values(filter).every((value) => value === "asc" || value === "desc");
3295
+ return isObject(filter) && Object.entries(filter).every(([key, value]) => {
3296
+ if (key === "*")
3297
+ return value === "random";
3298
+ return value === "asc" || value === "desc";
3299
+ });
2225
3300
  }
2226
3301
  function isSortFilterObject(filter) {
2227
3302
  return isObject(filter) && !isSortFilterBase(filter) && filter.column !== void 0;
@@ -2262,7 +3337,7 @@ var __privateMethod$2 = (obj, member, method) => {
2262
3337
  __accessCheck$4(obj, member, "access private method");
2263
3338
  return method;
2264
3339
  };
2265
- var _table, _getFetchProps, _db, _cache, _schemaTables$2, _trace, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _insertRecords, insertRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _updateRecords, updateRecords_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _deleteRecords, deleteRecords_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaTables$1, getSchemaTables_fn$1;
3340
+ var _table, _getFetchProps, _db, _cache, _schemaTables$2, _trace, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _insertRecords, insertRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _updateRecords, updateRecords_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _deleteRecords, deleteRecords_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaTables$1, getSchemaTables_fn$1, _transformObjectToApi, transformObjectToApi_fn;
2266
3341
  const BULK_OPERATION_MAX_SIZE = 1e3;
2267
3342
  class Repository extends Query {
2268
3343
  }
@@ -2284,6 +3359,7 @@ class RestRepository extends Query {
2284
3359
  __privateAdd$4(this, _setCacheQuery);
2285
3360
  __privateAdd$4(this, _getCacheQuery);
2286
3361
  __privateAdd$4(this, _getSchemaTables$1);
3362
+ __privateAdd$4(this, _transformObjectToApi);
2287
3363
  __privateAdd$4(this, _table, void 0);
2288
3364
  __privateAdd$4(this, _getFetchProps, void 0);
2289
3365
  __privateAdd$4(this, _db, void 0);
@@ -2294,10 +3370,7 @@ class RestRepository extends Query {
2294
3370
  __privateSet$4(this, _db, options.db);
2295
3371
  __privateSet$4(this, _cache, options.pluginOptions.cache);
2296
3372
  __privateSet$4(this, _schemaTables$2, options.schemaTables);
2297
- __privateSet$4(this, _getFetchProps, async () => {
2298
- const props = await options.pluginOptions.getFetchProps();
2299
- return { ...props, sessionID: generateUUID() };
2300
- });
3373
+ __privateSet$4(this, _getFetchProps, () => ({ ...options.pluginOptions, sessionID: generateUUID() }));
2301
3374
  const trace = options.pluginOptions.trace ?? defaultTrace;
2302
3375
  __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
2303
3376
  return trace(name, fn, {
@@ -2354,7 +3427,6 @@ class RestRepository extends Query {
2354
3427
  }
2355
3428
  const id = extractId(a);
2356
3429
  if (id) {
2357
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2358
3430
  try {
2359
3431
  const response = await getRecord({
2360
3432
  pathParams: {
@@ -2365,7 +3437,7 @@ class RestRepository extends Query {
2365
3437
  recordId: id
2366
3438
  },
2367
3439
  queryParams: { columns },
2368
- ...fetchProps
3440
+ ...__privateGet$4(this, _getFetchProps).call(this)
2369
3441
  });
2370
3442
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2371
3443
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2414,13 +3486,19 @@ class RestRepository extends Query {
2414
3486
  const result = await this.read(a, columns);
2415
3487
  return result;
2416
3488
  }
2417
- if (isString(a) && isObject(b)) {
2418
- const columns = isStringArray(c) ? c : void 0;
2419
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2420
- }
2421
- if (isObject(a) && isString(a.id)) {
2422
- const columns = isStringArray(b) ? b : void 0;
2423
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3489
+ try {
3490
+ if (isString(a) && isObject(b)) {
3491
+ const columns = isStringArray(c) ? c : void 0;
3492
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3493
+ }
3494
+ if (isObject(a) && isString(a.id)) {
3495
+ const columns = isStringArray(b) ? b : void 0;
3496
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3497
+ }
3498
+ } catch (error) {
3499
+ if (error.status === 422)
3500
+ return null;
3501
+ throw error;
2424
3502
  }
2425
3503
  throw new Error("Invalid arguments for update method");
2426
3504
  });
@@ -2459,12 +3537,22 @@ class RestRepository extends Query {
2459
3537
  return result;
2460
3538
  }
2461
3539
  if (isString(a) && isObject(b)) {
3540
+ if (a === "")
3541
+ throw new Error("The id can't be empty");
2462
3542
  const columns = isStringArray(c) ? c : void 0;
2463
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3543
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2464
3544
  }
2465
3545
  if (isObject(a) && isString(a.id)) {
3546
+ if (a.id === "")
3547
+ throw new Error("The id can't be empty");
2466
3548
  const columns = isStringArray(c) ? c : void 0;
2467
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3549
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3550
+ }
3551
+ if (!isDefined(a) && isObject(b)) {
3552
+ return await this.create(b, c);
3553
+ }
3554
+ if (isObject(a) && !isDefined(a.id)) {
3555
+ return await this.create(a, b);
2468
3556
  }
2469
3557
  throw new Error("Invalid arguments for createOrUpdate method");
2470
3558
  });
@@ -2481,12 +3569,22 @@ class RestRepository extends Query {
2481
3569
  return result;
2482
3570
  }
2483
3571
  if (isString(a) && isObject(b)) {
3572
+ if (a === "")
3573
+ throw new Error("The id can't be empty");
2484
3574
  const columns = isStringArray(c) ? c : void 0;
2485
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
3575
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
2486
3576
  }
2487
3577
  if (isObject(a) && isString(a.id)) {
3578
+ if (a.id === "")
3579
+ throw new Error("The id can't be empty");
2488
3580
  const columns = isStringArray(c) ? c : void 0;
2489
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3581
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3582
+ }
3583
+ if (!isDefined(a) && isObject(b)) {
3584
+ return await this.create(b, c);
3585
+ }
3586
+ if (isObject(a) && !isDefined(a.id)) {
3587
+ return await this.create(a, b);
2490
3588
  }
2491
3589
  throw new Error("Invalid arguments for createOrReplace method");
2492
3590
  });
@@ -2537,7 +3635,6 @@ class RestRepository extends Query {
2537
3635
  }
2538
3636
  async search(query, options = {}) {
2539
3637
  return __privateGet$4(this, _trace).call(this, "search", async () => {
2540
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2541
3638
  const { records } = await searchTable({
2542
3639
  pathParams: {
2543
3640
  workspace: "{workspaceId}",
@@ -2551,9 +3648,33 @@ class RestRepository extends Query {
2551
3648
  prefix: options.prefix,
2552
3649
  highlight: options.highlight,
2553
3650
  filter: options.filter,
2554
- boosters: options.boosters
3651
+ boosters: options.boosters,
3652
+ page: options.page,
3653
+ target: options.target
3654
+ },
3655
+ ...__privateGet$4(this, _getFetchProps).call(this)
3656
+ });
3657
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3658
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
3659
+ });
3660
+ }
3661
+ async vectorSearch(column, query, options) {
3662
+ return __privateGet$4(this, _trace).call(this, "vectorSearch", async () => {
3663
+ const { records } = await vectorSearchTable({
3664
+ pathParams: {
3665
+ workspace: "{workspaceId}",
3666
+ dbBranchName: "{dbBranch}",
3667
+ region: "{region}",
3668
+ tableName: __privateGet$4(this, _table)
3669
+ },
3670
+ body: {
3671
+ column,
3672
+ queryVector: query,
3673
+ similarityFunction: options?.similarityFunction,
3674
+ size: options?.size,
3675
+ filter: options?.filter
2555
3676
  },
2556
- ...fetchProps
3677
+ ...__privateGet$4(this, _getFetchProps).call(this)
2557
3678
  });
2558
3679
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2559
3680
  return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
@@ -2561,7 +3682,6 @@ class RestRepository extends Query {
2561
3682
  }
2562
3683
  async aggregate(aggs, filter) {
2563
3684
  return __privateGet$4(this, _trace).call(this, "aggregate", async () => {
2564
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2565
3685
  const result = await aggregateTable({
2566
3686
  pathParams: {
2567
3687
  workspace: "{workspaceId}",
@@ -2570,7 +3690,7 @@ class RestRepository extends Query {
2570
3690
  tableName: __privateGet$4(this, _table)
2571
3691
  },
2572
3692
  body: { aggs, filter },
2573
- ...fetchProps
3693
+ ...__privateGet$4(this, _getFetchProps).call(this)
2574
3694
  });
2575
3695
  return result;
2576
3696
  });
@@ -2581,7 +3701,6 @@ class RestRepository extends Query {
2581
3701
  if (cacheQuery)
2582
3702
  return new Page(query, cacheQuery.meta, cacheQuery.records);
2583
3703
  const data = query.getQueryOptions();
2584
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2585
3704
  const { meta, records: objects } = await queryTable({
2586
3705
  pathParams: {
2587
3706
  workspace: "{workspaceId}",
@@ -2593,10 +3712,11 @@ class RestRepository extends Query {
2593
3712
  filter: cleanFilter(data.filter),
2594
3713
  sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2595
3714
  page: data.pagination,
2596
- columns: data.columns ?? ["*"]
3715
+ columns: data.columns ?? ["*"],
3716
+ consistency: data.consistency
2597
3717
  },
2598
3718
  fetchOptions: data.fetchOptions,
2599
- ...fetchProps
3719
+ ...__privateGet$4(this, _getFetchProps).call(this)
2600
3720
  });
2601
3721
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2602
3722
  const records = objects.map(
@@ -2609,7 +3729,6 @@ class RestRepository extends Query {
2609
3729
  async summarizeTable(query, summaries, summariesFilter) {
2610
3730
  return __privateGet$4(this, _trace).call(this, "summarize", async () => {
2611
3731
  const data = query.getQueryOptions();
2612
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2613
3732
  const result = await summarizeTable({
2614
3733
  pathParams: {
2615
3734
  workspace: "{workspaceId}",
@@ -2621,15 +3740,44 @@ class RestRepository extends Query {
2621
3740
  filter: cleanFilter(data.filter),
2622
3741
  sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2623
3742
  columns: data.columns,
3743
+ consistency: data.consistency,
2624
3744
  page: data.pagination?.size !== void 0 ? { size: data.pagination?.size } : void 0,
2625
3745
  summaries,
2626
3746
  summariesFilter
2627
3747
  },
2628
- ...fetchProps
3748
+ ...__privateGet$4(this, _getFetchProps).call(this)
2629
3749
  });
2630
3750
  return result;
2631
3751
  });
2632
3752
  }
3753
+ ask(question, options) {
3754
+ const params = {
3755
+ pathParams: {
3756
+ workspace: "{workspaceId}",
3757
+ dbBranchName: "{dbBranch}",
3758
+ region: "{region}",
3759
+ tableName: __privateGet$4(this, _table)
3760
+ },
3761
+ body: {
3762
+ question,
3763
+ ...options
3764
+ },
3765
+ ...__privateGet$4(this, _getFetchProps).call(this)
3766
+ };
3767
+ if (options?.onMessage) {
3768
+ fetchSSERequest({
3769
+ endpoint: "dataPlane",
3770
+ url: "/db/{dbBranchName}/tables/{tableName}/ask",
3771
+ method: "POST",
3772
+ onMessage: (message) => {
3773
+ options.onMessage?.({ answer: message.text, records: message.records });
3774
+ },
3775
+ ...params
3776
+ });
3777
+ } else {
3778
+ return askTable(params);
3779
+ }
3780
+ }
2633
3781
  }
2634
3782
  _table = new WeakMap();
2635
3783
  _getFetchProps = new WeakMap();
@@ -2639,8 +3787,7 @@ _schemaTables$2 = new WeakMap();
2639
3787
  _trace = new WeakMap();
2640
3788
  _insertRecordWithoutId = new WeakSet();
2641
3789
  insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
2642
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2643
- const record = transformObjectLinks(object);
3790
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2644
3791
  const response = await insertRecord({
2645
3792
  pathParams: {
2646
3793
  workspace: "{workspaceId}",
@@ -2650,15 +3797,16 @@ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
2650
3797
  },
2651
3798
  queryParams: { columns },
2652
3799
  body: record,
2653
- ...fetchProps
3800
+ ...__privateGet$4(this, _getFetchProps).call(this)
2654
3801
  });
2655
3802
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2656
3803
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2657
3804
  };
2658
3805
  _insertRecordWithId = new WeakSet();
2659
3806
  insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { createOnly, ifVersion }) {
2660
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2661
- const record = transformObjectLinks(object);
3807
+ if (!recordId)
3808
+ return null;
3809
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2662
3810
  const response = await insertRecordWithID({
2663
3811
  pathParams: {
2664
3812
  workspace: "{workspaceId}",
@@ -2669,30 +3817,28 @@ insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { crea
2669
3817
  },
2670
3818
  body: record,
2671
3819
  queryParams: { createOnly, columns, ifVersion },
2672
- ...fetchProps
3820
+ ...__privateGet$4(this, _getFetchProps).call(this)
2673
3821
  });
2674
3822
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2675
3823
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2676
3824
  };
2677
3825
  _insertRecords = new WeakSet();
2678
3826
  insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2679
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2680
- const chunkedOperations = chunk(
2681
- objects.map((object) => ({
2682
- insert: { table: __privateGet$4(this, _table), record: transformObjectLinks(object), createOnly, ifVersion }
2683
- })),
2684
- BULK_OPERATION_MAX_SIZE
2685
- );
3827
+ const operations = await promiseMap(objects, async (object) => {
3828
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3829
+ return { insert: { table: __privateGet$4(this, _table), record, createOnly, ifVersion } };
3830
+ });
3831
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
2686
3832
  const ids = [];
2687
- for (const operations of chunkedOperations) {
3833
+ for (const operations2 of chunkedOperations) {
2688
3834
  const { results } = await branchTransaction({
2689
3835
  pathParams: {
2690
3836
  workspace: "{workspaceId}",
2691
3837
  dbBranchName: "{dbBranch}",
2692
3838
  region: "{region}"
2693
3839
  },
2694
- body: { operations },
2695
- ...fetchProps
3840
+ body: { operations: operations2 },
3841
+ ...__privateGet$4(this, _getFetchProps).call(this)
2696
3842
  });
2697
3843
  for (const result of results) {
2698
3844
  if (result.operation === "insert") {
@@ -2706,8 +3852,9 @@ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2706
3852
  };
2707
3853
  _updateRecordWithID = new WeakSet();
2708
3854
  updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2709
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2710
- const { id: _id, ...record } = transformObjectLinks(object);
3855
+ if (!recordId)
3856
+ return null;
3857
+ const { id: _id, ...record } = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2711
3858
  try {
2712
3859
  const response = await updateRecordWithID({
2713
3860
  pathParams: {
@@ -2719,7 +3866,7 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2719
3866
  },
2720
3867
  queryParams: { columns, ifVersion },
2721
3868
  body: record,
2722
- ...fetchProps
3869
+ ...__privateGet$4(this, _getFetchProps).call(this)
2723
3870
  });
2724
3871
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2725
3872
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2732,23 +3879,21 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2732
3879
  };
2733
3880
  _updateRecords = new WeakSet();
2734
3881
  updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2735
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2736
- const chunkedOperations = chunk(
2737
- objects.map(({ id, ...object }) => ({
2738
- update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields: transformObjectLinks(object) }
2739
- })),
2740
- BULK_OPERATION_MAX_SIZE
2741
- );
3882
+ const operations = await promiseMap(objects, async ({ id, ...object }) => {
3883
+ const fields = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3884
+ return { update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields } };
3885
+ });
3886
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
2742
3887
  const ids = [];
2743
- for (const operations of chunkedOperations) {
3888
+ for (const operations2 of chunkedOperations) {
2744
3889
  const { results } = await branchTransaction({
2745
3890
  pathParams: {
2746
3891
  workspace: "{workspaceId}",
2747
3892
  dbBranchName: "{dbBranch}",
2748
3893
  region: "{region}"
2749
3894
  },
2750
- body: { operations },
2751
- ...fetchProps
3895
+ body: { operations: operations2 },
3896
+ ...__privateGet$4(this, _getFetchProps).call(this)
2752
3897
  });
2753
3898
  for (const result of results) {
2754
3899
  if (result.operation === "update") {
@@ -2762,7 +3907,8 @@ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2762
3907
  };
2763
3908
  _upsertRecordWithID = new WeakSet();
2764
3909
  upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2765
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
3910
+ if (!recordId)
3911
+ return null;
2766
3912
  const response = await upsertRecordWithID({
2767
3913
  pathParams: {
2768
3914
  workspace: "{workspaceId}",
@@ -2773,14 +3919,15 @@ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2773
3919
  },
2774
3920
  queryParams: { columns, ifVersion },
2775
3921
  body: object,
2776
- ...fetchProps
3922
+ ...__privateGet$4(this, _getFetchProps).call(this)
2777
3923
  });
2778
3924
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2779
3925
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2780
3926
  };
2781
3927
  _deleteRecord = new WeakSet();
2782
3928
  deleteRecord_fn = async function(recordId, columns = ["*"]) {
2783
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
3929
+ if (!recordId)
3930
+ return null;
2784
3931
  try {
2785
3932
  const response = await deleteRecord({
2786
3933
  pathParams: {
@@ -2791,7 +3938,7 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2791
3938
  recordId
2792
3939
  },
2793
3940
  queryParams: { columns },
2794
- ...fetchProps
3941
+ ...__privateGet$4(this, _getFetchProps).call(this)
2795
3942
  });
2796
3943
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2797
3944
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2804,9 +3951,8 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2804
3951
  };
2805
3952
  _deleteRecords = new WeakSet();
2806
3953
  deleteRecords_fn = async function(recordIds) {
2807
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2808
3954
  const chunkedOperations = chunk(
2809
- recordIds.map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
3955
+ compact(recordIds).map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
2810
3956
  BULK_OPERATION_MAX_SIZE
2811
3957
  );
2812
3958
  for (const operations of chunkedOperations) {
@@ -2817,21 +3963,22 @@ deleteRecords_fn = async function(recordIds) {
2817
3963
  region: "{region}"
2818
3964
  },
2819
3965
  body: { operations },
2820
- ...fetchProps
3966
+ ...__privateGet$4(this, _getFetchProps).call(this)
2821
3967
  });
2822
3968
  }
2823
3969
  };
2824
3970
  _setCacheQuery = new WeakSet();
2825
3971
  setCacheQuery_fn = async function(query, meta, records) {
2826
- await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
3972
+ await __privateGet$4(this, _cache)?.set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: /* @__PURE__ */ new Date(), meta, records });
2827
3973
  };
2828
3974
  _getCacheQuery = new WeakSet();
2829
3975
  getCacheQuery_fn = async function(query) {
2830
3976
  const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
2831
- const result = await __privateGet$4(this, _cache).get(key);
3977
+ const result = await __privateGet$4(this, _cache)?.get(key);
2832
3978
  if (!result)
2833
3979
  return null;
2834
- const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
3980
+ const defaultTTL = __privateGet$4(this, _cache)?.defaultQueryTTL ?? -1;
3981
+ const { cache: ttl = defaultTTL } = query.getQueryOptions();
2835
3982
  if (ttl < 0)
2836
3983
  return null;
2837
3984
  const hasExpired = result.date.getTime() + ttl < Date.now();
@@ -2841,15 +3988,46 @@ _getSchemaTables$1 = new WeakSet();
2841
3988
  getSchemaTables_fn$1 = async function() {
2842
3989
  if (__privateGet$4(this, _schemaTables$2))
2843
3990
  return __privateGet$4(this, _schemaTables$2);
2844
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2845
3991
  const { schema } = await getBranchDetails({
2846
3992
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
2847
- ...fetchProps
3993
+ ...__privateGet$4(this, _getFetchProps).call(this)
2848
3994
  });
2849
3995
  __privateSet$4(this, _schemaTables$2, schema.tables);
2850
3996
  return schema.tables;
2851
3997
  };
2852
- const transformObjectLinks = (object) => {
3998
+ _transformObjectToApi = new WeakSet();
3999
+ transformObjectToApi_fn = async function(object) {
4000
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
4001
+ const schema = schemaTables.find((table) => table.name === __privateGet$4(this, _table));
4002
+ if (!schema)
4003
+ throw new Error(`Table ${__privateGet$4(this, _table)} not found in schema`);
4004
+ const result = {};
4005
+ for (const [key, value] of Object.entries(object)) {
4006
+ if (key === "xata")
4007
+ continue;
4008
+ const type = schema.columns.find((column) => column.name === key)?.type;
4009
+ switch (type) {
4010
+ case "link": {
4011
+ result[key] = isIdentifiable(value) ? value.id : value;
4012
+ break;
4013
+ }
4014
+ case "datetime": {
4015
+ result[key] = value instanceof Date ? value.toISOString() : value;
4016
+ break;
4017
+ }
4018
+ case `file`:
4019
+ result[key] = await parseInputFileEntry(value);
4020
+ break;
4021
+ case "file[]":
4022
+ result[key] = await promiseMap(value, (item) => parseInputFileEntry(item));
4023
+ break;
4024
+ default:
4025
+ result[key] = value;
4026
+ }
4027
+ }
4028
+ return result;
4029
+ };
4030
+ const removeLinksFromObject = (object) => {
2853
4031
  return Object.entries(object).reduce((acc, [key, value]) => {
2854
4032
  if (key === "xata")
2855
4033
  return acc;
@@ -2857,23 +4035,23 @@ const transformObjectLinks = (object) => {
2857
4035
  }, {});
2858
4036
  };
2859
4037
  const initObject = (db, schemaTables, table, object, selectedColumns) => {
2860
- const result = {};
4038
+ const data = {};
2861
4039
  const { xata, ...rest } = object ?? {};
2862
- Object.assign(result, rest);
4040
+ Object.assign(data, rest);
2863
4041
  const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
2864
4042
  if (!columns)
2865
4043
  console.error(`Table ${table} not found in schema`);
2866
4044
  for (const column of columns ?? []) {
2867
4045
  if (!isValidColumn(selectedColumns, column))
2868
4046
  continue;
2869
- const value = result[column.name];
4047
+ const value = data[column.name];
2870
4048
  switch (column.type) {
2871
4049
  case "datetime": {
2872
4050
  const date = value !== void 0 ? new Date(value) : null;
2873
4051
  if (date !== null && isNaN(date.getTime())) {
2874
4052
  console.error(`Failed to parse date ${value} for field ${column.name}`);
2875
4053
  } else {
2876
- result[column.name] = date;
4054
+ data[column.name] = date;
2877
4055
  }
2878
4056
  break;
2879
4057
  }
@@ -2892,44 +4070,60 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
2892
4070
  }
2893
4071
  return acc;
2894
4072
  }, []);
2895
- result[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
4073
+ data[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
2896
4074
  } else {
2897
- result[column.name] = null;
4075
+ data[column.name] = null;
2898
4076
  }
2899
4077
  break;
2900
4078
  }
4079
+ case "file":
4080
+ data[column.name] = isDefined(value) ? new XataFile(value) : null;
4081
+ break;
4082
+ case "file[]":
4083
+ data[column.name] = value?.map((item) => new XataFile(item)) ?? null;
4084
+ break;
2901
4085
  default:
2902
- result[column.name] = value ?? null;
4086
+ data[column.name] = value ?? null;
2903
4087
  if (column.notNull === true && value === null) {
2904
4088
  console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
2905
4089
  }
2906
4090
  break;
2907
4091
  }
2908
4092
  }
2909
- result.read = function(columns2) {
2910
- return db[table].read(result["id"], columns2);
4093
+ const record = { ...data };
4094
+ const serializable = { xata, ...removeLinksFromObject(data) };
4095
+ const metadata = xata !== void 0 ? { ...xata, createdAt: new Date(xata.createdAt), updatedAt: new Date(xata.updatedAt) } : void 0;
4096
+ record.read = function(columns2) {
4097
+ return db[table].read(record["id"], columns2);
2911
4098
  };
2912
- result.update = function(data, b, c) {
4099
+ record.update = function(data2, b, c) {
2913
4100
  const columns2 = isStringArray(b) ? b : ["*"];
2914
4101
  const ifVersion = parseIfVersion(b, c);
2915
- return db[table].update(result["id"], data, columns2, { ifVersion });
4102
+ return db[table].update(record["id"], data2, columns2, { ifVersion });
2916
4103
  };
2917
- result.replace = function(data, b, c) {
4104
+ record.replace = function(data2, b, c) {
2918
4105
  const columns2 = isStringArray(b) ? b : ["*"];
2919
4106
  const ifVersion = parseIfVersion(b, c);
2920
- return db[table].createOrReplace(result["id"], data, columns2, { ifVersion });
4107
+ return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
2921
4108
  };
2922
- result.delete = function() {
2923
- return db[table].delete(result["id"]);
4109
+ record.delete = function() {
4110
+ return db[table].delete(record["id"]);
2924
4111
  };
2925
- result.getMetadata = function() {
2926
- return xata;
4112
+ record.xata = Object.freeze(metadata);
4113
+ record.getMetadata = function() {
4114
+ return record.xata;
2927
4115
  };
2928
- for (const prop of ["read", "update", "replace", "delete", "getMetadata"]) {
2929
- Object.defineProperty(result, prop, { enumerable: false });
4116
+ record.toSerializable = function() {
4117
+ return JSON.parse(JSON.stringify(serializable));
4118
+ };
4119
+ record.toString = function() {
4120
+ return JSON.stringify(serializable);
4121
+ };
4122
+ for (const prop of ["read", "update", "replace", "delete", "getMetadata", "toSerializable", "toString"]) {
4123
+ Object.defineProperty(record, prop, { enumerable: false });
2930
4124
  }
2931
- Object.freeze(result);
2932
- return result;
4125
+ Object.freeze(record);
4126
+ return record;
2933
4127
  };
2934
4128
  function extractId(value) {
2935
4129
  if (isString(value))
@@ -2941,11 +4135,7 @@ function extractId(value) {
2941
4135
  function isValidColumn(columns, column) {
2942
4136
  if (columns.includes("*"))
2943
4137
  return true;
2944
- if (column.type === "link") {
2945
- const linkColumns = columns.filter((item) => item.startsWith(column.name));
2946
- return linkColumns.length > 0;
2947
- }
2948
- return columns.includes(column.name);
4138
+ return columns.filter((item) => item.startsWith(column.name)).length > 0;
2949
4139
  }
2950
4140
  function parseIfVersion(...args) {
2951
4141
  for (const arg of args) {
@@ -2956,6 +4146,12 @@ function parseIfVersion(...args) {
2956
4146
  return void 0;
2957
4147
  }
2958
4148
 
4149
+ var __defProp$3 = Object.defineProperty;
4150
+ var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4151
+ var __publicField$3 = (obj, key, value) => {
4152
+ __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
4153
+ return value;
4154
+ };
2959
4155
  var __accessCheck$3 = (obj, member, msg) => {
2960
4156
  if (!member.has(obj))
2961
4157
  throw TypeError("Cannot " + msg);
@@ -2978,6 +4174,8 @@ var _map;
2978
4174
  class SimpleCache {
2979
4175
  constructor(options = {}) {
2980
4176
  __privateAdd$3(this, _map, void 0);
4177
+ __publicField$3(this, "capacity");
4178
+ __publicField$3(this, "defaultQueryTTL");
2981
4179
  __privateSet$3(this, _map, /* @__PURE__ */ new Map());
2982
4180
  this.capacity = options.max ?? 500;
2983
4181
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
@@ -3113,19 +4311,19 @@ class SearchPlugin extends XataPlugin {
3113
4311
  __privateAdd$1(this, _schemaTables, void 0);
3114
4312
  __privateSet$1(this, _schemaTables, schemaTables);
3115
4313
  }
3116
- build({ getFetchProps }) {
4314
+ build(pluginOptions) {
3117
4315
  return {
3118
4316
  all: async (query, options = {}) => {
3119
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
3120
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
4317
+ const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
4318
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
3121
4319
  return records.map((record) => {
3122
4320
  const { table = "orphan" } = record.xata;
3123
4321
  return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
3124
4322
  });
3125
4323
  },
3126
4324
  byTable: async (query, options = {}) => {
3127
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
3128
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
4325
+ const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
4326
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
3129
4327
  return records.reduce((acc, record) => {
3130
4328
  const { table = "orphan" } = record.xata;
3131
4329
  const items = acc[table] ?? [];
@@ -3138,38 +4336,36 @@ class SearchPlugin extends XataPlugin {
3138
4336
  }
3139
4337
  _schemaTables = new WeakMap();
3140
4338
  _search = new WeakSet();
3141
- search_fn = async function(query, options, getFetchProps) {
3142
- const fetchProps = await getFetchProps();
3143
- const { tables, fuzziness, highlight, prefix } = options ?? {};
4339
+ search_fn = async function(query, options, pluginOptions) {
4340
+ const { tables, fuzziness, highlight, prefix, page } = options ?? {};
3144
4341
  const { records } = await searchBranch({
3145
4342
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3146
- body: { tables, query, fuzziness, prefix, highlight },
3147
- ...fetchProps
4343
+ // @ts-ignore https://github.com/xataio/client-ts/issues/313
4344
+ body: { tables, query, fuzziness, prefix, highlight, page },
4345
+ ...pluginOptions
3148
4346
  });
3149
4347
  return records;
3150
4348
  };
3151
4349
  _getSchemaTables = new WeakSet();
3152
- getSchemaTables_fn = async function(getFetchProps) {
4350
+ getSchemaTables_fn = async function(pluginOptions) {
3153
4351
  if (__privateGet$1(this, _schemaTables))
3154
4352
  return __privateGet$1(this, _schemaTables);
3155
- const fetchProps = await getFetchProps();
3156
4353
  const { schema } = await getBranchDetails({
3157
4354
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3158
- ...fetchProps
4355
+ ...pluginOptions
3159
4356
  });
3160
4357
  __privateSet$1(this, _schemaTables, schema.tables);
3161
4358
  return schema.tables;
3162
4359
  };
3163
4360
 
3164
4361
  class TransactionPlugin extends XataPlugin {
3165
- build({ getFetchProps }) {
4362
+ build(pluginOptions) {
3166
4363
  return {
3167
4364
  run: async (operations) => {
3168
- const fetchProps = await getFetchProps();
3169
4365
  const response = await branchTransaction({
3170
4366
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3171
4367
  body: { operations },
3172
- ...fetchProps
4368
+ ...pluginOptions
3173
4369
  });
3174
4370
  return response;
3175
4371
  }
@@ -3177,93 +4373,12 @@ class TransactionPlugin extends XataPlugin {
3177
4373
  }
3178
4374
  }
3179
4375
 
3180
- const isBranchStrategyBuilder = (strategy) => {
3181
- return typeof strategy === "function";
4376
+ var __defProp$2 = Object.defineProperty;
4377
+ var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4378
+ var __publicField$2 = (obj, key, value) => {
4379
+ __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
4380
+ return value;
3182
4381
  };
3183
-
3184
- async function getCurrentBranchName(options) {
3185
- const { branch, envBranch } = getEnvironment();
3186
- if (branch) {
3187
- const details = await getDatabaseBranch(branch, options);
3188
- if (details)
3189
- return branch;
3190
- console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
3191
- }
3192
- const gitBranch = envBranch || await getGitBranch();
3193
- return resolveXataBranch(gitBranch, options);
3194
- }
3195
- async function getCurrentBranchDetails(options) {
3196
- const branch = await getCurrentBranchName(options);
3197
- return getDatabaseBranch(branch, options);
3198
- }
3199
- async function resolveXataBranch(gitBranch, options) {
3200
- const databaseURL = options?.databaseURL || getDatabaseURL();
3201
- const apiKey = options?.apiKey || getAPIKey();
3202
- if (!databaseURL)
3203
- throw new Error(
3204
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
3205
- );
3206
- if (!apiKey)
3207
- throw new Error(
3208
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
3209
- );
3210
- const [protocol, , host, , dbName] = databaseURL.split("/");
3211
- const urlParts = parseWorkspacesUrlParts(host);
3212
- if (!urlParts)
3213
- throw new Error(`Unable to parse workspace and region: ${databaseURL}`);
3214
- const { workspace, region } = urlParts;
3215
- const { fallbackBranch } = getEnvironment();
3216
- const { branch } = await resolveBranch({
3217
- apiKey,
3218
- apiUrl: databaseURL,
3219
- fetchImpl: getFetchImplementation(options?.fetchImpl),
3220
- workspacesApiUrl: `${protocol}//${host}`,
3221
- pathParams: { dbName, workspace, region },
3222
- queryParams: { gitBranch, fallbackBranch },
3223
- trace: defaultTrace
3224
- });
3225
- return branch;
3226
- }
3227
- async function getDatabaseBranch(branch, options) {
3228
- const databaseURL = options?.databaseURL || getDatabaseURL();
3229
- const apiKey = options?.apiKey || getAPIKey();
3230
- if (!databaseURL)
3231
- throw new Error(
3232
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
3233
- );
3234
- if (!apiKey)
3235
- throw new Error(
3236
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
3237
- );
3238
- const [protocol, , host, , database] = databaseURL.split("/");
3239
- const urlParts = parseWorkspacesUrlParts(host);
3240
- if (!urlParts)
3241
- throw new Error(`Unable to parse workspace and region: ${databaseURL}`);
3242
- const { workspace, region } = urlParts;
3243
- try {
3244
- return await getBranchDetails({
3245
- apiKey,
3246
- apiUrl: databaseURL,
3247
- fetchImpl: getFetchImplementation(options?.fetchImpl),
3248
- workspacesApiUrl: `${protocol}//${host}`,
3249
- pathParams: { dbBranchName: `${database}:${branch}`, workspace, region },
3250
- trace: defaultTrace
3251
- });
3252
- } catch (err) {
3253
- if (isObject(err) && err.status === 404)
3254
- return null;
3255
- throw err;
3256
- }
3257
- }
3258
- function getDatabaseURL() {
3259
- try {
3260
- const { databaseURL } = getEnvironment();
3261
- return databaseURL;
3262
- } catch (err) {
3263
- return void 0;
3264
- }
3265
- }
3266
-
3267
4382
  var __accessCheck = (obj, member, msg) => {
3268
4383
  if (!member.has(obj))
3269
4384
  throw TypeError("Cannot " + msg);
@@ -3287,48 +4402,45 @@ var __privateMethod = (obj, member, method) => {
3287
4402
  return method;
3288
4403
  };
3289
4404
  const buildClient = (plugins) => {
3290
- var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
4405
+ var _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _a;
3291
4406
  return _a = class {
3292
4407
  constructor(options = {}, schemaTables) {
3293
4408
  __privateAdd(this, _parseOptions);
3294
4409
  __privateAdd(this, _getFetchProps);
3295
- __privateAdd(this, _evaluateBranch);
3296
- __privateAdd(this, _branch, void 0);
3297
4410
  __privateAdd(this, _options, void 0);
4411
+ __publicField$2(this, "db");
4412
+ __publicField$2(this, "search");
4413
+ __publicField$2(this, "transactions");
4414
+ __publicField$2(this, "files");
3298
4415
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
3299
4416
  __privateSet(this, _options, safeOptions);
3300
4417
  const pluginOptions = {
3301
- getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
4418
+ ...__privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
3302
4419
  cache: safeOptions.cache,
3303
- trace: safeOptions.trace
4420
+ host: safeOptions.host
3304
4421
  };
3305
4422
  const db = new SchemaPlugin(schemaTables).build(pluginOptions);
3306
4423
  const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
3307
4424
  const transactions = new TransactionPlugin().build(pluginOptions);
4425
+ const files = new FilesPlugin().build(pluginOptions);
3308
4426
  this.db = db;
3309
4427
  this.search = search;
3310
4428
  this.transactions = transactions;
4429
+ this.files = files;
3311
4430
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
3312
4431
  if (namespace === void 0)
3313
4432
  continue;
3314
- const result = namespace.build(pluginOptions);
3315
- if (result instanceof Promise) {
3316
- void result.then((namespace2) => {
3317
- this[key] = namespace2;
3318
- });
3319
- } else {
3320
- this[key] = result;
3321
- }
4433
+ this[key] = namespace.build(pluginOptions);
3322
4434
  }
3323
4435
  }
3324
4436
  async getConfig() {
3325
4437
  const databaseURL = __privateGet(this, _options).databaseURL;
3326
- const branch = await __privateGet(this, _options).branch();
4438
+ const branch = __privateGet(this, _options).branch;
3327
4439
  return { databaseURL, branch };
3328
4440
  }
3329
- }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
4441
+ }, _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3330
4442
  const enableBrowser = options?.enableBrowser ?? getEnableBrowserVariable() ?? false;
3331
- const isBrowser = typeof window !== "undefined";
4443
+ const isBrowser = typeof window !== "undefined" && typeof Deno === "undefined";
3332
4444
  if (isBrowser && !enableBrowser) {
3333
4445
  throw new Error(
3334
4446
  "You are trying to use Xata from the browser, which is potentially a non-secure environment. If you understand the security concerns, such as leaking your credentials, pass `enableBrowser: true` to the client options to remove this error."
@@ -3339,56 +4451,89 @@ const buildClient = (plugins) => {
3339
4451
  const apiKey = options?.apiKey || getAPIKey();
3340
4452
  const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
3341
4453
  const trace = options?.trace ?? defaultTrace;
3342
- const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
4454
+ const clientName = options?.clientName;
4455
+ const host = options?.host ?? "production";
4456
+ const xataAgentExtra = options?.xataAgentExtra;
3343
4457
  if (!apiKey) {
3344
4458
  throw new Error("Option apiKey is required");
3345
4459
  }
3346
4460
  if (!databaseURL) {
3347
4461
  throw new Error("Option databaseURL is required");
3348
4462
  }
3349
- return { fetch, databaseURL, apiKey, branch, cache, trace, clientID: generateUUID(), enableBrowser };
3350
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace, clientID }) {
3351
- const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
3352
- if (!branchValue)
3353
- throw new Error("Unable to resolve branch value");
4463
+ const envBranch = getBranch();
4464
+ const previewBranch = getPreviewBranch();
4465
+ const branch = options?.branch || previewBranch || envBranch || "main";
4466
+ if (!!previewBranch && branch !== previewBranch) {
4467
+ console.warn(
4468
+ `Ignoring preview branch ${previewBranch} because branch option was passed to the client constructor with value ${branch}`
4469
+ );
4470
+ } else if (!!envBranch && branch !== envBranch) {
4471
+ console.warn(
4472
+ `Ignoring branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
4473
+ );
4474
+ } else if (!!previewBranch && !!envBranch && previewBranch !== envBranch) {
4475
+ console.warn(
4476
+ `Ignoring preview branch ${previewBranch} and branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
4477
+ );
4478
+ } else if (!previewBranch && !envBranch && options?.branch === void 0) {
4479
+ console.warn(
4480
+ `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.`
4481
+ );
4482
+ }
4483
+ return {
4484
+ fetch,
4485
+ databaseURL,
4486
+ apiKey,
4487
+ branch,
4488
+ cache,
4489
+ trace,
4490
+ host,
4491
+ clientID: generateUUID(),
4492
+ enableBrowser,
4493
+ clientName,
4494
+ xataAgentExtra
4495
+ };
4496
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = function({
4497
+ fetch,
4498
+ apiKey,
4499
+ databaseURL,
4500
+ branch,
4501
+ trace,
4502
+ clientID,
4503
+ clientName,
4504
+ xataAgentExtra
4505
+ }) {
3354
4506
  return {
3355
- fetchImpl: fetch,
4507
+ fetch,
3356
4508
  apiKey,
3357
4509
  apiUrl: "",
4510
+ // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
3358
4511
  workspacesApiUrl: (path, params) => {
3359
4512
  const hasBranch = params.dbBranchName ?? params.branch;
3360
- const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branchValue}` : "");
4513
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branch}` : "");
3361
4514
  return databaseURL + newPath;
3362
4515
  },
3363
4516
  trace,
3364
- clientID
3365
- };
3366
- }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
3367
- if (__privateGet(this, _branch))
3368
- return __privateGet(this, _branch);
3369
- if (param === void 0)
3370
- return void 0;
3371
- const strategies = Array.isArray(param) ? [...param] : [param];
3372
- const evaluateBranch = async (strategy) => {
3373
- return isBranchStrategyBuilder(strategy) ? await strategy() : strategy;
4517
+ clientID,
4518
+ clientName,
4519
+ xataAgentExtra
3374
4520
  };
3375
- for await (const strategy of strategies) {
3376
- const branch = await evaluateBranch(strategy);
3377
- if (branch) {
3378
- __privateSet(this, _branch, branch);
3379
- return branch;
3380
- }
3381
- }
3382
4521
  }, _a;
3383
4522
  };
3384
4523
  class BaseClient extends buildClient() {
3385
4524
  }
3386
4525
 
4526
+ var __defProp$1 = Object.defineProperty;
4527
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4528
+ var __publicField$1 = (obj, key, value) => {
4529
+ __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
4530
+ return value;
4531
+ };
3387
4532
  const META = "__";
3388
4533
  const VALUE = "___";
3389
4534
  class Serializer {
3390
4535
  constructor() {
3391
- this.classes = {};
4536
+ __publicField$1(this, "classes", {});
3392
4537
  }
3393
4538
  add(clazz) {
3394
4539
  this.classes[clazz.name] = clazz;
@@ -3452,7 +4597,7 @@ const deserialize = (json) => {
3452
4597
  };
3453
4598
 
3454
4599
  function buildWorkerRunner(config) {
3455
- return function xataWorker(name, _worker) {
4600
+ return function xataWorker(name, worker) {
3456
4601
  return async (...args) => {
3457
4602
  const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
3458
4603
  const result = await fetch(url, {
@@ -3466,14 +4611,22 @@ function buildWorkerRunner(config) {
3466
4611
  };
3467
4612
  }
3468
4613
 
4614
+ var __defProp = Object.defineProperty;
4615
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4616
+ var __publicField = (obj, key, value) => {
4617
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4618
+ return value;
4619
+ };
3469
4620
  class XataError extends Error {
3470
4621
  constructor(message, status) {
3471
4622
  super(message);
4623
+ __publicField(this, "status");
3472
4624
  this.status = status;
3473
4625
  }
3474
4626
  }
3475
4627
 
3476
4628
  exports.BaseClient = BaseClient;
4629
+ exports.FetcherError = FetcherError;
3477
4630
  exports.Operations = operationsByTag;
3478
4631
  exports.PAGINATION_DEFAULT_OFFSET = PAGINATION_DEFAULT_OFFSET;
3479
4632
  exports.PAGINATION_DEFAULT_SIZE = PAGINATION_DEFAULT_SIZE;
@@ -3482,6 +4635,7 @@ exports.PAGINATION_MAX_SIZE = PAGINATION_MAX_SIZE;
3482
4635
  exports.Page = Page;
3483
4636
  exports.Query = Query;
3484
4637
  exports.RecordArray = RecordArray;
4638
+ exports.RecordColumnTypes = RecordColumnTypes;
3485
4639
  exports.Repository = Repository;
3486
4640
  exports.RestRepository = RestRepository;
3487
4641
  exports.SchemaPlugin = SchemaPlugin;
@@ -3491,14 +4645,19 @@ exports.SimpleCache = SimpleCache;
3491
4645
  exports.XataApiClient = XataApiClient;
3492
4646
  exports.XataApiPlugin = XataApiPlugin;
3493
4647
  exports.XataError = XataError;
4648
+ exports.XataFile = XataFile;
3494
4649
  exports.XataPlugin = XataPlugin;
3495
4650
  exports.acceptWorkspaceMemberInvite = acceptWorkspaceMemberInvite;
3496
4651
  exports.addGitBranchesEntry = addGitBranchesEntry;
3497
4652
  exports.addTableColumn = addTableColumn;
3498
4653
  exports.aggregateTable = aggregateTable;
3499
4654
  exports.applyBranchSchemaEdit = applyBranchSchemaEdit;
4655
+ exports.askTable = askTable;
4656
+ exports.askTableSession = askTableSession;
3500
4657
  exports.branchTransaction = branchTransaction;
3501
4658
  exports.buildClient = buildClient;
4659
+ exports.buildPreviewBranchName = buildPreviewBranchName;
4660
+ exports.buildProviderString = buildProviderString;
3502
4661
  exports.buildWorkerRunner = buildWorkerRunner;
3503
4662
  exports.bulkInsertTableRecords = bulkInsertTableRecords;
3504
4663
  exports.cancelWorkspaceMemberInvite = cancelWorkspaceMemberInvite;
@@ -3506,20 +4665,19 @@ exports.compareBranchSchemas = compareBranchSchemas;
3506
4665
  exports.compareBranchWithUserSchema = compareBranchWithUserSchema;
3507
4666
  exports.compareMigrationRequest = compareMigrationRequest;
3508
4667
  exports.contains = contains;
4668
+ exports.copyBranch = copyBranch;
3509
4669
  exports.createBranch = createBranch;
3510
4670
  exports.createDatabase = createDatabase;
3511
4671
  exports.createMigrationRequest = createMigrationRequest;
3512
4672
  exports.createTable = createTable;
3513
4673
  exports.createUserAPIKey = createUserAPIKey;
3514
4674
  exports.createWorkspace = createWorkspace;
3515
- exports.dEPRECATEDcreateDatabase = dEPRECATEDcreateDatabase;
3516
- exports.dEPRECATEDdeleteDatabase = dEPRECATEDdeleteDatabase;
3517
- exports.dEPRECATEDgetDatabaseList = dEPRECATEDgetDatabaseList;
3518
- exports.dEPRECATEDgetDatabaseMetadata = dEPRECATEDgetDatabaseMetadata;
3519
- exports.dEPRECATEDupdateDatabaseMetadata = dEPRECATEDupdateDatabaseMetadata;
3520
4675
  exports.deleteBranch = deleteBranch;
3521
4676
  exports.deleteColumn = deleteColumn;
3522
4677
  exports.deleteDatabase = deleteDatabase;
4678
+ exports.deleteDatabaseGithubSettings = deleteDatabaseGithubSettings;
4679
+ exports.deleteFile = deleteFile;
4680
+ exports.deleteFileItem = deleteFileItem;
3523
4681
  exports.deleteRecord = deleteRecord;
3524
4682
  exports.deleteTable = deleteTable;
3525
4683
  exports.deleteUser = deleteUser;
@@ -3530,8 +4688,11 @@ exports.endsWith = endsWith;
3530
4688
  exports.equals = equals;
3531
4689
  exports.executeBranchMigrationPlan = executeBranchMigrationPlan;
3532
4690
  exports.exists = exists;
4691
+ exports.fileAccess = fileAccess;
3533
4692
  exports.ge = ge;
4693
+ exports.generateAccessToken = generateAccessToken;
3534
4694
  exports.getAPIKey = getAPIKey;
4695
+ exports.getBranch = getBranch;
3535
4696
  exports.getBranchDetails = getBranchDetails;
3536
4697
  exports.getBranchList = getBranchList;
3537
4698
  exports.getBranchMetadata = getBranchMetadata;
@@ -3540,15 +4701,17 @@ exports.getBranchMigrationPlan = getBranchMigrationPlan;
3540
4701
  exports.getBranchSchemaHistory = getBranchSchemaHistory;
3541
4702
  exports.getBranchStats = getBranchStats;
3542
4703
  exports.getColumn = getColumn;
3543
- exports.getCurrentBranchDetails = getCurrentBranchDetails;
3544
- exports.getCurrentBranchName = getCurrentBranchName;
4704
+ exports.getDatabaseGithubSettings = getDatabaseGithubSettings;
3545
4705
  exports.getDatabaseList = getDatabaseList;
3546
4706
  exports.getDatabaseMetadata = getDatabaseMetadata;
3547
4707
  exports.getDatabaseURL = getDatabaseURL;
4708
+ exports.getFile = getFile;
4709
+ exports.getFileItem = getFileItem;
3548
4710
  exports.getGitBranchesMapping = getGitBranchesMapping;
3549
4711
  exports.getHostUrl = getHostUrl;
3550
4712
  exports.getMigrationRequest = getMigrationRequest;
3551
4713
  exports.getMigrationRequestIsMerged = getMigrationRequestIsMerged;
4714
+ exports.getPreviewBranch = getPreviewBranch;
3552
4715
  exports.getRecord = getRecord;
3553
4716
  exports.getTableColumns = getTableColumns;
3554
4717
  exports.getTableSchema = getTableSchema;
@@ -3557,6 +4720,7 @@ exports.getUserAPIKeys = getUserAPIKeys;
3557
4720
  exports.getWorkspace = getWorkspace;
3558
4721
  exports.getWorkspaceMembersList = getWorkspaceMembersList;
3559
4722
  exports.getWorkspacesList = getWorkspacesList;
4723
+ exports.grantAuthorizationCode = grantAuthorizationCode;
3560
4724
  exports.greaterEquals = greaterEquals;
3561
4725
  exports.greaterThan = greaterThan;
3562
4726
  exports.greaterThanEquals = greaterThanEquals;
@@ -3591,21 +4755,27 @@ exports.parseProviderString = parseProviderString;
3591
4755
  exports.parseWorkspacesUrlParts = parseWorkspacesUrlParts;
3592
4756
  exports.pattern = pattern;
3593
4757
  exports.previewBranchSchemaEdit = previewBranchSchemaEdit;
4758
+ exports.pushBranchMigrations = pushBranchMigrations;
4759
+ exports.putFile = putFile;
4760
+ exports.putFileItem = putFileItem;
3594
4761
  exports.queryMigrationRequests = queryMigrationRequests;
3595
4762
  exports.queryTable = queryTable;
3596
4763
  exports.removeGitBranchesEntry = removeGitBranchesEntry;
3597
4764
  exports.removeWorkspaceMember = removeWorkspaceMember;
4765
+ exports.renameDatabase = renameDatabase;
3598
4766
  exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite;
3599
4767
  exports.resolveBranch = resolveBranch;
3600
4768
  exports.searchBranch = searchBranch;
3601
4769
  exports.searchTable = searchTable;
3602
4770
  exports.serialize = serialize;
3603
4771
  exports.setTableSchema = setTableSchema;
4772
+ exports.sqlQuery = sqlQuery;
3604
4773
  exports.startsWith = startsWith;
3605
4774
  exports.summarizeTable = summarizeTable;
3606
4775
  exports.updateBranchMetadata = updateBranchMetadata;
3607
4776
  exports.updateBranchSchema = updateBranchSchema;
3608
4777
  exports.updateColumn = updateColumn;
4778
+ exports.updateDatabaseGithubSettings = updateDatabaseGithubSettings;
3609
4779
  exports.updateDatabaseMetadata = updateDatabaseMetadata;
3610
4780
  exports.updateMigrationRequest = updateMigrationRequest;
3611
4781
  exports.updateRecordWithID = updateRecordWithID;
@@ -3615,4 +4785,5 @@ exports.updateWorkspace = updateWorkspace;
3615
4785
  exports.updateWorkspaceMemberInvite = updateWorkspaceMemberInvite;
3616
4786
  exports.updateWorkspaceMemberRole = updateWorkspaceMemberRole;
3617
4787
  exports.upsertRecordWithID = upsertRecordWithID;
4788
+ exports.vectorSearchTable = vectorSearchTable;
3618
4789
  //# sourceMappingURL=index.cjs.map