@xata.io/client 0.0.0-alpha.vf85aa00 → 0.0.0-alpha.vf864fe862f895317faad5b0041a40e871fe5ad03

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -18,7 +18,8 @@ const TraceAttributes = {
18
18
  HTTP_METHOD: "http.method",
19
19
  HTTP_URL: "http.url",
20
20
  HTTP_ROUTE: "http.route",
21
- HTTP_TARGET: "http.target"
21
+ HTTP_TARGET: "http.target",
22
+ CLOUDFLARE_RAY_ID: "cf.ray"
22
23
  };
23
24
 
24
25
  function notEmpty(value) {
@@ -27,8 +28,18 @@ function notEmpty(value) {
27
28
  function compact(arr) {
28
29
  return arr.filter(notEmpty);
29
30
  }
31
+ function compactObject(obj) {
32
+ return Object.fromEntries(Object.entries(obj).filter(([, value]) => notEmpty(value)));
33
+ }
34
+ function isBlob(value) {
35
+ try {
36
+ return value instanceof Blob;
37
+ } catch (error) {
38
+ return false;
39
+ }
40
+ }
30
41
  function isObject(value) {
31
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
42
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date) && !isBlob(value);
32
43
  }
33
44
  function isDefined(value) {
34
45
  return value !== null && value !== void 0;
@@ -83,6 +94,27 @@ function chunk(array, chunkSize) {
83
94
  async function timeout(ms) {
84
95
  return new Promise((resolve) => setTimeout(resolve, ms));
85
96
  }
97
+ function timeoutWithCancel(ms) {
98
+ let timeoutId;
99
+ const promise = new Promise((resolve) => {
100
+ timeoutId = setTimeout(() => {
101
+ resolve();
102
+ }, ms);
103
+ });
104
+ return {
105
+ cancel: () => clearTimeout(timeoutId),
106
+ promise
107
+ };
108
+ }
109
+ function promiseMap(inputValues, mapper) {
110
+ const reducer = (acc$, inputValue) => acc$.then(
111
+ (acc) => mapper(inputValue).then((result) => {
112
+ acc.push(result);
113
+ return acc;
114
+ })
115
+ );
116
+ return inputValues.reduce(reducer, Promise.resolve([]));
117
+ }
86
118
 
87
119
  function getEnvironment() {
88
120
  try {
@@ -182,7 +214,7 @@ function getAPIKey() {
182
214
  function getBranch() {
183
215
  try {
184
216
  const { branch } = getEnvironment();
185
- return branch ?? "main";
217
+ return branch;
186
218
  } catch (err) {
187
219
  return void 0;
188
220
  }
@@ -214,7 +246,7 @@ var __accessCheck$8 = (obj, member, msg) => {
214
246
  if (!member.has(obj))
215
247
  throw TypeError("Cannot " + msg);
216
248
  };
217
- var __privateGet$8 = (obj, member, getter) => {
249
+ var __privateGet$7 = (obj, member, getter) => {
218
250
  __accessCheck$8(obj, member, "read from private field");
219
251
  return getter ? getter.call(obj) : member.get(obj);
220
252
  };
@@ -223,7 +255,7 @@ var __privateAdd$8 = (obj, member, value) => {
223
255
  throw TypeError("Cannot add the same private member more than once");
224
256
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
225
257
  };
226
- var __privateSet$8 = (obj, member, value, setter) => {
258
+ var __privateSet$6 = (obj, member, value, setter) => {
227
259
  __accessCheck$8(obj, member, "write to private field");
228
260
  setter ? setter.call(obj, value) : member.set(obj, value);
229
261
  return value;
@@ -233,13 +265,13 @@ var __privateMethod$4 = (obj, member, method) => {
233
265
  return method;
234
266
  };
235
267
  var _fetch, _queue, _concurrency, _enqueue, enqueue_fn;
268
+ const REQUEST_TIMEOUT = 5 * 60 * 1e3;
236
269
  function getFetchImplementation(userFetch) {
237
270
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
238
- const fetchImpl = userFetch ?? globalFetch;
271
+ const globalThisFetch = typeof globalThis !== "undefined" ? globalThis.fetch : void 0;
272
+ const fetchImpl = userFetch ?? globalFetch ?? globalThisFetch;
239
273
  if (!fetchImpl) {
240
- throw new Error(
241
- `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
242
- );
274
+ throw new Error(`Couldn't find a global \`fetch\`. Pass a fetch implementation explicitly.`);
243
275
  }
244
276
  return fetchImpl;
245
277
  }
@@ -249,33 +281,37 @@ class ApiRequestPool {
249
281
  __privateAdd$8(this, _fetch, void 0);
250
282
  __privateAdd$8(this, _queue, void 0);
251
283
  __privateAdd$8(this, _concurrency, void 0);
252
- __privateSet$8(this, _queue, []);
253
- __privateSet$8(this, _concurrency, concurrency);
284
+ __privateSet$6(this, _queue, []);
285
+ __privateSet$6(this, _concurrency, concurrency);
254
286
  this.running = 0;
255
287
  this.started = 0;
256
288
  }
257
289
  setFetch(fetch2) {
258
- __privateSet$8(this, _fetch, fetch2);
290
+ __privateSet$6(this, _fetch, fetch2);
259
291
  }
260
292
  getFetch() {
261
- if (!__privateGet$8(this, _fetch)) {
293
+ if (!__privateGet$7(this, _fetch)) {
262
294
  throw new Error("Fetch not set");
263
295
  }
264
- return __privateGet$8(this, _fetch);
296
+ return __privateGet$7(this, _fetch);
265
297
  }
266
298
  request(url, options) {
267
- const start = new Date();
268
- const fetch2 = this.getFetch();
299
+ const start = /* @__PURE__ */ new Date();
300
+ const fetchImpl = this.getFetch();
269
301
  const runRequest = async (stalled = false) => {
270
- const response = await fetch2(url, options);
302
+ const { promise, cancel } = timeoutWithCancel(REQUEST_TIMEOUT);
303
+ const response = await Promise.race([fetchImpl(url, options), promise.then(() => null)]).finally(cancel);
304
+ if (!response) {
305
+ throw new Error("Request timed out");
306
+ }
271
307
  if (response.status === 429) {
272
308
  const rateLimitReset = parseNumber(response.headers?.get("x-ratelimit-reset")) ?? 1;
273
309
  await timeout(rateLimitReset * 1e3);
274
310
  return await runRequest(true);
275
311
  }
276
312
  if (stalled) {
277
- const stalledTime = new Date().getTime() - start.getTime();
278
- console.warn(`A request to Xata hit your workspace limits, was retried and stalled for ${stalledTime}ms`);
313
+ const stalledTime = (/* @__PURE__ */ new Date()).getTime() - start.getTime();
314
+ console.warn(`A request to Xata hit branch rate limits, was retried and stalled for ${stalledTime}ms`);
279
315
  }
280
316
  return response;
281
317
  };
@@ -289,19 +325,19 @@ _queue = new WeakMap();
289
325
  _concurrency = new WeakMap();
290
326
  _enqueue = new WeakSet();
291
327
  enqueue_fn = function(task) {
292
- const promise = new Promise((resolve) => __privateGet$8(this, _queue).push(resolve)).finally(() => {
328
+ const promise = new Promise((resolve) => __privateGet$7(this, _queue).push(resolve)).finally(() => {
293
329
  this.started--;
294
330
  this.running++;
295
331
  }).then(() => task()).finally(() => {
296
332
  this.running--;
297
- const next = __privateGet$8(this, _queue).shift();
333
+ const next = __privateGet$7(this, _queue).shift();
298
334
  if (next !== void 0) {
299
335
  this.started++;
300
336
  next();
301
337
  }
302
338
  });
303
- if (this.running + this.started < __privateGet$8(this, _concurrency)) {
304
- const next = __privateGet$8(this, _queue).shift();
339
+ if (this.running + this.started < __privateGet$7(this, _concurrency)) {
340
+ const next = __privateGet$7(this, _queue).shift();
305
341
  if (next !== void 0) {
306
342
  this.started++;
307
343
  next();
@@ -490,7 +526,7 @@ function defaultOnOpen(response) {
490
526
  }
491
527
  }
492
528
 
493
- const VERSION = "0.23.4";
529
+ const VERSION = "0.29.0";
494
530
 
495
531
  class ErrorWithCause extends Error {
496
532
  constructor(message, options) {
@@ -533,6 +569,67 @@ function getMessage(data) {
533
569
  }
534
570
  }
535
571
 
572
+ function getHostUrl(provider, type) {
573
+ if (isHostProviderAlias(provider)) {
574
+ return providers[provider][type];
575
+ } else if (isHostProviderBuilder(provider)) {
576
+ return provider[type];
577
+ }
578
+ throw new Error("Invalid API provider");
579
+ }
580
+ const providers = {
581
+ production: {
582
+ main: "https://api.xata.io",
583
+ workspaces: "https://{workspaceId}.{region}.xata.sh"
584
+ },
585
+ staging: {
586
+ main: "https://api.staging-xata.dev",
587
+ workspaces: "https://{workspaceId}.{region}.staging-xata.dev"
588
+ },
589
+ dev: {
590
+ main: "https://api.dev-xata.dev",
591
+ workspaces: "https://{workspaceId}.{region}.dev-xata.dev"
592
+ },
593
+ local: {
594
+ main: "http://localhost:6001",
595
+ workspaces: "http://{workspaceId}.{region}.localhost:6001"
596
+ }
597
+ };
598
+ function isHostProviderAlias(alias) {
599
+ return isString(alias) && Object.keys(providers).includes(alias);
600
+ }
601
+ function isHostProviderBuilder(builder) {
602
+ return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
603
+ }
604
+ function parseProviderString(provider = "production") {
605
+ if (isHostProviderAlias(provider)) {
606
+ return provider;
607
+ }
608
+ const [main, workspaces] = provider.split(",");
609
+ if (!main || !workspaces)
610
+ return null;
611
+ return { main, workspaces };
612
+ }
613
+ function buildProviderString(provider) {
614
+ if (isHostProviderAlias(provider))
615
+ return provider;
616
+ return `${provider.main},${provider.workspaces}`;
617
+ }
618
+ function parseWorkspacesUrlParts(url) {
619
+ if (!isString(url))
620
+ return null;
621
+ const matches = {
622
+ production: url.match(/(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/),
623
+ staging: url.match(/(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.staging-xata\.dev.*/),
624
+ dev: url.match(/(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.dev-xata\.dev.*/),
625
+ local: url.match(/(?:https?:\/\/)?([^.]+)(?:\.([^.]+))\.localhost:(\d+)/)
626
+ };
627
+ const [host, match] = Object.entries(matches).find(([, match2]) => match2 !== null) ?? [];
628
+ if (!isHostProviderAlias(host) || !match)
629
+ return null;
630
+ return { workspace: match[1], region: match[2], host };
631
+ }
632
+
536
633
  const pool = new ApiRequestPool();
537
634
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
538
635
  const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
@@ -548,6 +645,7 @@ const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
548
645
  return url.replace(/\{\w*\}/g, (key) => cleanPathParams[key.slice(1, -1)]) + queryString;
549
646
  };
550
647
  function buildBaseUrl({
648
+ method,
551
649
  endpoint,
552
650
  path,
553
651
  workspacesApiUrl,
@@ -555,7 +653,24 @@ function buildBaseUrl({
555
653
  pathParams = {}
556
654
  }) {
557
655
  if (endpoint === "dataPlane") {
558
- const url = isString(workspacesApiUrl) ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
656
+ let url = isString(workspacesApiUrl) ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
657
+ if (method.toUpperCase() === "PUT" && [
658
+ "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
659
+ "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}"
660
+ ].includes(path)) {
661
+ const { host } = parseWorkspacesUrlParts(url) ?? {};
662
+ switch (host) {
663
+ case "production":
664
+ url = url.replace("xata.sh", "upload.xata.sh");
665
+ break;
666
+ case "staging":
667
+ url = url.replace("staging-xata.dev", "upload.staging-xata.dev");
668
+ break;
669
+ case "dev":
670
+ url = url.replace("dev-xata.dev", "upload.dev-xata.dev");
671
+ break;
672
+ }
673
+ }
559
674
  const urlWithWorkspace = isString(pathParams.workspace) ? url.replace("{workspaceId}", String(pathParams.workspace)) : url;
560
675
  return isString(pathParams.region) ? urlWithWorkspace.replace("{region}", String(pathParams.region)) : urlWithWorkspace;
561
676
  }
@@ -566,6 +681,18 @@ function hostHeader(url) {
566
681
  const { groups } = pattern.exec(url) ?? {};
567
682
  return groups?.host ? { Host: groups.host } : {};
568
683
  }
684
+ async function parseBody(body, headers) {
685
+ if (!isDefined(body))
686
+ return void 0;
687
+ if (isBlob(body) || typeof body.text === "function") {
688
+ return body;
689
+ }
690
+ const { "Content-Type": contentType } = headers ?? {};
691
+ if (String(contentType).toLowerCase() === "application/json" && isObject(body)) {
692
+ return JSON.stringify(body);
693
+ }
694
+ return body;
695
+ }
569
696
  const defaultClientID = generateUUID();
570
697
  async function fetch$1({
571
698
  url: path,
@@ -585,15 +712,16 @@ async function fetch$1({
585
712
  sessionID,
586
713
  clientName,
587
714
  xataAgentExtra,
588
- fetchOptions = {}
715
+ fetchOptions = {},
716
+ rawResponse = false
589
717
  }) {
590
718
  pool.setFetch(fetch2);
591
719
  return await trace(
592
720
  `${method.toUpperCase()} ${path}`,
593
721
  async ({ setAttributes }) => {
594
- const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
722
+ const baseUrl = buildBaseUrl({ method, endpoint, path, workspacesApiUrl, pathParams, apiUrl });
595
723
  const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
596
- const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
724
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\.[^.]+\./, "http://") : fullUrl;
597
725
  setAttributes({
598
726
  [TraceAttributes.HTTP_URL]: url,
599
727
  [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
@@ -604,7 +732,7 @@ async function fetch$1({
604
732
  isDefined(clientName) ? ["service", clientName] : void 0,
605
733
  ...Object.entries(xataAgentExtra ?? {})
606
734
  ]).map(([key, value]) => `${key}=${value}`).join("; ");
607
- const headers = {
735
+ const headers = compactObject({
608
736
  "Accept-Encoding": "identity",
609
737
  "Content-Type": "application/json",
610
738
  "X-Xata-Client-ID": clientID ?? defaultClientID,
@@ -613,11 +741,11 @@ async function fetch$1({
613
741
  ...customHeaders,
614
742
  ...hostHeader(fullUrl),
615
743
  Authorization: `Bearer ${apiKey}`
616
- };
744
+ });
617
745
  const response = await pool.request(url, {
618
746
  ...fetchOptions,
619
747
  method: method.toUpperCase(),
620
- body: body ? JSON.stringify(body) : void 0,
748
+ body: await parseBody(body, headers),
621
749
  headers,
622
750
  signal
623
751
  });
@@ -628,8 +756,12 @@ async function fetch$1({
628
756
  [TraceAttributes.HTTP_REQUEST_ID]: requestId,
629
757
  [TraceAttributes.HTTP_STATUS_CODE]: response.status,
630
758
  [TraceAttributes.HTTP_HOST]: host,
631
- [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
759
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", ""),
760
+ [TraceAttributes.CLOUDFLARE_RAY_ID]: response.headers?.get("cf-ray") ?? void 0
632
761
  });
762
+ const message = response.headers?.get("x-xata-message");
763
+ if (message)
764
+ console.warn(message);
633
765
  if (response.status === 204) {
634
766
  return {};
635
767
  }
@@ -637,7 +769,7 @@ async function fetch$1({
637
769
  throw new FetcherError(response.status, "Rate limit exceeded", requestId);
638
770
  }
639
771
  try {
640
- const jsonResponse = await response.json();
772
+ const jsonResponse = rawResponse ? await response.blob() : await response.json();
641
773
  if (response.ok) {
642
774
  return jsonResponse;
643
775
  }
@@ -670,7 +802,7 @@ function fetchSSERequest({
670
802
  clientName,
671
803
  xataAgentExtra
672
804
  }) {
673
- const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
805
+ const baseUrl = buildBaseUrl({ method, endpoint, path, workspacesApiUrl, pathParams, apiUrl });
674
806
  const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
675
807
  const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
676
808
  void fetchEventSource(url, {
@@ -713,6 +845,20 @@ function parseUrl(url) {
713
845
 
714
846
  const dataPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "dataPlane" });
715
847
 
848
+ const applyMigration = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/pgroll/apply", method: "post", ...variables, signal });
849
+ const pgRollStatus = (variables, signal) => dataPlaneFetch({
850
+ url: "/db/{dbBranchName}/pgroll/status",
851
+ method: "get",
852
+ ...variables,
853
+ signal
854
+ });
855
+ const pgRollJobStatus = (variables, signal) => dataPlaneFetch({
856
+ url: "/db/{dbBranchName}/pgroll/jobs/{jobId}",
857
+ method: "get",
858
+ ...variables,
859
+ signal
860
+ });
861
+ const pgRollMigrationHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/pgroll/migrations", method: "get", ...variables, signal });
716
862
  const getBranchList = (variables, signal) => dataPlaneFetch({
717
863
  url: "/dbs/{dbName}",
718
864
  method: "get",
@@ -732,6 +878,12 @@ const deleteBranch = (variables, signal) => dataPlaneFetch({
732
878
  ...variables,
733
879
  signal
734
880
  });
881
+ const getSchema = (variables, signal) => dataPlaneFetch({
882
+ url: "/db/{dbBranchName}/schema",
883
+ method: "get",
884
+ ...variables,
885
+ signal
886
+ });
735
887
  const copyBranch = (variables, signal) => dataPlaneFetch({
736
888
  url: "/db/{dbBranchName}/copy",
737
889
  method: "post",
@@ -832,6 +984,42 @@ const deleteColumn = (variables, signal) => dataPlaneFetch({
832
984
  });
833
985
  const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
834
986
  const insertRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
987
+ const getFileItem = (variables, signal) => dataPlaneFetch({
988
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
989
+ method: "get",
990
+ ...variables,
991
+ signal
992
+ });
993
+ const putFileItem = (variables, signal) => dataPlaneFetch({
994
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
995
+ method: "put",
996
+ ...variables,
997
+ signal
998
+ });
999
+ const deleteFileItem = (variables, signal) => dataPlaneFetch({
1000
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
1001
+ method: "delete",
1002
+ ...variables,
1003
+ signal
1004
+ });
1005
+ const getFile = (variables, signal) => dataPlaneFetch({
1006
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
1007
+ method: "get",
1008
+ ...variables,
1009
+ signal
1010
+ });
1011
+ const putFile = (variables, signal) => dataPlaneFetch({
1012
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
1013
+ method: "put",
1014
+ ...variables,
1015
+ signal
1016
+ });
1017
+ const deleteFile = (variables, signal) => dataPlaneFetch({
1018
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
1019
+ method: "delete",
1020
+ ...variables,
1021
+ signal
1022
+ });
835
1023
  const getRecord = (variables, signal) => dataPlaneFetch({
836
1024
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
837
1025
  method: "get",
@@ -861,12 +1049,6 @@ const searchTable = (variables, signal) => dataPlaneFetch({
861
1049
  ...variables,
862
1050
  signal
863
1051
  });
864
- const sqlQuery = (variables, signal) => dataPlaneFetch({
865
- url: "/db/{dbBranchName}/sql",
866
- method: "post",
867
- ...variables,
868
- signal
869
- });
870
1052
  const vectorSearchTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/vectorSearch", method: "post", ...variables, signal });
871
1053
  const askTable = (variables, signal) => dataPlaneFetch({
872
1054
  url: "/db/{dbBranchName}/tables/{tableName}/ask",
@@ -874,10 +1056,33 @@ const askTable = (variables, signal) => dataPlaneFetch({
874
1056
  ...variables,
875
1057
  signal
876
1058
  });
1059
+ const askTableSession = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}", method: "post", ...variables, signal });
877
1060
  const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
878
1061
  const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
1062
+ const fileAccess = (variables, signal) => dataPlaneFetch({
1063
+ url: "/file/{fileId}",
1064
+ method: "get",
1065
+ ...variables,
1066
+ signal
1067
+ });
1068
+ const fileUpload = (variables, signal) => dataPlaneFetch({
1069
+ url: "/file/{fileId}",
1070
+ method: "put",
1071
+ ...variables,
1072
+ signal
1073
+ });
1074
+ const sqlQuery = (variables, signal) => dataPlaneFetch({
1075
+ url: "/db/{dbBranchName}/sql",
1076
+ method: "post",
1077
+ ...variables,
1078
+ signal
1079
+ });
879
1080
  const operationsByTag$2 = {
880
1081
  branch: {
1082
+ applyMigration,
1083
+ pgRollStatus,
1084
+ pgRollJobStatus,
1085
+ pgRollMigrationHistory,
881
1086
  getBranchList,
882
1087
  getBranchDetails,
883
1088
  createBranch,
@@ -892,6 +1097,7 @@ const operationsByTag$2 = {
892
1097
  resolveBranch
893
1098
  },
894
1099
  migrations: {
1100
+ getSchema,
895
1101
  getBranchMigrationHistory,
896
1102
  getBranchMigrationPlan,
897
1103
  executeBranchMigrationPlan,
@@ -935,20 +1141,24 @@ const operationsByTag$2 = {
935
1141
  deleteRecord,
936
1142
  bulkInsertTableRecords
937
1143
  },
1144
+ files: { getFileItem, putFileItem, deleteFileItem, getFile, putFile, deleteFile, fileAccess, fileUpload },
938
1145
  searchAndFilter: {
939
1146
  queryTable,
940
1147
  searchBranch,
941
1148
  searchTable,
942
- sqlQuery,
943
1149
  vectorSearchTable,
944
1150
  askTable,
1151
+ askTableSession,
945
1152
  summarizeTable,
946
1153
  aggregateTable
947
- }
1154
+ },
1155
+ sql: { sqlQuery }
948
1156
  };
949
1157
 
950
1158
  const controlPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "controlPlane" });
951
1159
 
1160
+ const getAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "get", ...variables, signal });
1161
+ const grantAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "post", ...variables, signal });
952
1162
  const getUser = (variables, signal) => controlPlaneFetch({
953
1163
  url: "/user",
954
1164
  method: "get",
@@ -985,6 +1195,31 @@ const deleteUserAPIKey = (variables, signal) => controlPlaneFetch({
985
1195
  ...variables,
986
1196
  signal
987
1197
  });
1198
+ const getUserOAuthClients = (variables, signal) => controlPlaneFetch({
1199
+ url: "/user/oauth/clients",
1200
+ method: "get",
1201
+ ...variables,
1202
+ signal
1203
+ });
1204
+ const deleteUserOAuthClient = (variables, signal) => controlPlaneFetch({
1205
+ url: "/user/oauth/clients/{clientId}",
1206
+ method: "delete",
1207
+ ...variables,
1208
+ signal
1209
+ });
1210
+ const getUserOAuthAccessTokens = (variables, signal) => controlPlaneFetch({
1211
+ url: "/user/oauth/tokens",
1212
+ method: "get",
1213
+ ...variables,
1214
+ signal
1215
+ });
1216
+ const deleteOAuthAccessToken = (variables, signal) => controlPlaneFetch({
1217
+ url: "/user/oauth/tokens/{token}",
1218
+ method: "delete",
1219
+ ...variables,
1220
+ signal
1221
+ });
1222
+ const updateOAuthAccessToken = (variables, signal) => controlPlaneFetch({ url: "/user/oauth/tokens/{token}", method: "patch", ...variables, signal });
988
1223
  const getWorkspacesList = (variables, signal) => controlPlaneFetch({
989
1224
  url: "/workspaces",
990
1225
  method: "get",
@@ -1028,6 +1263,15 @@ const updateWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ u
1028
1263
  const cancelWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "delete", ...variables, signal });
1029
1264
  const acceptWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept", method: "post", ...variables, signal });
1030
1265
  const resendWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}/resend", method: "post", ...variables, signal });
1266
+ const listClusters = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/clusters", method: "get", ...variables, signal });
1267
+ const createCluster = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/clusters", method: "post", ...variables, signal });
1268
+ const getCluster = (variables, signal) => controlPlaneFetch({
1269
+ url: "/workspaces/{workspaceId}/clusters/{clusterId}",
1270
+ method: "get",
1271
+ ...variables,
1272
+ signal
1273
+ });
1274
+ const updateCluster = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/clusters/{clusterId}", method: "patch", ...variables, signal });
1031
1275
  const getDatabaseList = (variables, signal) => controlPlaneFetch({
1032
1276
  url: "/workspaces/{workspaceId}/dbs",
1033
1277
  method: "get",
@@ -1043,6 +1287,7 @@ const deleteDatabase = (variables, signal) => controlPlaneFetch({
1043
1287
  });
1044
1288
  const getDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "get", ...variables, signal });
1045
1289
  const updateDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "patch", ...variables, signal });
1290
+ const renameDatabase = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/rename", method: "post", ...variables, signal });
1046
1291
  const getDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "get", ...variables, signal });
1047
1292
  const updateDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "put", ...variables, signal });
1048
1293
  const deleteDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "delete", ...variables, signal });
@@ -1053,6 +1298,15 @@ const listRegions = (variables, signal) => controlPlaneFetch({
1053
1298
  signal
1054
1299
  });
1055
1300
  const operationsByTag$1 = {
1301
+ oAuth: {
1302
+ getAuthorizationCode,
1303
+ grantAuthorizationCode,
1304
+ getUserOAuthClients,
1305
+ deleteUserOAuthClient,
1306
+ getUserOAuthAccessTokens,
1307
+ deleteOAuthAccessToken,
1308
+ updateOAuthAccessToken
1309
+ },
1056
1310
  users: { getUser, updateUser, deleteUser },
1057
1311
  authentication: { getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
1058
1312
  workspaces: {
@@ -1072,12 +1326,14 @@ const operationsByTag$1 = {
1072
1326
  acceptWorkspaceMemberInvite,
1073
1327
  resendWorkspaceMemberInvite
1074
1328
  },
1329
+ xbcontrolOther: { listClusters, createCluster, getCluster, updateCluster },
1075
1330
  databases: {
1076
1331
  getDatabaseList,
1077
1332
  createDatabase,
1078
1333
  deleteDatabase,
1079
1334
  getDatabaseMetadata,
1080
1335
  updateDatabaseMetadata,
1336
+ renameDatabase,
1081
1337
  getDatabaseGithubSettings,
1082
1338
  updateDatabaseGithubSettings,
1083
1339
  deleteDatabaseGithubSettings,
@@ -1087,66 +1343,11 @@ const operationsByTag$1 = {
1087
1343
 
1088
1344
  const operationsByTag = deepMerge(operationsByTag$2, operationsByTag$1);
1089
1345
 
1090
- function getHostUrl(provider, type) {
1091
- if (isHostProviderAlias(provider)) {
1092
- return providers[provider][type];
1093
- } else if (isHostProviderBuilder(provider)) {
1094
- return provider[type];
1095
- }
1096
- throw new Error("Invalid API provider");
1097
- }
1098
- const providers = {
1099
- production: {
1100
- main: "https://api.xata.io",
1101
- workspaces: "https://{workspaceId}.{region}.xata.sh"
1102
- },
1103
- staging: {
1104
- main: "https://api.staging-xata.dev",
1105
- workspaces: "https://{workspaceId}.{region}.staging-xata.dev"
1106
- },
1107
- dev: {
1108
- main: "https://api.dev-xata.dev",
1109
- workspaces: "https://{workspaceId}.{region}.dev-xata.dev"
1110
- }
1111
- };
1112
- function isHostProviderAlias(alias) {
1113
- return isString(alias) && Object.keys(providers).includes(alias);
1114
- }
1115
- function isHostProviderBuilder(builder) {
1116
- return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
1117
- }
1118
- function parseProviderString(provider = "production") {
1119
- if (isHostProviderAlias(provider)) {
1120
- return provider;
1121
- }
1122
- const [main, workspaces] = provider.split(",");
1123
- if (!main || !workspaces)
1124
- return null;
1125
- return { main, workspaces };
1126
- }
1127
- function buildProviderString(provider) {
1128
- if (isHostProviderAlias(provider))
1129
- return provider;
1130
- return `${provider.main},${provider.workspaces}`;
1131
- }
1132
- function parseWorkspacesUrlParts(url) {
1133
- if (!isString(url))
1134
- return null;
1135
- const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/;
1136
- const regexDev = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.dev-xata\.dev.*/;
1137
- const regexStaging = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.staging-xata\.dev.*/;
1138
- const regexProdTesting = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.tech.*/;
1139
- const match = url.match(regex) || url.match(regexDev) || url.match(regexStaging) || url.match(regexProdTesting);
1140
- if (!match)
1141
- return null;
1142
- return { workspace: match[1], region: match[2] };
1143
- }
1144
-
1145
1346
  var __accessCheck$7 = (obj, member, msg) => {
1146
1347
  if (!member.has(obj))
1147
1348
  throw TypeError("Cannot " + msg);
1148
1349
  };
1149
- var __privateGet$7 = (obj, member, getter) => {
1350
+ var __privateGet$6 = (obj, member, getter) => {
1150
1351
  __accessCheck$7(obj, member, "read from private field");
1151
1352
  return getter ? getter.call(obj) : member.get(obj);
1152
1353
  };
@@ -1155,7 +1356,7 @@ var __privateAdd$7 = (obj, member, value) => {
1155
1356
  throw TypeError("Cannot add the same private member more than once");
1156
1357
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1157
1358
  };
1158
- var __privateSet$7 = (obj, member, value, setter) => {
1359
+ var __privateSet$5 = (obj, member, value, setter) => {
1159
1360
  __accessCheck$7(obj, member, "write to private field");
1160
1361
  setter ? setter.call(obj, value) : member.set(obj, value);
1161
1362
  return value;
@@ -1172,7 +1373,7 @@ class XataApiClient {
1172
1373
  if (!apiKey) {
1173
1374
  throw new Error("Could not resolve a valid apiKey");
1174
1375
  }
1175
- __privateSet$7(this, _extraProps, {
1376
+ __privateSet$5(this, _extraProps, {
1176
1377
  apiUrl: getHostUrl(provider, "main"),
1177
1378
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
1178
1379
  fetch: getFetchImplementation(options.fetch),
@@ -1184,59 +1385,64 @@ class XataApiClient {
1184
1385
  });
1185
1386
  }
1186
1387
  get user() {
1187
- if (!__privateGet$7(this, _namespaces).user)
1188
- __privateGet$7(this, _namespaces).user = new UserApi(__privateGet$7(this, _extraProps));
1189
- return __privateGet$7(this, _namespaces).user;
1388
+ if (!__privateGet$6(this, _namespaces).user)
1389
+ __privateGet$6(this, _namespaces).user = new UserApi(__privateGet$6(this, _extraProps));
1390
+ return __privateGet$6(this, _namespaces).user;
1190
1391
  }
1191
1392
  get authentication() {
1192
- if (!__privateGet$7(this, _namespaces).authentication)
1193
- __privateGet$7(this, _namespaces).authentication = new AuthenticationApi(__privateGet$7(this, _extraProps));
1194
- return __privateGet$7(this, _namespaces).authentication;
1393
+ if (!__privateGet$6(this, _namespaces).authentication)
1394
+ __privateGet$6(this, _namespaces).authentication = new AuthenticationApi(__privateGet$6(this, _extraProps));
1395
+ return __privateGet$6(this, _namespaces).authentication;
1195
1396
  }
1196
1397
  get workspaces() {
1197
- if (!__privateGet$7(this, _namespaces).workspaces)
1198
- __privateGet$7(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$7(this, _extraProps));
1199
- return __privateGet$7(this, _namespaces).workspaces;
1398
+ if (!__privateGet$6(this, _namespaces).workspaces)
1399
+ __privateGet$6(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$6(this, _extraProps));
1400
+ return __privateGet$6(this, _namespaces).workspaces;
1200
1401
  }
1201
1402
  get invites() {
1202
- if (!__privateGet$7(this, _namespaces).invites)
1203
- __privateGet$7(this, _namespaces).invites = new InvitesApi(__privateGet$7(this, _extraProps));
1204
- return __privateGet$7(this, _namespaces).invites;
1403
+ if (!__privateGet$6(this, _namespaces).invites)
1404
+ __privateGet$6(this, _namespaces).invites = new InvitesApi(__privateGet$6(this, _extraProps));
1405
+ return __privateGet$6(this, _namespaces).invites;
1205
1406
  }
1206
1407
  get database() {
1207
- if (!__privateGet$7(this, _namespaces).database)
1208
- __privateGet$7(this, _namespaces).database = new DatabaseApi(__privateGet$7(this, _extraProps));
1209
- return __privateGet$7(this, _namespaces).database;
1408
+ if (!__privateGet$6(this, _namespaces).database)
1409
+ __privateGet$6(this, _namespaces).database = new DatabaseApi(__privateGet$6(this, _extraProps));
1410
+ return __privateGet$6(this, _namespaces).database;
1210
1411
  }
1211
1412
  get branches() {
1212
- if (!__privateGet$7(this, _namespaces).branches)
1213
- __privateGet$7(this, _namespaces).branches = new BranchApi(__privateGet$7(this, _extraProps));
1214
- return __privateGet$7(this, _namespaces).branches;
1413
+ if (!__privateGet$6(this, _namespaces).branches)
1414
+ __privateGet$6(this, _namespaces).branches = new BranchApi(__privateGet$6(this, _extraProps));
1415
+ return __privateGet$6(this, _namespaces).branches;
1215
1416
  }
1216
1417
  get migrations() {
1217
- if (!__privateGet$7(this, _namespaces).migrations)
1218
- __privateGet$7(this, _namespaces).migrations = new MigrationsApi(__privateGet$7(this, _extraProps));
1219
- return __privateGet$7(this, _namespaces).migrations;
1418
+ if (!__privateGet$6(this, _namespaces).migrations)
1419
+ __privateGet$6(this, _namespaces).migrations = new MigrationsApi(__privateGet$6(this, _extraProps));
1420
+ return __privateGet$6(this, _namespaces).migrations;
1220
1421
  }
1221
1422
  get migrationRequests() {
1222
- if (!__privateGet$7(this, _namespaces).migrationRequests)
1223
- __privateGet$7(this, _namespaces).migrationRequests = new MigrationRequestsApi(__privateGet$7(this, _extraProps));
1224
- return __privateGet$7(this, _namespaces).migrationRequests;
1423
+ if (!__privateGet$6(this, _namespaces).migrationRequests)
1424
+ __privateGet$6(this, _namespaces).migrationRequests = new MigrationRequestsApi(__privateGet$6(this, _extraProps));
1425
+ return __privateGet$6(this, _namespaces).migrationRequests;
1225
1426
  }
1226
1427
  get tables() {
1227
- if (!__privateGet$7(this, _namespaces).tables)
1228
- __privateGet$7(this, _namespaces).tables = new TableApi(__privateGet$7(this, _extraProps));
1229
- return __privateGet$7(this, _namespaces).tables;
1428
+ if (!__privateGet$6(this, _namespaces).tables)
1429
+ __privateGet$6(this, _namespaces).tables = new TableApi(__privateGet$6(this, _extraProps));
1430
+ return __privateGet$6(this, _namespaces).tables;
1230
1431
  }
1231
1432
  get records() {
1232
- if (!__privateGet$7(this, _namespaces).records)
1233
- __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
1234
- return __privateGet$7(this, _namespaces).records;
1433
+ if (!__privateGet$6(this, _namespaces).records)
1434
+ __privateGet$6(this, _namespaces).records = new RecordsApi(__privateGet$6(this, _extraProps));
1435
+ return __privateGet$6(this, _namespaces).records;
1436
+ }
1437
+ get files() {
1438
+ if (!__privateGet$6(this, _namespaces).files)
1439
+ __privateGet$6(this, _namespaces).files = new FilesApi(__privateGet$6(this, _extraProps));
1440
+ return __privateGet$6(this, _namespaces).files;
1235
1441
  }
1236
1442
  get searchAndFilter() {
1237
- if (!__privateGet$7(this, _namespaces).searchAndFilter)
1238
- __privateGet$7(this, _namespaces).searchAndFilter = new SearchAndFilterApi(__privateGet$7(this, _extraProps));
1239
- return __privateGet$7(this, _namespaces).searchAndFilter;
1443
+ if (!__privateGet$6(this, _namespaces).searchAndFilter)
1444
+ __privateGet$6(this, _namespaces).searchAndFilter = new SearchAndFilterApi(__privateGet$6(this, _extraProps));
1445
+ return __privateGet$6(this, _namespaces).searchAndFilter;
1240
1446
  }
1241
1447
  }
1242
1448
  _extraProps = new WeakMap();
@@ -1538,6 +1744,30 @@ class BranchApi {
1538
1744
  ...this.extraProps
1539
1745
  });
1540
1746
  }
1747
+ pgRollMigrationHistory({
1748
+ workspace,
1749
+ region,
1750
+ database,
1751
+ branch
1752
+ }) {
1753
+ return operationsByTag.branch.pgRollMigrationHistory({
1754
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1755
+ ...this.extraProps
1756
+ });
1757
+ }
1758
+ applyMigration({
1759
+ workspace,
1760
+ region,
1761
+ database,
1762
+ branch,
1763
+ migration
1764
+ }) {
1765
+ return operationsByTag.branch.applyMigration({
1766
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1767
+ body: migration,
1768
+ ...this.extraProps
1769
+ });
1770
+ }
1541
1771
  }
1542
1772
  class TableApi {
1543
1773
  constructor(extraProps) {
@@ -1803,9 +2033,167 @@ class RecordsApi {
1803
2033
  branch,
1804
2034
  operations
1805
2035
  }) {
1806
- return operationsByTag.records.branchTransaction({
1807
- pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1808
- body: { operations },
2036
+ return operationsByTag.records.branchTransaction({
2037
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2038
+ body: { operations },
2039
+ ...this.extraProps
2040
+ });
2041
+ }
2042
+ }
2043
+ class FilesApi {
2044
+ constructor(extraProps) {
2045
+ this.extraProps = extraProps;
2046
+ }
2047
+ getFileItem({
2048
+ workspace,
2049
+ region,
2050
+ database,
2051
+ branch,
2052
+ table,
2053
+ record,
2054
+ column,
2055
+ fileId
2056
+ }) {
2057
+ return operationsByTag.files.getFileItem({
2058
+ pathParams: {
2059
+ workspace,
2060
+ region,
2061
+ dbBranchName: `${database}:${branch}`,
2062
+ tableName: table,
2063
+ recordId: record,
2064
+ columnName: column,
2065
+ fileId
2066
+ },
2067
+ ...this.extraProps
2068
+ });
2069
+ }
2070
+ putFileItem({
2071
+ workspace,
2072
+ region,
2073
+ database,
2074
+ branch,
2075
+ table,
2076
+ record,
2077
+ column,
2078
+ fileId,
2079
+ file
2080
+ }) {
2081
+ return operationsByTag.files.putFileItem({
2082
+ pathParams: {
2083
+ workspace,
2084
+ region,
2085
+ dbBranchName: `${database}:${branch}`,
2086
+ tableName: table,
2087
+ recordId: record,
2088
+ columnName: column,
2089
+ fileId
2090
+ },
2091
+ // @ts-ignore
2092
+ body: file,
2093
+ ...this.extraProps
2094
+ });
2095
+ }
2096
+ deleteFileItem({
2097
+ workspace,
2098
+ region,
2099
+ database,
2100
+ branch,
2101
+ table,
2102
+ record,
2103
+ column,
2104
+ fileId
2105
+ }) {
2106
+ return operationsByTag.files.deleteFileItem({
2107
+ pathParams: {
2108
+ workspace,
2109
+ region,
2110
+ dbBranchName: `${database}:${branch}`,
2111
+ tableName: table,
2112
+ recordId: record,
2113
+ columnName: column,
2114
+ fileId
2115
+ },
2116
+ ...this.extraProps
2117
+ });
2118
+ }
2119
+ getFile({
2120
+ workspace,
2121
+ region,
2122
+ database,
2123
+ branch,
2124
+ table,
2125
+ record,
2126
+ column
2127
+ }) {
2128
+ return operationsByTag.files.getFile({
2129
+ pathParams: {
2130
+ workspace,
2131
+ region,
2132
+ dbBranchName: `${database}:${branch}`,
2133
+ tableName: table,
2134
+ recordId: record,
2135
+ columnName: column
2136
+ },
2137
+ ...this.extraProps
2138
+ });
2139
+ }
2140
+ putFile({
2141
+ workspace,
2142
+ region,
2143
+ database,
2144
+ branch,
2145
+ table,
2146
+ record,
2147
+ column,
2148
+ file
2149
+ }) {
2150
+ return operationsByTag.files.putFile({
2151
+ pathParams: {
2152
+ workspace,
2153
+ region,
2154
+ dbBranchName: `${database}:${branch}`,
2155
+ tableName: table,
2156
+ recordId: record,
2157
+ columnName: column
2158
+ },
2159
+ body: file,
2160
+ ...this.extraProps
2161
+ });
2162
+ }
2163
+ deleteFile({
2164
+ workspace,
2165
+ region,
2166
+ database,
2167
+ branch,
2168
+ table,
2169
+ record,
2170
+ column
2171
+ }) {
2172
+ return operationsByTag.files.deleteFile({
2173
+ pathParams: {
2174
+ workspace,
2175
+ region,
2176
+ dbBranchName: `${database}:${branch}`,
2177
+ tableName: table,
2178
+ recordId: record,
2179
+ columnName: column
2180
+ },
2181
+ ...this.extraProps
2182
+ });
2183
+ }
2184
+ fileAccess({
2185
+ workspace,
2186
+ region,
2187
+ fileId,
2188
+ verify
2189
+ }) {
2190
+ return operationsByTag.files.fileAccess({
2191
+ pathParams: {
2192
+ workspace,
2193
+ region,
2194
+ fileId
2195
+ },
2196
+ queryParams: { verify },
1809
2197
  ...this.extraProps
1810
2198
  });
1811
2199
  }
@@ -1901,6 +2289,21 @@ class SearchAndFilterApi {
1901
2289
  ...this.extraProps
1902
2290
  });
1903
2291
  }
2292
+ askTableSession({
2293
+ workspace,
2294
+ region,
2295
+ database,
2296
+ branch,
2297
+ table,
2298
+ sessionId,
2299
+ message
2300
+ }) {
2301
+ return operationsByTag.searchAndFilter.askTableSession({
2302
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, sessionId },
2303
+ body: { message },
2304
+ ...this.extraProps
2305
+ });
2306
+ }
1904
2307
  summarizeTable({
1905
2308
  workspace,
1906
2309
  region,
@@ -2178,6 +2581,17 @@ class MigrationsApi {
2178
2581
  ...this.extraProps
2179
2582
  });
2180
2583
  }
2584
+ getSchema({
2585
+ workspace,
2586
+ region,
2587
+ database,
2588
+ branch
2589
+ }) {
2590
+ return operationsByTag.migrations.getSchema({
2591
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2592
+ ...this.extraProps
2593
+ });
2594
+ }
2181
2595
  }
2182
2596
  class DatabaseApi {
2183
2597
  constructor(extraProps) {
@@ -2192,11 +2606,13 @@ class DatabaseApi {
2192
2606
  createDatabase({
2193
2607
  workspace,
2194
2608
  database,
2195
- data
2609
+ data,
2610
+ headers
2196
2611
  }) {
2197
2612
  return operationsByTag.databases.createDatabase({
2198
2613
  pathParams: { workspaceId: workspace, dbName: database },
2199
2614
  body: data,
2615
+ headers,
2200
2616
  ...this.extraProps
2201
2617
  });
2202
2618
  }
@@ -2229,6 +2645,17 @@ class DatabaseApi {
2229
2645
  ...this.extraProps
2230
2646
  });
2231
2647
  }
2648
+ renameDatabase({
2649
+ workspace,
2650
+ database,
2651
+ newName
2652
+ }) {
2653
+ return operationsByTag.databases.renameDatabase({
2654
+ pathParams: { workspaceId: workspace, dbName: database },
2655
+ body: { newName },
2656
+ ...this.extraProps
2657
+ });
2658
+ }
2232
2659
  getDatabaseGithubSettings({
2233
2660
  workspace,
2234
2661
  database
@@ -2275,18 +2702,202 @@ class XataApiPlugin {
2275
2702
  class XataPlugin {
2276
2703
  }
2277
2704
 
2705
+ function buildTransformString(transformations) {
2706
+ return transformations.flatMap(
2707
+ (t) => Object.entries(t).map(([key, value]) => {
2708
+ if (key === "trim") {
2709
+ const { left = 0, top = 0, right = 0, bottom = 0 } = value;
2710
+ return `${key}=${[top, right, bottom, left].join(";")}`;
2711
+ }
2712
+ if (key === "gravity" && typeof value === "object") {
2713
+ const { x = 0.5, y = 0.5 } = value;
2714
+ return `${key}=${[x, y].join("x")}`;
2715
+ }
2716
+ return `${key}=${value}`;
2717
+ })
2718
+ ).join(",");
2719
+ }
2720
+ function transformImage(url, ...transformations) {
2721
+ if (!isDefined(url))
2722
+ return void 0;
2723
+ const newTransformations = buildTransformString(transformations);
2724
+ const { hostname, pathname, search } = new URL(url);
2725
+ const pathParts = pathname.split("/");
2726
+ const transformIndex = pathParts.findIndex((part) => part === "transform");
2727
+ const removedItems = transformIndex >= 0 ? pathParts.splice(transformIndex, 2) : [];
2728
+ const transform = `/transform/${[removedItems[1], newTransformations].filter(isDefined).join(",")}`;
2729
+ const path = pathParts.join("/");
2730
+ return `https://${hostname}${transform}${path}${search}`;
2731
+ }
2732
+
2733
+ class XataFile {
2734
+ constructor(file) {
2735
+ this.id = file.id;
2736
+ this.name = file.name;
2737
+ this.mediaType = file.mediaType;
2738
+ this.base64Content = file.base64Content;
2739
+ this.enablePublicUrl = file.enablePublicUrl;
2740
+ this.signedUrlTimeout = file.signedUrlTimeout;
2741
+ this.uploadUrlTimeout = file.uploadUrlTimeout;
2742
+ this.size = file.size;
2743
+ this.version = file.version;
2744
+ this.url = file.url;
2745
+ this.signedUrl = file.signedUrl;
2746
+ this.uploadUrl = file.uploadUrl;
2747
+ this.attributes = file.attributes;
2748
+ }
2749
+ static fromBuffer(buffer, options = {}) {
2750
+ const base64Content = buffer.toString("base64");
2751
+ return new XataFile({ ...options, base64Content });
2752
+ }
2753
+ toBuffer() {
2754
+ if (!this.base64Content) {
2755
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2756
+ }
2757
+ return Buffer.from(this.base64Content, "base64");
2758
+ }
2759
+ static fromArrayBuffer(arrayBuffer, options = {}) {
2760
+ const uint8Array = new Uint8Array(arrayBuffer);
2761
+ return this.fromUint8Array(uint8Array, options);
2762
+ }
2763
+ toArrayBuffer() {
2764
+ if (!this.base64Content) {
2765
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2766
+ }
2767
+ const binary = atob(this.base64Content);
2768
+ return new ArrayBuffer(binary.length);
2769
+ }
2770
+ static fromUint8Array(uint8Array, options = {}) {
2771
+ let binary = "";
2772
+ for (let i = 0; i < uint8Array.byteLength; i++) {
2773
+ binary += String.fromCharCode(uint8Array[i]);
2774
+ }
2775
+ const base64Content = btoa(binary);
2776
+ return new XataFile({ ...options, base64Content });
2777
+ }
2778
+ toUint8Array() {
2779
+ if (!this.base64Content) {
2780
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2781
+ }
2782
+ const binary = atob(this.base64Content);
2783
+ const uint8Array = new Uint8Array(binary.length);
2784
+ for (let i = 0; i < binary.length; i++) {
2785
+ uint8Array[i] = binary.charCodeAt(i);
2786
+ }
2787
+ return uint8Array;
2788
+ }
2789
+ static async fromBlob(file, options = {}) {
2790
+ const name = options.name ?? file.name;
2791
+ const mediaType = file.type;
2792
+ const arrayBuffer = await file.arrayBuffer();
2793
+ return this.fromArrayBuffer(arrayBuffer, { ...options, name, mediaType });
2794
+ }
2795
+ toBlob() {
2796
+ if (!this.base64Content) {
2797
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2798
+ }
2799
+ const binary = atob(this.base64Content);
2800
+ const uint8Array = new Uint8Array(binary.length);
2801
+ for (let i = 0; i < binary.length; i++) {
2802
+ uint8Array[i] = binary.charCodeAt(i);
2803
+ }
2804
+ return new Blob([uint8Array], { type: this.mediaType });
2805
+ }
2806
+ static fromString(string, options = {}) {
2807
+ const base64Content = btoa(string);
2808
+ return new XataFile({ ...options, base64Content });
2809
+ }
2810
+ toString() {
2811
+ if (!this.base64Content) {
2812
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2813
+ }
2814
+ return atob(this.base64Content);
2815
+ }
2816
+ static fromBase64(base64Content, options = {}) {
2817
+ return new XataFile({ ...options, base64Content });
2818
+ }
2819
+ toBase64() {
2820
+ if (!this.base64Content) {
2821
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2822
+ }
2823
+ return this.base64Content;
2824
+ }
2825
+ transform(...options) {
2826
+ return {
2827
+ url: transformImage(this.url, ...options),
2828
+ signedUrl: transformImage(this.signedUrl, ...options),
2829
+ metadataUrl: transformImage(this.url, ...options, { format: "json" }),
2830
+ metadataSignedUrl: transformImage(this.signedUrl, ...options, { format: "json" })
2831
+ };
2832
+ }
2833
+ }
2834
+ const parseInputFileEntry = async (entry) => {
2835
+ if (!isDefined(entry))
2836
+ return null;
2837
+ const { id, name, mediaType, base64Content, enablePublicUrl, signedUrlTimeout, uploadUrlTimeout } = await entry;
2838
+ return compactObject({
2839
+ id,
2840
+ // Name cannot be an empty string in our API
2841
+ name: name ? name : void 0,
2842
+ mediaType,
2843
+ base64Content,
2844
+ enablePublicUrl,
2845
+ signedUrlTimeout,
2846
+ uploadUrlTimeout
2847
+ });
2848
+ };
2849
+
2278
2850
  function cleanFilter(filter) {
2279
- if (!filter)
2851
+ if (!isDefined(filter))
2280
2852
  return void 0;
2281
- const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
2282
- return values.length > 0 ? filter : void 0;
2853
+ if (!isObject(filter))
2854
+ return filter;
2855
+ const values = Object.fromEntries(
2856
+ Object.entries(filter).reduce((acc, [key, value]) => {
2857
+ if (!isDefined(value))
2858
+ return acc;
2859
+ if (Array.isArray(value)) {
2860
+ const clean = value.map((item) => cleanFilter(item)).filter((item) => isDefined(item));
2861
+ if (clean.length === 0)
2862
+ return acc;
2863
+ return [...acc, [key, clean]];
2864
+ }
2865
+ if (isObject(value)) {
2866
+ const clean = cleanFilter(value);
2867
+ if (!isDefined(clean))
2868
+ return acc;
2869
+ return [...acc, [key, clean]];
2870
+ }
2871
+ return [...acc, [key, value]];
2872
+ }, [])
2873
+ );
2874
+ return Object.keys(values).length > 0 ? values : void 0;
2875
+ }
2876
+
2877
+ function stringifyJson(value) {
2878
+ if (!isDefined(value))
2879
+ return value;
2880
+ if (isString(value))
2881
+ return value;
2882
+ try {
2883
+ return JSON.stringify(value);
2884
+ } catch (e) {
2885
+ return value;
2886
+ }
2887
+ }
2888
+ function parseJson(value) {
2889
+ try {
2890
+ return JSON.parse(value);
2891
+ } catch (e) {
2892
+ return value;
2893
+ }
2283
2894
  }
2284
2895
 
2285
2896
  var __accessCheck$6 = (obj, member, msg) => {
2286
2897
  if (!member.has(obj))
2287
2898
  throw TypeError("Cannot " + msg);
2288
2899
  };
2289
- var __privateGet$6 = (obj, member, getter) => {
2900
+ var __privateGet$5 = (obj, member, getter) => {
2290
2901
  __accessCheck$6(obj, member, "read from private field");
2291
2902
  return getter ? getter.call(obj) : member.get(obj);
2292
2903
  };
@@ -2295,7 +2906,7 @@ var __privateAdd$6 = (obj, member, value) => {
2295
2906
  throw TypeError("Cannot add the same private member more than once");
2296
2907
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
2297
2908
  };
2298
- var __privateSet$6 = (obj, member, value, setter) => {
2909
+ var __privateSet$4 = (obj, member, value, setter) => {
2299
2910
  __accessCheck$6(obj, member, "write to private field");
2300
2911
  setter ? setter.call(obj, value) : member.set(obj, value);
2301
2912
  return value;
@@ -2304,39 +2915,67 @@ var _query, _page;
2304
2915
  class Page {
2305
2916
  constructor(query, meta, records = []) {
2306
2917
  __privateAdd$6(this, _query, void 0);
2307
- __privateSet$6(this, _query, query);
2918
+ __privateSet$4(this, _query, query);
2308
2919
  this.meta = meta;
2309
2920
  this.records = new RecordArray(this, records);
2310
2921
  }
2922
+ /**
2923
+ * Retrieves the next page of results.
2924
+ * @param size Maximum number of results to be retrieved.
2925
+ * @param offset Number of results to skip when retrieving the results.
2926
+ * @returns The next page or results.
2927
+ */
2311
2928
  async nextPage(size, offset) {
2312
- return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
2313
- }
2929
+ return __privateGet$5(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
2930
+ }
2931
+ /**
2932
+ * Retrieves the previous page of results.
2933
+ * @param size Maximum number of results to be retrieved.
2934
+ * @param offset Number of results to skip when retrieving the results.
2935
+ * @returns The previous page or results.
2936
+ */
2314
2937
  async previousPage(size, offset) {
2315
- return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
2316
- }
2938
+ return __privateGet$5(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
2939
+ }
2940
+ /**
2941
+ * Retrieves the start page of results.
2942
+ * @param size Maximum number of results to be retrieved.
2943
+ * @param offset Number of results to skip when retrieving the results.
2944
+ * @returns The start page or results.
2945
+ */
2317
2946
  async startPage(size, offset) {
2318
- return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, start: this.meta.page.cursor } });
2319
- }
2947
+ return __privateGet$5(this, _query).getPaginated({ pagination: { size, offset, start: this.meta.page.cursor } });
2948
+ }
2949
+ /**
2950
+ * Retrieves the end page of results.
2951
+ * @param size Maximum number of results to be retrieved.
2952
+ * @param offset Number of results to skip when retrieving the results.
2953
+ * @returns The end page or results.
2954
+ */
2320
2955
  async endPage(size, offset) {
2321
- return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, end: this.meta.page.cursor } });
2956
+ return __privateGet$5(this, _query).getPaginated({ pagination: { size, offset, end: this.meta.page.cursor } });
2322
2957
  }
2958
+ /**
2959
+ * Shortcut method to check if there will be additional results if the next page of results is retrieved.
2960
+ * @returns Whether or not there will be additional results in the next page of results.
2961
+ */
2323
2962
  hasNextPage() {
2324
2963
  return this.meta.page.more;
2325
2964
  }
2326
2965
  }
2327
2966
  _query = new WeakMap();
2328
- const PAGINATION_MAX_SIZE = 200;
2967
+ const PAGINATION_MAX_SIZE = 1e3;
2329
2968
  const PAGINATION_DEFAULT_SIZE = 20;
2330
- const PAGINATION_MAX_OFFSET = 800;
2969
+ const PAGINATION_MAX_OFFSET = 49e3;
2331
2970
  const PAGINATION_DEFAULT_OFFSET = 0;
2332
2971
  function isCursorPaginationOptions(options) {
2333
2972
  return isDefined(options) && (isDefined(options.start) || isDefined(options.end) || isDefined(options.after) || isDefined(options.before));
2334
2973
  }
2335
- const _RecordArray = class extends Array {
2974
+ const _RecordArray = class _RecordArray extends Array {
2336
2975
  constructor(...args) {
2337
2976
  super(..._RecordArray.parseConstructorParams(...args));
2338
2977
  __privateAdd$6(this, _page, void 0);
2339
- __privateSet$6(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
2978
+ __privateSet$4(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
2340
2979
  }
2341
2980
  static parseConstructorParams(...args) {
2342
2981
  if (args.length === 1 && typeof args[0] === "number") {
@@ -2360,34 +2999,57 @@ const _RecordArray = class extends Array {
2360
2999
  map(callbackfn, thisArg) {
2361
3000
  return this.toArray().map(callbackfn, thisArg);
2362
3001
  }
3002
+ /**
3003
+ * Retrieve next page of records
3004
+ *
3005
+ * @returns A new array of objects
3006
+ */
2363
3007
  async nextPage(size, offset) {
2364
- const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
3008
+ const newPage = await __privateGet$5(this, _page).nextPage(size, offset);
2365
3009
  return new _RecordArray(newPage);
2366
3010
  }
3011
+ /**
3012
+ * Retrieve previous page of records
3013
+ *
3014
+ * @returns A new array of objects
3015
+ */
2367
3016
  async previousPage(size, offset) {
2368
- const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
3017
+ const newPage = await __privateGet$5(this, _page).previousPage(size, offset);
2369
3018
  return new _RecordArray(newPage);
2370
3019
  }
3020
+ /**
3021
+ * Retrieve start page of records
3022
+ *
3023
+ * @returns A new array of objects
3024
+ */
2371
3025
  async startPage(size, offset) {
2372
- const newPage = await __privateGet$6(this, _page).startPage(size, offset);
3026
+ const newPage = await __privateGet$5(this, _page).startPage(size, offset);
2373
3027
  return new _RecordArray(newPage);
2374
3028
  }
3029
+ /**
3030
+ * Retrieve end page of records
3031
+ *
3032
+ * @returns A new array of objects
3033
+ */
2375
3034
  async endPage(size, offset) {
2376
- const newPage = await __privateGet$6(this, _page).endPage(size, offset);
3035
+ const newPage = await __privateGet$5(this, _page).endPage(size, offset);
2377
3036
  return new _RecordArray(newPage);
2378
3037
  }
3038
+ /**
3039
+ * @returns Boolean indicating if there is a next page
3040
+ */
2379
3041
  hasNextPage() {
2380
- return __privateGet$6(this, _page).meta.page.more;
3042
+ return __privateGet$5(this, _page).meta.page.more;
2381
3043
  }
2382
3044
  };
2383
- let RecordArray = _RecordArray;
2384
3045
  _page = new WeakMap();
3046
+ let RecordArray = _RecordArray;
2385
3047
 
2386
3048
  var __accessCheck$5 = (obj, member, msg) => {
2387
3049
  if (!member.has(obj))
2388
3050
  throw TypeError("Cannot " + msg);
2389
3051
  };
2390
- var __privateGet$5 = (obj, member, getter) => {
3052
+ var __privateGet$4 = (obj, member, getter) => {
2391
3053
  __accessCheck$5(obj, member, "read from private field");
2392
3054
  return getter ? getter.call(obj) : member.get(obj);
2393
3055
  };
@@ -2396,7 +3058,7 @@ var __privateAdd$5 = (obj, member, value) => {
2396
3058
  throw TypeError("Cannot add the same private member more than once");
2397
3059
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
2398
3060
  };
2399
- var __privateSet$5 = (obj, member, value, setter) => {
3061
+ var __privateSet$3 = (obj, member, value, setter) => {
2400
3062
  __accessCheck$5(obj, member, "write to private field");
2401
3063
  setter ? setter.call(obj, value) : member.set(obj, value);
2402
3064
  return value;
@@ -2406,32 +3068,33 @@ var __privateMethod$3 = (obj, member, method) => {
2406
3068
  return method;
2407
3069
  };
2408
3070
  var _table$1, _repository, _data, _cleanFilterConstraint, cleanFilterConstraint_fn;
2409
- const _Query = class {
3071
+ const _Query = class _Query {
2410
3072
  constructor(repository, table, data, rawParent) {
2411
3073
  __privateAdd$5(this, _cleanFilterConstraint);
2412
3074
  __privateAdd$5(this, _table$1, void 0);
2413
3075
  __privateAdd$5(this, _repository, void 0);
2414
3076
  __privateAdd$5(this, _data, { filter: {} });
2415
- this.meta = { page: { cursor: "start", more: true } };
3077
+ // Implements pagination
3078
+ this.meta = { page: { cursor: "start", more: true, size: PAGINATION_DEFAULT_SIZE } };
2416
3079
  this.records = new RecordArray(this, []);
2417
- __privateSet$5(this, _table$1, table);
3080
+ __privateSet$3(this, _table$1, table);
2418
3081
  if (repository) {
2419
- __privateSet$5(this, _repository, repository);
3082
+ __privateSet$3(this, _repository, repository);
2420
3083
  } else {
2421
- __privateSet$5(this, _repository, this);
3084
+ __privateSet$3(this, _repository, this);
2422
3085
  }
2423
3086
  const parent = cleanParent(data, rawParent);
2424
- __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
2425
- __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
2426
- __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
2427
- __privateGet$5(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
2428
- __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
2429
- __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
2430
- __privateGet$5(this, _data).columns = data.columns ?? parent?.columns;
2431
- __privateGet$5(this, _data).consistency = data.consistency ?? parent?.consistency;
2432
- __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
2433
- __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
2434
- __privateGet$5(this, _data).fetchOptions = data.fetchOptions ?? parent?.fetchOptions;
3087
+ __privateGet$4(this, _data).filter = data.filter ?? parent?.filter ?? {};
3088
+ __privateGet$4(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
3089
+ __privateGet$4(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
3090
+ __privateGet$4(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
3091
+ __privateGet$4(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
3092
+ __privateGet$4(this, _data).sort = data.sort ?? parent?.sort;
3093
+ __privateGet$4(this, _data).columns = data.columns ?? parent?.columns;
3094
+ __privateGet$4(this, _data).consistency = data.consistency ?? parent?.consistency;
3095
+ __privateGet$4(this, _data).pagination = data.pagination ?? parent?.pagination;
3096
+ __privateGet$4(this, _data).cache = data.cache ?? parent?.cache;
3097
+ __privateGet$4(this, _data).fetchOptions = data.fetchOptions ?? parent?.fetchOptions;
2435
3098
  this.any = this.any.bind(this);
2436
3099
  this.all = this.all.bind(this);
2437
3100
  this.not = this.not.bind(this);
@@ -2442,59 +3105,90 @@ const _Query = class {
2442
3105
  Object.defineProperty(this, "repository", { enumerable: false });
2443
3106
  }
2444
3107
  getQueryOptions() {
2445
- return __privateGet$5(this, _data);
3108
+ return __privateGet$4(this, _data);
2446
3109
  }
2447
3110
  key() {
2448
- const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$5(this, _data);
3111
+ const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$4(this, _data);
2449
3112
  const key = JSON.stringify({ columns, filter, sort, pagination });
2450
3113
  return toBase64(key);
2451
3114
  }
3115
+ /**
3116
+ * Builds a new query object representing a logical OR between the given subqueries.
3117
+ * @param queries An array of subqueries.
3118
+ * @returns A new Query object.
3119
+ */
2452
3120
  any(...queries) {
2453
3121
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
2454
- return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
3122
+ return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $any } }, __privateGet$4(this, _data));
2455
3123
  }
3124
+ /**
3125
+ * Builds a new query object representing a logical AND between the given subqueries.
3126
+ * @param queries An array of subqueries.
3127
+ * @returns A new Query object.
3128
+ */
2456
3129
  all(...queries) {
2457
3130
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
2458
- return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
3131
+ return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
2459
3132
  }
3133
+ /**
3134
+ * Builds a new query object representing a logical OR negating each subquery. In pseudo-code: !q1 OR !q2
3135
+ * @param queries An array of subqueries.
3136
+ * @returns A new Query object.
3137
+ */
2460
3138
  not(...queries) {
2461
3139
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
2462
- return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
3140
+ return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $not } }, __privateGet$4(this, _data));
2463
3141
  }
3142
+ /**
3143
+ * Builds a new query object representing a logical AND negating each subquery. In pseudo-code: !q1 AND !q2
3144
+ * @param queries An array of subqueries.
3145
+ * @returns A new Query object.
3146
+ */
2464
3147
  none(...queries) {
2465
3148
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
2466
- return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
3149
+ return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $none } }, __privateGet$4(this, _data));
2467
3150
  }
2468
3151
  filter(a, b) {
2469
3152
  if (arguments.length === 1) {
2470
3153
  const constraints = Object.entries(a ?? {}).map(([column, constraint]) => ({
2471
3154
  [column]: __privateMethod$3(this, _cleanFilterConstraint, cleanFilterConstraint_fn).call(this, column, constraint)
2472
3155
  }));
2473
- const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
2474
- return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
3156
+ const $all = compact([__privateGet$4(this, _data).filter?.$all].flat().concat(constraints));
3157
+ return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
2475
3158
  } else {
2476
3159
  const constraints = isDefined(a) && isDefined(b) ? [{ [a]: __privateMethod$3(this, _cleanFilterConstraint, cleanFilterConstraint_fn).call(this, a, b) }] : void 0;
2477
- const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
2478
- return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
3160
+ const $all = compact([__privateGet$4(this, _data).filter?.$all].flat().concat(constraints));
3161
+ return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
2479
3162
  }
2480
3163
  }
2481
3164
  sort(column, direction = "asc") {
2482
- const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
3165
+ const originalSort = [__privateGet$4(this, _data).sort ?? []].flat();
2483
3166
  const sort = [...originalSort, { column, direction }];
2484
- return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
3167
+ return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { sort }, __privateGet$4(this, _data));
2485
3168
  }
3169
+ /**
3170
+ * Builds a new query specifying the set of columns to be returned in the query response.
3171
+ * @param columns Array of column names to be returned by the query.
3172
+ * @returns A new Query object.
3173
+ */
2486
3174
  select(columns) {
2487
3175
  return new _Query(
2488
- __privateGet$5(this, _repository),
2489
- __privateGet$5(this, _table$1),
3176
+ __privateGet$4(this, _repository),
3177
+ __privateGet$4(this, _table$1),
2490
3178
  { columns },
2491
- __privateGet$5(this, _data)
3179
+ __privateGet$4(this, _data)
2492
3180
  );
2493
3181
  }
2494
3182
  getPaginated(options = {}) {
2495
- const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
2496
- return __privateGet$5(this, _repository).query(query);
2497
- }
3183
+ const query = new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), options, __privateGet$4(this, _data));
3184
+ return __privateGet$4(this, _repository).query(query);
3185
+ }
3186
+ /**
3187
+ * Get results in an iterator
3188
+ *
3189
+ * @async
3190
+ * @returns Async interable of results
3191
+ */
2498
3192
  async *[Symbol.asyncIterator]() {
2499
3193
  for await (const [record] of this.getIterator({ batchSize: 1 })) {
2500
3194
  yield record;
@@ -2548,39 +3242,66 @@ const _Query = class {
2548
3242
  async summarize(params = {}) {
2549
3243
  const { summaries, summariesFilter, ...options } = params;
2550
3244
  const query = new _Query(
2551
- __privateGet$5(this, _repository),
2552
- __privateGet$5(this, _table$1),
3245
+ __privateGet$4(this, _repository),
3246
+ __privateGet$4(this, _table$1),
2553
3247
  options,
2554
- __privateGet$5(this, _data)
3248
+ __privateGet$4(this, _data)
2555
3249
  );
2556
- return __privateGet$5(this, _repository).summarizeTable(query, summaries, summariesFilter);
3250
+ return __privateGet$4(this, _repository).summarizeTable(query, summaries, summariesFilter);
2557
3251
  }
3252
+ /**
3253
+ * Builds a new query object adding a cache TTL in milliseconds.
3254
+ * @param ttl The cache TTL in milliseconds.
3255
+ * @returns A new Query object.
3256
+ */
2558
3257
  cache(ttl) {
2559
- return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
3258
+ return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { cache: ttl }, __privateGet$4(this, _data));
2560
3259
  }
3260
+ /**
3261
+ * Retrieve next page of records
3262
+ *
3263
+ * @returns A new page object.
3264
+ */
2561
3265
  nextPage(size, offset) {
2562
3266
  return this.startPage(size, offset);
2563
3267
  }
3268
+ /**
3269
+ * Retrieve previous page of records
3270
+ *
3271
+ * @returns A new page object
3272
+ */
2564
3273
  previousPage(size, offset) {
2565
3274
  return this.startPage(size, offset);
2566
3275
  }
3276
+ /**
3277
+ * Retrieve start page of records
3278
+ *
3279
+ * @returns A new page object
3280
+ */
2567
3281
  startPage(size, offset) {
2568
3282
  return this.getPaginated({ pagination: { size, offset } });
2569
3283
  }
3284
+ /**
3285
+ * Retrieve last page of records
3286
+ *
3287
+ * @returns A new page object
3288
+ */
2570
3289
  endPage(size, offset) {
2571
3290
  return this.getPaginated({ pagination: { size, offset, before: "end" } });
2572
3291
  }
3292
+ /**
3293
+ * @returns Boolean indicating if there is a next page
3294
+ */
2573
3295
  hasNextPage() {
2574
3296
  return this.meta.page.more;
2575
3297
  }
2576
3298
  };
2577
- let Query = _Query;
2578
3299
  _table$1 = new WeakMap();
2579
3300
  _repository = new WeakMap();
2580
3301
  _data = new WeakMap();
2581
3302
  _cleanFilterConstraint = new WeakSet();
2582
3303
  cleanFilterConstraint_fn = function(column, value) {
2583
- const columnType = __privateGet$5(this, _table$1).schema?.columns.find(({ name }) => name === column)?.type;
3304
+ const columnType = __privateGet$4(this, _table$1).schema?.columns.find(({ name }) => name === column)?.type;
2584
3305
  if (columnType === "multiple" && (isString(value) || isStringArray(value))) {
2585
3306
  return { $includes: value };
2586
3307
  }
@@ -2589,6 +3310,7 @@ cleanFilterConstraint_fn = function(column, value) {
2589
3310
  }
2590
3311
  return value;
2591
3312
  };
3313
+ let Query = _Query;
2592
3314
  function cleanParent(data, parent) {
2593
3315
  if (isCursorPaginationOptions(data.pagination)) {
2594
3316
  return { ...parent, sort: void 0, filter: void 0 };
@@ -2596,6 +3318,21 @@ function cleanParent(data, parent) {
2596
3318
  return parent;
2597
3319
  }
2598
3320
 
3321
+ const RecordColumnTypes = [
3322
+ "bool",
3323
+ "int",
3324
+ "float",
3325
+ "string",
3326
+ "text",
3327
+ "email",
3328
+ "multiple",
3329
+ "link",
3330
+ "datetime",
3331
+ "vector",
3332
+ "file[]",
3333
+ "file",
3334
+ "json"
3335
+ ];
2599
3336
  function isIdentifiable(x) {
2600
3337
  return isObject(x) && isString(x?.id);
2601
3338
  }
@@ -2605,6 +3342,24 @@ function isXataRecord(x) {
2605
3342
  return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
2606
3343
  }
2607
3344
 
3345
+ function isValidExpandedColumn(column) {
3346
+ return isObject(column) && isString(column.name);
3347
+ }
3348
+ function isValidSelectableColumns(columns) {
3349
+ if (!Array.isArray(columns)) {
3350
+ return false;
3351
+ }
3352
+ return columns.every((column) => {
3353
+ if (typeof column === "string") {
3354
+ return true;
3355
+ }
3356
+ if (typeof column === "object") {
3357
+ return isValidExpandedColumn(column);
3358
+ }
3359
+ return false;
3360
+ });
3361
+ }
3362
+
2608
3363
  function isSortFilterString(value) {
2609
3364
  return isString(value);
2610
3365
  }
@@ -2636,7 +3391,7 @@ var __accessCheck$4 = (obj, member, msg) => {
2636
3391
  if (!member.has(obj))
2637
3392
  throw TypeError("Cannot " + msg);
2638
3393
  };
2639
- var __privateGet$4 = (obj, member, getter) => {
3394
+ var __privateGet$3 = (obj, member, getter) => {
2640
3395
  __accessCheck$4(obj, member, "read from private field");
2641
3396
  return getter ? getter.call(obj) : member.get(obj);
2642
3397
  };
@@ -2645,7 +3400,7 @@ var __privateAdd$4 = (obj, member, value) => {
2645
3400
  throw TypeError("Cannot add the same private member more than once");
2646
3401
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
2647
3402
  };
2648
- var __privateSet$4 = (obj, member, value, setter) => {
3403
+ var __privateSet$2 = (obj, member, value, setter) => {
2649
3404
  __accessCheck$4(obj, member, "write to private field");
2650
3405
  setter ? setter.call(obj, value) : member.set(obj, value);
2651
3406
  return value;
@@ -2654,7 +3409,7 @@ var __privateMethod$2 = (obj, member, method) => {
2654
3409
  __accessCheck$4(obj, member, "access private method");
2655
3410
  return method;
2656
3411
  };
2657
- 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;
3412
+ var _table, _getFetchProps, _db, _cache, _schemaTables, _trace, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _insertRecords, insertRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _updateRecords, updateRecords_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _deleteRecords, deleteRecords_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaTables, getSchemaTables_fn, _transformObjectToApi, transformObjectToApi_fn;
2658
3413
  const BULK_OPERATION_MAX_SIZE = 1e3;
2659
3414
  class Repository extends Query {
2660
3415
  }
@@ -2675,61 +3430,62 @@ class RestRepository extends Query {
2675
3430
  __privateAdd$4(this, _deleteRecords);
2676
3431
  __privateAdd$4(this, _setCacheQuery);
2677
3432
  __privateAdd$4(this, _getCacheQuery);
2678
- __privateAdd$4(this, _getSchemaTables$1);
3433
+ __privateAdd$4(this, _getSchemaTables);
3434
+ __privateAdd$4(this, _transformObjectToApi);
2679
3435
  __privateAdd$4(this, _table, void 0);
2680
3436
  __privateAdd$4(this, _getFetchProps, void 0);
2681
3437
  __privateAdd$4(this, _db, void 0);
2682
3438
  __privateAdd$4(this, _cache, void 0);
2683
- __privateAdd$4(this, _schemaTables$2, void 0);
3439
+ __privateAdd$4(this, _schemaTables, void 0);
2684
3440
  __privateAdd$4(this, _trace, void 0);
2685
- __privateSet$4(this, _table, options.table);
2686
- __privateSet$4(this, _db, options.db);
2687
- __privateSet$4(this, _cache, options.pluginOptions.cache);
2688
- __privateSet$4(this, _schemaTables$2, options.schemaTables);
2689
- __privateSet$4(this, _getFetchProps, () => ({ ...options.pluginOptions, sessionID: generateUUID() }));
3441
+ __privateSet$2(this, _table, options.table);
3442
+ __privateSet$2(this, _db, options.db);
3443
+ __privateSet$2(this, _cache, options.pluginOptions.cache);
3444
+ __privateSet$2(this, _schemaTables, options.schemaTables);
3445
+ __privateSet$2(this, _getFetchProps, () => ({ ...options.pluginOptions, sessionID: generateUUID() }));
2690
3446
  const trace = options.pluginOptions.trace ?? defaultTrace;
2691
- __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
3447
+ __privateSet$2(this, _trace, async (name, fn, options2 = {}) => {
2692
3448
  return trace(name, fn, {
2693
3449
  ...options2,
2694
- [TraceAttributes.TABLE]: __privateGet$4(this, _table),
3450
+ [TraceAttributes.TABLE]: __privateGet$3(this, _table),
2695
3451
  [TraceAttributes.KIND]: "sdk-operation",
2696
3452
  [TraceAttributes.VERSION]: VERSION
2697
3453
  });
2698
3454
  });
2699
3455
  }
2700
3456
  async create(a, b, c, d) {
2701
- return __privateGet$4(this, _trace).call(this, "create", async () => {
3457
+ return __privateGet$3(this, _trace).call(this, "create", async () => {
2702
3458
  const ifVersion = parseIfVersion(b, c, d);
2703
3459
  if (Array.isArray(a)) {
2704
3460
  if (a.length === 0)
2705
3461
  return [];
2706
3462
  const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: true });
2707
- const columns = isStringArray(b) ? b : ["*"];
3463
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2708
3464
  const result = await this.read(ids, columns);
2709
3465
  return result;
2710
3466
  }
2711
3467
  if (isString(a) && isObject(b)) {
2712
3468
  if (a === "")
2713
3469
  throw new Error("The id can't be empty");
2714
- const columns = isStringArray(c) ? c : void 0;
3470
+ const columns = isValidSelectableColumns(c) ? c : void 0;
2715
3471
  return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
2716
3472
  }
2717
3473
  if (isObject(a) && isString(a.id)) {
2718
3474
  if (a.id === "")
2719
3475
  throw new Error("The id can't be empty");
2720
- const columns = isStringArray(b) ? b : void 0;
3476
+ const columns = isValidSelectableColumns(b) ? b : void 0;
2721
3477
  return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
2722
3478
  }
2723
3479
  if (isObject(a)) {
2724
- const columns = isStringArray(b) ? b : void 0;
3480
+ const columns = isValidSelectableColumns(b) ? b : void 0;
2725
3481
  return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
2726
3482
  }
2727
3483
  throw new Error("Invalid arguments for create method");
2728
3484
  });
2729
3485
  }
2730
3486
  async read(a, b) {
2731
- return __privateGet$4(this, _trace).call(this, "read", async () => {
2732
- const columns = isStringArray(b) ? b : ["*"];
3487
+ return __privateGet$3(this, _trace).call(this, "read", async () => {
3488
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2733
3489
  if (Array.isArray(a)) {
2734
3490
  if (a.length === 0)
2735
3491
  return [];
@@ -2749,14 +3505,20 @@ class RestRepository extends Query {
2749
3505
  workspace: "{workspaceId}",
2750
3506
  dbBranchName: "{dbBranch}",
2751
3507
  region: "{region}",
2752
- tableName: __privateGet$4(this, _table),
3508
+ tableName: __privateGet$3(this, _table),
2753
3509
  recordId: id
2754
3510
  },
2755
3511
  queryParams: { columns },
2756
- ...__privateGet$4(this, _getFetchProps).call(this)
3512
+ ...__privateGet$3(this, _getFetchProps).call(this)
2757
3513
  });
2758
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2759
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
3514
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
3515
+ return initObject(
3516
+ __privateGet$3(this, _db),
3517
+ schemaTables,
3518
+ __privateGet$3(this, _table),
3519
+ response,
3520
+ columns
3521
+ );
2760
3522
  } catch (e) {
2761
3523
  if (isObject(e) && e.status === 404) {
2762
3524
  return null;
@@ -2768,7 +3530,7 @@ class RestRepository extends Query {
2768
3530
  });
2769
3531
  }
2770
3532
  async readOrThrow(a, b) {
2771
- return __privateGet$4(this, _trace).call(this, "readOrThrow", async () => {
3533
+ return __privateGet$3(this, _trace).call(this, "readOrThrow", async () => {
2772
3534
  const result = await this.read(a, b);
2773
3535
  if (Array.isArray(result)) {
2774
3536
  const missingIds = compact(
@@ -2787,7 +3549,7 @@ class RestRepository extends Query {
2787
3549
  });
2788
3550
  }
2789
3551
  async update(a, b, c, d) {
2790
- return __privateGet$4(this, _trace).call(this, "update", async () => {
3552
+ return __privateGet$3(this, _trace).call(this, "update", async () => {
2791
3553
  const ifVersion = parseIfVersion(b, c, d);
2792
3554
  if (Array.isArray(a)) {
2793
3555
  if (a.length === 0)
@@ -2798,17 +3560,17 @@ class RestRepository extends Query {
2798
3560
  ifVersion,
2799
3561
  upsert: false
2800
3562
  });
2801
- const columns = isStringArray(b) ? b : ["*"];
3563
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2802
3564
  const result = await this.read(a, columns);
2803
3565
  return result;
2804
3566
  }
2805
3567
  try {
2806
3568
  if (isString(a) && isObject(b)) {
2807
- const columns = isStringArray(c) ? c : void 0;
3569
+ const columns = isValidSelectableColumns(c) ? c : void 0;
2808
3570
  return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2809
3571
  }
2810
3572
  if (isObject(a) && isString(a.id)) {
2811
- const columns = isStringArray(b) ? b : void 0;
3573
+ const columns = isValidSelectableColumns(b) ? b : void 0;
2812
3574
  return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
2813
3575
  }
2814
3576
  } catch (error) {
@@ -2820,7 +3582,7 @@ class RestRepository extends Query {
2820
3582
  });
2821
3583
  }
2822
3584
  async updateOrThrow(a, b, c, d) {
2823
- return __privateGet$4(this, _trace).call(this, "updateOrThrow", async () => {
3585
+ return __privateGet$3(this, _trace).call(this, "updateOrThrow", async () => {
2824
3586
  const result = await this.update(a, b, c, d);
2825
3587
  if (Array.isArray(result)) {
2826
3588
  const missingIds = compact(
@@ -2839,7 +3601,7 @@ class RestRepository extends Query {
2839
3601
  });
2840
3602
  }
2841
3603
  async createOrUpdate(a, b, c, d) {
2842
- return __privateGet$4(this, _trace).call(this, "createOrUpdate", async () => {
3604
+ return __privateGet$3(this, _trace).call(this, "createOrUpdate", async () => {
2843
3605
  const ifVersion = parseIfVersion(b, c, d);
2844
3606
  if (Array.isArray(a)) {
2845
3607
  if (a.length === 0)
@@ -2848,45 +3610,65 @@ class RestRepository extends Query {
2848
3610
  ifVersion,
2849
3611
  upsert: true
2850
3612
  });
2851
- const columns = isStringArray(b) ? b : ["*"];
3613
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2852
3614
  const result = await this.read(a, columns);
2853
3615
  return result;
2854
3616
  }
2855
3617
  if (isString(a) && isObject(b)) {
2856
- const columns = isStringArray(c) ? c : void 0;
2857
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3618
+ if (a === "")
3619
+ throw new Error("The id can't be empty");
3620
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3621
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2858
3622
  }
2859
3623
  if (isObject(a) && isString(a.id)) {
2860
- const columns = isStringArray(c) ? c : void 0;
2861
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3624
+ if (a.id === "")
3625
+ throw new Error("The id can't be empty");
3626
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3627
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3628
+ }
3629
+ if (!isDefined(a) && isObject(b)) {
3630
+ return await this.create(b, c);
3631
+ }
3632
+ if (isObject(a) && !isDefined(a.id)) {
3633
+ return await this.create(a, b);
2862
3634
  }
2863
3635
  throw new Error("Invalid arguments for createOrUpdate method");
2864
3636
  });
2865
3637
  }
2866
3638
  async createOrReplace(a, b, c, d) {
2867
- return __privateGet$4(this, _trace).call(this, "createOrReplace", async () => {
3639
+ return __privateGet$3(this, _trace).call(this, "createOrReplace", async () => {
2868
3640
  const ifVersion = parseIfVersion(b, c, d);
2869
3641
  if (Array.isArray(a)) {
2870
3642
  if (a.length === 0)
2871
3643
  return [];
2872
3644
  const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: false });
2873
- const columns = isStringArray(b) ? b : ["*"];
3645
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2874
3646
  const result = await this.read(ids, columns);
2875
3647
  return result;
2876
3648
  }
2877
3649
  if (isString(a) && isObject(b)) {
2878
- const columns = isStringArray(c) ? c : void 0;
2879
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
3650
+ if (a === "")
3651
+ throw new Error("The id can't be empty");
3652
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3653
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
2880
3654
  }
2881
3655
  if (isObject(a) && isString(a.id)) {
2882
- const columns = isStringArray(c) ? c : void 0;
2883
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3656
+ if (a.id === "")
3657
+ throw new Error("The id can't be empty");
3658
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3659
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3660
+ }
3661
+ if (!isDefined(a) && isObject(b)) {
3662
+ return await this.create(b, c);
3663
+ }
3664
+ if (isObject(a) && !isDefined(a.id)) {
3665
+ return await this.create(a, b);
2884
3666
  }
2885
3667
  throw new Error("Invalid arguments for createOrReplace method");
2886
3668
  });
2887
3669
  }
2888
3670
  async delete(a, b) {
2889
- return __privateGet$4(this, _trace).call(this, "delete", async () => {
3671
+ return __privateGet$3(this, _trace).call(this, "delete", async () => {
2890
3672
  if (Array.isArray(a)) {
2891
3673
  if (a.length === 0)
2892
3674
  return [];
@@ -2897,7 +3679,7 @@ class RestRepository extends Query {
2897
3679
  return o.id;
2898
3680
  throw new Error("Invalid arguments for delete method");
2899
3681
  });
2900
- const columns = isStringArray(b) ? b : ["*"];
3682
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2901
3683
  const result = await this.read(a, columns);
2902
3684
  await __privateMethod$2(this, _deleteRecords, deleteRecords_fn).call(this, ids);
2903
3685
  return result;
@@ -2912,7 +3694,7 @@ class RestRepository extends Query {
2912
3694
  });
2913
3695
  }
2914
3696
  async deleteOrThrow(a, b) {
2915
- return __privateGet$4(this, _trace).call(this, "deleteOrThrow", async () => {
3697
+ return __privateGet$3(this, _trace).call(this, "deleteOrThrow", async () => {
2916
3698
  const result = await this.delete(a, b);
2917
3699
  if (Array.isArray(result)) {
2918
3700
  const missingIds = compact(
@@ -2930,13 +3712,13 @@ class RestRepository extends Query {
2930
3712
  });
2931
3713
  }
2932
3714
  async search(query, options = {}) {
2933
- return __privateGet$4(this, _trace).call(this, "search", async () => {
2934
- const { records } = await searchTable({
3715
+ return __privateGet$3(this, _trace).call(this, "search", async () => {
3716
+ const { records, totalCount } = await searchTable({
2935
3717
  pathParams: {
2936
3718
  workspace: "{workspaceId}",
2937
3719
  dbBranchName: "{dbBranch}",
2938
3720
  region: "{region}",
2939
- tableName: __privateGet$4(this, _table)
3721
+ tableName: __privateGet$3(this, _table)
2940
3722
  },
2941
3723
  body: {
2942
3724
  query,
@@ -2948,20 +3730,23 @@ class RestRepository extends Query {
2948
3730
  page: options.page,
2949
3731
  target: options.target
2950
3732
  },
2951
- ...__privateGet$4(this, _getFetchProps).call(this)
3733
+ ...__privateGet$3(this, _getFetchProps).call(this)
2952
3734
  });
2953
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2954
- return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
3735
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
3736
+ return {
3737
+ records: records.map((item) => initObject(__privateGet$3(this, _db), schemaTables, __privateGet$3(this, _table), item, ["*"])),
3738
+ totalCount
3739
+ };
2955
3740
  });
2956
3741
  }
2957
3742
  async vectorSearch(column, query, options) {
2958
- return __privateGet$4(this, _trace).call(this, "vectorSearch", async () => {
2959
- const { records } = await vectorSearchTable({
3743
+ return __privateGet$3(this, _trace).call(this, "vectorSearch", async () => {
3744
+ const { records, totalCount } = await vectorSearchTable({
2960
3745
  pathParams: {
2961
3746
  workspace: "{workspaceId}",
2962
3747
  dbBranchName: "{dbBranch}",
2963
3748
  region: "{region}",
2964
- tableName: __privateGet$4(this, _table)
3749
+ tableName: __privateGet$3(this, _table)
2965
3750
  },
2966
3751
  body: {
2967
3752
  column,
@@ -2970,29 +3755,32 @@ class RestRepository extends Query {
2970
3755
  size: options?.size,
2971
3756
  filter: options?.filter
2972
3757
  },
2973
- ...__privateGet$4(this, _getFetchProps).call(this)
3758
+ ...__privateGet$3(this, _getFetchProps).call(this)
2974
3759
  });
2975
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2976
- return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
3760
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
3761
+ return {
3762
+ records: records.map((item) => initObject(__privateGet$3(this, _db), schemaTables, __privateGet$3(this, _table), item, ["*"])),
3763
+ totalCount
3764
+ };
2977
3765
  });
2978
3766
  }
2979
3767
  async aggregate(aggs, filter) {
2980
- return __privateGet$4(this, _trace).call(this, "aggregate", async () => {
3768
+ return __privateGet$3(this, _trace).call(this, "aggregate", async () => {
2981
3769
  const result = await aggregateTable({
2982
3770
  pathParams: {
2983
3771
  workspace: "{workspaceId}",
2984
3772
  dbBranchName: "{dbBranch}",
2985
3773
  region: "{region}",
2986
- tableName: __privateGet$4(this, _table)
3774
+ tableName: __privateGet$3(this, _table)
2987
3775
  },
2988
3776
  body: { aggs, filter },
2989
- ...__privateGet$4(this, _getFetchProps).call(this)
3777
+ ...__privateGet$3(this, _getFetchProps).call(this)
2990
3778
  });
2991
3779
  return result;
2992
3780
  });
2993
3781
  }
2994
3782
  async query(query) {
2995
- return __privateGet$4(this, _trace).call(this, "query", async () => {
3783
+ return __privateGet$3(this, _trace).call(this, "query", async () => {
2996
3784
  const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
2997
3785
  if (cacheQuery)
2998
3786
  return new Page(query, cacheQuery.meta, cacheQuery.records);
@@ -3002,7 +3790,7 @@ class RestRepository extends Query {
3002
3790
  workspace: "{workspaceId}",
3003
3791
  dbBranchName: "{dbBranch}",
3004
3792
  region: "{region}",
3005
- tableName: __privateGet$4(this, _table)
3793
+ tableName: __privateGet$3(this, _table)
3006
3794
  },
3007
3795
  body: {
3008
3796
  filter: cleanFilter(data.filter),
@@ -3012,25 +3800,31 @@ class RestRepository extends Query {
3012
3800
  consistency: data.consistency
3013
3801
  },
3014
3802
  fetchOptions: data.fetchOptions,
3015
- ...__privateGet$4(this, _getFetchProps).call(this)
3803
+ ...__privateGet$3(this, _getFetchProps).call(this)
3016
3804
  });
3017
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3805
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
3018
3806
  const records = objects.map(
3019
- (record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record, data.columns ?? ["*"])
3807
+ (record) => initObject(
3808
+ __privateGet$3(this, _db),
3809
+ schemaTables,
3810
+ __privateGet$3(this, _table),
3811
+ record,
3812
+ data.columns ?? ["*"]
3813
+ )
3020
3814
  );
3021
3815
  await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
3022
3816
  return new Page(query, meta, records);
3023
3817
  });
3024
3818
  }
3025
3819
  async summarizeTable(query, summaries, summariesFilter) {
3026
- return __privateGet$4(this, _trace).call(this, "summarize", async () => {
3820
+ return __privateGet$3(this, _trace).call(this, "summarize", async () => {
3027
3821
  const data = query.getQueryOptions();
3028
3822
  const result = await summarizeTable({
3029
3823
  pathParams: {
3030
3824
  workspace: "{workspaceId}",
3031
3825
  dbBranchName: "{dbBranch}",
3032
3826
  region: "{region}",
3033
- tableName: __privateGet$4(this, _table)
3827
+ tableName: __privateGet$3(this, _table)
3034
3828
  },
3035
3829
  body: {
3036
3830
  filter: cleanFilter(data.filter),
@@ -3041,29 +3835,40 @@ class RestRepository extends Query {
3041
3835
  summaries,
3042
3836
  summariesFilter
3043
3837
  },
3044
- ...__privateGet$4(this, _getFetchProps).call(this)
3838
+ ...__privateGet$3(this, _getFetchProps).call(this)
3045
3839
  });
3046
- return result;
3840
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
3841
+ return {
3842
+ ...result,
3843
+ summaries: result.summaries.map(
3844
+ (summary) => initObject(__privateGet$3(this, _db), schemaTables, __privateGet$3(this, _table), summary, data.columns ?? [])
3845
+ )
3846
+ };
3047
3847
  });
3048
3848
  }
3049
3849
  ask(question, options) {
3850
+ const questionParam = options?.sessionId ? { message: question } : { question };
3050
3851
  const params = {
3051
3852
  pathParams: {
3052
3853
  workspace: "{workspaceId}",
3053
3854
  dbBranchName: "{dbBranch}",
3054
3855
  region: "{region}",
3055
- tableName: __privateGet$4(this, _table)
3856
+ tableName: __privateGet$3(this, _table),
3857
+ sessionId: options?.sessionId
3056
3858
  },
3057
3859
  body: {
3058
- question,
3059
- ...options
3860
+ ...questionParam,
3861
+ rules: options?.rules,
3862
+ searchType: options?.searchType,
3863
+ search: options?.searchType === "keyword" ? options?.search : void 0,
3864
+ vectorSearch: options?.searchType === "vector" ? options?.vectorSearch : void 0
3060
3865
  },
3061
- ...__privateGet$4(this, _getFetchProps).call(this)
3866
+ ...__privateGet$3(this, _getFetchProps).call(this)
3062
3867
  };
3063
3868
  if (options?.onMessage) {
3064
3869
  fetchSSERequest({
3065
3870
  endpoint: "dataPlane",
3066
- url: "/db/{dbBranchName}/tables/{tableName}/ask",
3871
+ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}",
3067
3872
  method: "POST",
3068
3873
  onMessage: (message) => {
3069
3874
  options.onMessage?.({ answer: message.text, records: message.records });
@@ -3071,7 +3876,7 @@ class RestRepository extends Query {
3071
3876
  ...params
3072
3877
  });
3073
3878
  } else {
3074
- return askTable(params);
3879
+ return askTableSession(params);
3075
3880
  }
3076
3881
  }
3077
3882
  }
@@ -3079,61 +3884,62 @@ _table = new WeakMap();
3079
3884
  _getFetchProps = new WeakMap();
3080
3885
  _db = new WeakMap();
3081
3886
  _cache = new WeakMap();
3082
- _schemaTables$2 = new WeakMap();
3887
+ _schemaTables = new WeakMap();
3083
3888
  _trace = new WeakMap();
3084
3889
  _insertRecordWithoutId = new WeakSet();
3085
3890
  insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
3086
- const record = transformObjectLinks(object);
3891
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3087
3892
  const response = await insertRecord({
3088
3893
  pathParams: {
3089
3894
  workspace: "{workspaceId}",
3090
3895
  dbBranchName: "{dbBranch}",
3091
3896
  region: "{region}",
3092
- tableName: __privateGet$4(this, _table)
3897
+ tableName: __privateGet$3(this, _table)
3093
3898
  },
3094
3899
  queryParams: { columns },
3095
3900
  body: record,
3096
- ...__privateGet$4(this, _getFetchProps).call(this)
3901
+ ...__privateGet$3(this, _getFetchProps).call(this)
3097
3902
  });
3098
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3099
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
3903
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
3904
+ return initObject(__privateGet$3(this, _db), schemaTables, __privateGet$3(this, _table), response, columns);
3100
3905
  };
3101
3906
  _insertRecordWithId = new WeakSet();
3102
3907
  insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { createOnly, ifVersion }) {
3103
- const record = transformObjectLinks(object);
3908
+ if (!recordId)
3909
+ return null;
3910
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3104
3911
  const response = await insertRecordWithID({
3105
3912
  pathParams: {
3106
3913
  workspace: "{workspaceId}",
3107
3914
  dbBranchName: "{dbBranch}",
3108
3915
  region: "{region}",
3109
- tableName: __privateGet$4(this, _table),
3916
+ tableName: __privateGet$3(this, _table),
3110
3917
  recordId
3111
3918
  },
3112
3919
  body: record,
3113
3920
  queryParams: { createOnly, columns, ifVersion },
3114
- ...__privateGet$4(this, _getFetchProps).call(this)
3921
+ ...__privateGet$3(this, _getFetchProps).call(this)
3115
3922
  });
3116
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3117
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
3923
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
3924
+ return initObject(__privateGet$3(this, _db), schemaTables, __privateGet$3(this, _table), response, columns);
3118
3925
  };
3119
3926
  _insertRecords = new WeakSet();
3120
3927
  insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
3121
- const chunkedOperations = chunk(
3122
- objects.map((object) => ({
3123
- insert: { table: __privateGet$4(this, _table), record: transformObjectLinks(object), createOnly, ifVersion }
3124
- })),
3125
- BULK_OPERATION_MAX_SIZE
3126
- );
3928
+ const operations = await promiseMap(objects, async (object) => {
3929
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3930
+ return { insert: { table: __privateGet$3(this, _table), record, createOnly, ifVersion } };
3931
+ });
3932
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
3127
3933
  const ids = [];
3128
- for (const operations of chunkedOperations) {
3934
+ for (const operations2 of chunkedOperations) {
3129
3935
  const { results } = await branchTransaction({
3130
3936
  pathParams: {
3131
3937
  workspace: "{workspaceId}",
3132
3938
  dbBranchName: "{dbBranch}",
3133
3939
  region: "{region}"
3134
3940
  },
3135
- body: { operations },
3136
- ...__privateGet$4(this, _getFetchProps).call(this)
3941
+ body: { operations: operations2 },
3942
+ ...__privateGet$3(this, _getFetchProps).call(this)
3137
3943
  });
3138
3944
  for (const result of results) {
3139
3945
  if (result.operation === "insert") {
@@ -3147,22 +3953,24 @@ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
3147
3953
  };
3148
3954
  _updateRecordWithID = new WeakSet();
3149
3955
  updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
3150
- const { id: _id, ...record } = transformObjectLinks(object);
3956
+ if (!recordId)
3957
+ return null;
3958
+ const { id: _id, ...record } = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3151
3959
  try {
3152
3960
  const response = await updateRecordWithID({
3153
3961
  pathParams: {
3154
3962
  workspace: "{workspaceId}",
3155
3963
  dbBranchName: "{dbBranch}",
3156
3964
  region: "{region}",
3157
- tableName: __privateGet$4(this, _table),
3965
+ tableName: __privateGet$3(this, _table),
3158
3966
  recordId
3159
3967
  },
3160
3968
  queryParams: { columns, ifVersion },
3161
3969
  body: record,
3162
- ...__privateGet$4(this, _getFetchProps).call(this)
3970
+ ...__privateGet$3(this, _getFetchProps).call(this)
3163
3971
  });
3164
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3165
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
3972
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
3973
+ return initObject(__privateGet$3(this, _db), schemaTables, __privateGet$3(this, _table), response, columns);
3166
3974
  } catch (e) {
3167
3975
  if (isObject(e) && e.status === 404) {
3168
3976
  return null;
@@ -3172,22 +3980,21 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
3172
3980
  };
3173
3981
  _updateRecords = new WeakSet();
3174
3982
  updateRecords_fn = async function(objects, { ifVersion, upsert }) {
3175
- const chunkedOperations = chunk(
3176
- objects.map(({ id, ...object }) => ({
3177
- update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields: transformObjectLinks(object) }
3178
- })),
3179
- BULK_OPERATION_MAX_SIZE
3180
- );
3983
+ const operations = await promiseMap(objects, async ({ id, ...object }) => {
3984
+ const fields = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3985
+ return { update: { table: __privateGet$3(this, _table), id, ifVersion, upsert, fields } };
3986
+ });
3987
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
3181
3988
  const ids = [];
3182
- for (const operations of chunkedOperations) {
3989
+ for (const operations2 of chunkedOperations) {
3183
3990
  const { results } = await branchTransaction({
3184
3991
  pathParams: {
3185
3992
  workspace: "{workspaceId}",
3186
3993
  dbBranchName: "{dbBranch}",
3187
3994
  region: "{region}"
3188
3995
  },
3189
- body: { operations },
3190
- ...__privateGet$4(this, _getFetchProps).call(this)
3996
+ body: { operations: operations2 },
3997
+ ...__privateGet$3(this, _getFetchProps).call(this)
3191
3998
  });
3192
3999
  for (const result of results) {
3193
4000
  if (result.operation === "update") {
@@ -3201,37 +4008,41 @@ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
3201
4008
  };
3202
4009
  _upsertRecordWithID = new WeakSet();
3203
4010
  upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
4011
+ if (!recordId)
4012
+ return null;
3204
4013
  const response = await upsertRecordWithID({
3205
4014
  pathParams: {
3206
4015
  workspace: "{workspaceId}",
3207
4016
  dbBranchName: "{dbBranch}",
3208
4017
  region: "{region}",
3209
- tableName: __privateGet$4(this, _table),
4018
+ tableName: __privateGet$3(this, _table),
3210
4019
  recordId
3211
4020
  },
3212
4021
  queryParams: { columns, ifVersion },
3213
4022
  body: object,
3214
- ...__privateGet$4(this, _getFetchProps).call(this)
4023
+ ...__privateGet$3(this, _getFetchProps).call(this)
3215
4024
  });
3216
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3217
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
4025
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
4026
+ return initObject(__privateGet$3(this, _db), schemaTables, __privateGet$3(this, _table), response, columns);
3218
4027
  };
3219
4028
  _deleteRecord = new WeakSet();
3220
4029
  deleteRecord_fn = async function(recordId, columns = ["*"]) {
4030
+ if (!recordId)
4031
+ return null;
3221
4032
  try {
3222
4033
  const response = await deleteRecord({
3223
4034
  pathParams: {
3224
4035
  workspace: "{workspaceId}",
3225
4036
  dbBranchName: "{dbBranch}",
3226
4037
  region: "{region}",
3227
- tableName: __privateGet$4(this, _table),
4038
+ tableName: __privateGet$3(this, _table),
3228
4039
  recordId
3229
4040
  },
3230
4041
  queryParams: { columns },
3231
- ...__privateGet$4(this, _getFetchProps).call(this)
4042
+ ...__privateGet$3(this, _getFetchProps).call(this)
3232
4043
  });
3233
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3234
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
4044
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
4045
+ return initObject(__privateGet$3(this, _db), schemaTables, __privateGet$3(this, _table), response, columns);
3235
4046
  } catch (e) {
3236
4047
  if (isObject(e) && e.status === 404) {
3237
4048
  return null;
@@ -3242,7 +4053,7 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
3242
4053
  _deleteRecords = new WeakSet();
3243
4054
  deleteRecords_fn = async function(recordIds) {
3244
4055
  const chunkedOperations = chunk(
3245
- recordIds.map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
4056
+ compact(recordIds).map((id) => ({ delete: { table: __privateGet$3(this, _table), id } })),
3246
4057
  BULK_OPERATION_MAX_SIZE
3247
4058
  );
3248
4059
  for (const operations of chunkedOperations) {
@@ -3253,44 +4064,72 @@ deleteRecords_fn = async function(recordIds) {
3253
4064
  region: "{region}"
3254
4065
  },
3255
4066
  body: { operations },
3256
- ...__privateGet$4(this, _getFetchProps).call(this)
4067
+ ...__privateGet$3(this, _getFetchProps).call(this)
3257
4068
  });
3258
4069
  }
3259
4070
  };
3260
4071
  _setCacheQuery = new WeakSet();
3261
4072
  setCacheQuery_fn = async function(query, meta, records) {
3262
- await __privateGet$4(this, _cache)?.set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
4073
+ await __privateGet$3(this, _cache)?.set(`query_${__privateGet$3(this, _table)}:${query.key()}`, { date: /* @__PURE__ */ new Date(), meta, records });
3263
4074
  };
3264
4075
  _getCacheQuery = new WeakSet();
3265
4076
  getCacheQuery_fn = async function(query) {
3266
- const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
3267
- const result = await __privateGet$4(this, _cache)?.get(key);
4077
+ const key = `query_${__privateGet$3(this, _table)}:${query.key()}`;
4078
+ const result = await __privateGet$3(this, _cache)?.get(key);
3268
4079
  if (!result)
3269
4080
  return null;
3270
- const defaultTTL = __privateGet$4(this, _cache)?.defaultQueryTTL ?? -1;
4081
+ const defaultTTL = __privateGet$3(this, _cache)?.defaultQueryTTL ?? -1;
3271
4082
  const { cache: ttl = defaultTTL } = query.getQueryOptions();
3272
4083
  if (ttl < 0)
3273
4084
  return null;
3274
4085
  const hasExpired = result.date.getTime() + ttl < Date.now();
3275
4086
  return hasExpired ? null : result;
3276
4087
  };
3277
- _getSchemaTables$1 = new WeakSet();
3278
- getSchemaTables_fn$1 = async function() {
3279
- if (__privateGet$4(this, _schemaTables$2))
3280
- return __privateGet$4(this, _schemaTables$2);
4088
+ _getSchemaTables = new WeakSet();
4089
+ getSchemaTables_fn = async function() {
4090
+ if (__privateGet$3(this, _schemaTables))
4091
+ return __privateGet$3(this, _schemaTables);
3281
4092
  const { schema } = await getBranchDetails({
3282
4093
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3283
- ...__privateGet$4(this, _getFetchProps).call(this)
4094
+ ...__privateGet$3(this, _getFetchProps).call(this)
3284
4095
  });
3285
- __privateSet$4(this, _schemaTables$2, schema.tables);
4096
+ __privateSet$2(this, _schemaTables, schema.tables);
3286
4097
  return schema.tables;
3287
4098
  };
3288
- const transformObjectLinks = (object) => {
3289
- return Object.entries(object).reduce((acc, [key, value]) => {
4099
+ _transformObjectToApi = new WeakSet();
4100
+ transformObjectToApi_fn = async function(object) {
4101
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables, getSchemaTables_fn).call(this);
4102
+ const schema = schemaTables.find((table) => table.name === __privateGet$3(this, _table));
4103
+ if (!schema)
4104
+ throw new Error(`Table ${__privateGet$3(this, _table)} not found in schema`);
4105
+ const result = {};
4106
+ for (const [key, value] of Object.entries(object)) {
3290
4107
  if (key === "xata")
3291
- return acc;
3292
- return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
3293
- }, {});
4108
+ continue;
4109
+ const type = schema.columns.find((column) => column.name === key)?.type;
4110
+ switch (type) {
4111
+ case "link": {
4112
+ result[key] = isIdentifiable(value) ? value.id : value;
4113
+ break;
4114
+ }
4115
+ case "datetime": {
4116
+ result[key] = value instanceof Date ? value.toISOString() : value;
4117
+ break;
4118
+ }
4119
+ case `file`:
4120
+ result[key] = await parseInputFileEntry(value);
4121
+ break;
4122
+ case "file[]":
4123
+ result[key] = await promiseMap(value, (item) => parseInputFileEntry(item));
4124
+ break;
4125
+ case "json":
4126
+ result[key] = stringifyJson(value);
4127
+ break;
4128
+ default:
4129
+ result[key] = value;
4130
+ }
4131
+ }
4132
+ return result;
3294
4133
  };
3295
4134
  const initObject = (db, schemaTables, table, object, selectedColumns) => {
3296
4135
  const data = {};
@@ -3322,18 +4161,33 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
3322
4161
  if (item === column.name) {
3323
4162
  return [...acc, "*"];
3324
4163
  }
3325
- if (item.startsWith(`${column.name}.`)) {
4164
+ if (isString(item) && item.startsWith(`${column.name}.`)) {
3326
4165
  const [, ...path] = item.split(".");
3327
4166
  return [...acc, path.join(".")];
3328
4167
  }
3329
4168
  return acc;
3330
4169
  }, []);
3331
- data[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
4170
+ data[column.name] = initObject(
4171
+ db,
4172
+ schemaTables,
4173
+ linkTable,
4174
+ value,
4175
+ selectedLinkColumns
4176
+ );
3332
4177
  } else {
3333
4178
  data[column.name] = null;
3334
4179
  }
3335
4180
  break;
3336
4181
  }
4182
+ case "file":
4183
+ data[column.name] = isDefined(value) ? new XataFile(value) : null;
4184
+ break;
4185
+ case "file[]":
4186
+ data[column.name] = value?.map((item) => new XataFile(item)) ?? null;
4187
+ break;
4188
+ case "json":
4189
+ data[column.name] = parseJson(value);
4190
+ break;
3337
4191
  default:
3338
4192
  data[column.name] = value ?? null;
3339
4193
  if (column.notNull === true && value === null) {
@@ -3343,30 +4197,34 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
3343
4197
  }
3344
4198
  }
3345
4199
  const record = { ...data };
4200
+ const metadata = xata !== void 0 ? { ...xata, createdAt: new Date(xata.createdAt), updatedAt: new Date(xata.updatedAt) } : void 0;
3346
4201
  record.read = function(columns2) {
3347
4202
  return db[table].read(record["id"], columns2);
3348
4203
  };
3349
4204
  record.update = function(data2, b, c) {
3350
- const columns2 = isStringArray(b) ? b : ["*"];
4205
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
3351
4206
  const ifVersion = parseIfVersion(b, c);
3352
4207
  return db[table].update(record["id"], data2, columns2, { ifVersion });
3353
4208
  };
3354
4209
  record.replace = function(data2, b, c) {
3355
- const columns2 = isStringArray(b) ? b : ["*"];
4210
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
3356
4211
  const ifVersion = parseIfVersion(b, c);
3357
4212
  return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
3358
4213
  };
3359
4214
  record.delete = function() {
3360
4215
  return db[table].delete(record["id"]);
3361
4216
  };
4217
+ if (metadata !== void 0) {
4218
+ record.xata = Object.freeze(metadata);
4219
+ }
3362
4220
  record.getMetadata = function() {
3363
- return xata;
4221
+ return record.xata;
3364
4222
  };
3365
4223
  record.toSerializable = function() {
3366
- return JSON.parse(JSON.stringify(transformObjectLinks(data)));
4224
+ return JSON.parse(JSON.stringify(record));
3367
4225
  };
3368
4226
  record.toString = function() {
3369
- return JSON.stringify(transformObjectLinks(data));
4227
+ return JSON.stringify(record);
3370
4228
  };
3371
4229
  for (const prop of ["read", "update", "replace", "delete", "getMetadata", "toSerializable", "toString"]) {
3372
4230
  Object.defineProperty(record, prop, { enumerable: false });
@@ -3384,11 +4242,7 @@ function extractId(value) {
3384
4242
  function isValidColumn(columns, column) {
3385
4243
  if (columns.includes("*"))
3386
4244
  return true;
3387
- if (column.type === "link") {
3388
- const linkColumns = columns.filter((item) => item.startsWith(column.name));
3389
- return linkColumns.length > 0;
3390
- }
3391
- return columns.includes(column.name);
4245
+ return columns.filter((item) => isString(item) && item.startsWith(column.name)).length > 0;
3392
4246
  }
3393
4247
  function parseIfVersion(...args) {
3394
4248
  for (const arg of args) {
@@ -3403,7 +4257,7 @@ var __accessCheck$3 = (obj, member, msg) => {
3403
4257
  if (!member.has(obj))
3404
4258
  throw TypeError("Cannot " + msg);
3405
4259
  };
3406
- var __privateGet$3 = (obj, member, getter) => {
4260
+ var __privateGet$2 = (obj, member, getter) => {
3407
4261
  __accessCheck$3(obj, member, "read from private field");
3408
4262
  return getter ? getter.call(obj) : member.get(obj);
3409
4263
  };
@@ -3412,7 +4266,7 @@ var __privateAdd$3 = (obj, member, value) => {
3412
4266
  throw TypeError("Cannot add the same private member more than once");
3413
4267
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
3414
4268
  };
3415
- var __privateSet$3 = (obj, member, value, setter) => {
4269
+ var __privateSet$1 = (obj, member, value, setter) => {
3416
4270
  __accessCheck$3(obj, member, "write to private field");
3417
4271
  setter ? setter.call(obj, value) : member.set(obj, value);
3418
4272
  return value;
@@ -3421,29 +4275,29 @@ var _map;
3421
4275
  class SimpleCache {
3422
4276
  constructor(options = {}) {
3423
4277
  __privateAdd$3(this, _map, void 0);
3424
- __privateSet$3(this, _map, /* @__PURE__ */ new Map());
4278
+ __privateSet$1(this, _map, /* @__PURE__ */ new Map());
3425
4279
  this.capacity = options.max ?? 500;
3426
4280
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
3427
4281
  }
3428
4282
  async getAll() {
3429
- return Object.fromEntries(__privateGet$3(this, _map));
4283
+ return Object.fromEntries(__privateGet$2(this, _map));
3430
4284
  }
3431
4285
  async get(key) {
3432
- return __privateGet$3(this, _map).get(key) ?? null;
4286
+ return __privateGet$2(this, _map).get(key) ?? null;
3433
4287
  }
3434
4288
  async set(key, value) {
3435
4289
  await this.delete(key);
3436
- __privateGet$3(this, _map).set(key, value);
3437
- if (__privateGet$3(this, _map).size > this.capacity) {
3438
- const leastRecentlyUsed = __privateGet$3(this, _map).keys().next().value;
4290
+ __privateGet$2(this, _map).set(key, value);
4291
+ if (__privateGet$2(this, _map).size > this.capacity) {
4292
+ const leastRecentlyUsed = __privateGet$2(this, _map).keys().next().value;
3439
4293
  await this.delete(leastRecentlyUsed);
3440
4294
  }
3441
4295
  }
3442
4296
  async delete(key) {
3443
- __privateGet$3(this, _map).delete(key);
4297
+ __privateGet$2(this, _map).delete(key);
3444
4298
  }
3445
4299
  async clear() {
3446
- return __privateGet$3(this, _map).clear();
4300
+ return __privateGet$2(this, _map).clear();
3447
4301
  }
3448
4302
  }
3449
4303
  _map = new WeakMap();
@@ -3465,10 +4319,12 @@ const notExists = (column) => ({ $notExists: column });
3465
4319
  const startsWith = (value) => ({ $startsWith: value });
3466
4320
  const endsWith = (value) => ({ $endsWith: value });
3467
4321
  const pattern = (value) => ({ $pattern: value });
4322
+ const iPattern = (value) => ({ $iPattern: value });
3468
4323
  const is = (value) => ({ $is: value });
3469
4324
  const equals = is;
3470
4325
  const isNot = (value) => ({ $isNot: value });
3471
4326
  const contains = (value) => ({ $contains: value });
4327
+ const iContains = (value) => ({ $iContains: value });
3472
4328
  const includes = (value) => ({ $includes: value });
3473
4329
  const includesAll = (value) => ({ $includesAll: value });
3474
4330
  const includesNone = (value) => ({ $includesNone: value });
@@ -3478,7 +4334,7 @@ var __accessCheck$2 = (obj, member, msg) => {
3478
4334
  if (!member.has(obj))
3479
4335
  throw TypeError("Cannot " + msg);
3480
4336
  };
3481
- var __privateGet$2 = (obj, member, getter) => {
4337
+ var __privateGet$1 = (obj, member, getter) => {
3482
4338
  __accessCheck$2(obj, member, "read from private field");
3483
4339
  return getter ? getter.call(obj) : member.get(obj);
3484
4340
  };
@@ -3487,18 +4343,11 @@ var __privateAdd$2 = (obj, member, value) => {
3487
4343
  throw TypeError("Cannot add the same private member more than once");
3488
4344
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
3489
4345
  };
3490
- var __privateSet$2 = (obj, member, value, setter) => {
3491
- __accessCheck$2(obj, member, "write to private field");
3492
- setter ? setter.call(obj, value) : member.set(obj, value);
3493
- return value;
3494
- };
3495
- var _tables, _schemaTables$1;
4346
+ var _tables;
3496
4347
  class SchemaPlugin extends XataPlugin {
3497
- constructor(schemaTables) {
4348
+ constructor() {
3498
4349
  super();
3499
4350
  __privateAdd$2(this, _tables, {});
3500
- __privateAdd$2(this, _schemaTables$1, void 0);
3501
- __privateSet$2(this, _schemaTables$1, schemaTables);
3502
4351
  }
3503
4352
  build(pluginOptions) {
3504
4353
  const db = new Proxy(
@@ -3507,101 +4356,234 @@ class SchemaPlugin extends XataPlugin {
3507
4356
  get: (_target, table) => {
3508
4357
  if (!isString(table))
3509
4358
  throw new Error("Invalid table name");
3510
- if (__privateGet$2(this, _tables)[table] === void 0) {
3511
- __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
4359
+ if (__privateGet$1(this, _tables)[table] === void 0) {
4360
+ __privateGet$1(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: pluginOptions.tables });
3512
4361
  }
3513
- return __privateGet$2(this, _tables)[table];
4362
+ return __privateGet$1(this, _tables)[table];
3514
4363
  }
3515
4364
  }
3516
4365
  );
3517
- const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
4366
+ const tableNames = pluginOptions.tables?.map(({ name }) => name) ?? [];
3518
4367
  for (const table of tableNames) {
3519
- db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
4368
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: pluginOptions.tables });
3520
4369
  }
3521
4370
  return db;
3522
4371
  }
3523
4372
  }
3524
4373
  _tables = new WeakMap();
3525
- _schemaTables$1 = new WeakMap();
4374
+
4375
+ class FilesPlugin extends XataPlugin {
4376
+ build(pluginOptions) {
4377
+ return {
4378
+ download: async (location) => {
4379
+ const { table, record, column, fileId = "" } = location ?? {};
4380
+ return await getFileItem({
4381
+ pathParams: {
4382
+ workspace: "{workspaceId}",
4383
+ dbBranchName: "{dbBranch}",
4384
+ region: "{region}",
4385
+ tableName: table ?? "",
4386
+ recordId: record ?? "",
4387
+ columnName: column ?? "",
4388
+ fileId
4389
+ },
4390
+ ...pluginOptions,
4391
+ rawResponse: true
4392
+ });
4393
+ },
4394
+ upload: async (location, file, options) => {
4395
+ const { table, record, column, fileId = "" } = location ?? {};
4396
+ const resolvedFile = await file;
4397
+ const contentType = options?.mediaType || getContentType(resolvedFile);
4398
+ const body = resolvedFile instanceof XataFile ? resolvedFile.toBlob() : resolvedFile;
4399
+ return await putFileItem({
4400
+ ...pluginOptions,
4401
+ pathParams: {
4402
+ workspace: "{workspaceId}",
4403
+ dbBranchName: "{dbBranch}",
4404
+ region: "{region}",
4405
+ tableName: table ?? "",
4406
+ recordId: record ?? "",
4407
+ columnName: column ?? "",
4408
+ fileId
4409
+ },
4410
+ body,
4411
+ headers: { "Content-Type": contentType }
4412
+ });
4413
+ },
4414
+ delete: async (location) => {
4415
+ const { table, record, column, fileId = "" } = location ?? {};
4416
+ return await deleteFileItem({
4417
+ pathParams: {
4418
+ workspace: "{workspaceId}",
4419
+ dbBranchName: "{dbBranch}",
4420
+ region: "{region}",
4421
+ tableName: table ?? "",
4422
+ recordId: record ?? "",
4423
+ columnName: column ?? "",
4424
+ fileId
4425
+ },
4426
+ ...pluginOptions
4427
+ });
4428
+ }
4429
+ };
4430
+ }
4431
+ }
4432
+ function getContentType(file) {
4433
+ if (typeof file === "string") {
4434
+ return "text/plain";
4435
+ }
4436
+ if ("mediaType" in file && file.mediaType !== void 0) {
4437
+ return file.mediaType;
4438
+ }
4439
+ if (isBlob(file)) {
4440
+ return file.type;
4441
+ }
4442
+ try {
4443
+ return file.type;
4444
+ } catch (e) {
4445
+ }
4446
+ return "application/octet-stream";
4447
+ }
3526
4448
 
3527
4449
  var __accessCheck$1 = (obj, member, msg) => {
3528
4450
  if (!member.has(obj))
3529
4451
  throw TypeError("Cannot " + msg);
3530
4452
  };
3531
- var __privateGet$1 = (obj, member, getter) => {
3532
- __accessCheck$1(obj, member, "read from private field");
3533
- return getter ? getter.call(obj) : member.get(obj);
3534
- };
3535
4453
  var __privateAdd$1 = (obj, member, value) => {
3536
4454
  if (member.has(obj))
3537
4455
  throw TypeError("Cannot add the same private member more than once");
3538
4456
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
3539
4457
  };
3540
- var __privateSet$1 = (obj, member, value, setter) => {
3541
- __accessCheck$1(obj, member, "write to private field");
3542
- setter ? setter.call(obj, value) : member.set(obj, value);
3543
- return value;
3544
- };
3545
4458
  var __privateMethod$1 = (obj, member, method) => {
3546
4459
  __accessCheck$1(obj, member, "access private method");
3547
4460
  return method;
3548
4461
  };
3549
- var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
4462
+ var _search, search_fn;
3550
4463
  class SearchPlugin extends XataPlugin {
3551
- constructor(db, schemaTables) {
4464
+ constructor(db) {
3552
4465
  super();
3553
4466
  this.db = db;
3554
4467
  __privateAdd$1(this, _search);
3555
- __privateAdd$1(this, _getSchemaTables);
3556
- __privateAdd$1(this, _schemaTables, void 0);
3557
- __privateSet$1(this, _schemaTables, schemaTables);
3558
4468
  }
3559
4469
  build(pluginOptions) {
3560
4470
  return {
3561
4471
  all: async (query, options = {}) => {
3562
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
3563
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
3564
- return records.map((record) => {
3565
- const { table = "orphan" } = record.xata;
3566
- return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
3567
- });
4472
+ const { records, totalCount } = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
4473
+ return {
4474
+ totalCount,
4475
+ records: records.map((record) => {
4476
+ const { table = "orphan" } = record.xata;
4477
+ return { table, record: initObject(this.db, pluginOptions.tables, table, record, ["*"]) };
4478
+ })
4479
+ };
3568
4480
  },
3569
4481
  byTable: async (query, options = {}) => {
3570
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
3571
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
3572
- return records.reduce((acc, record) => {
4482
+ const { records: rawRecords, totalCount } = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
4483
+ const records = rawRecords.reduce((acc, record) => {
3573
4484
  const { table = "orphan" } = record.xata;
3574
4485
  const items = acc[table] ?? [];
3575
- const item = initObject(this.db, schemaTables, table, record, ["*"]);
4486
+ const item = initObject(this.db, pluginOptions.tables, table, record, ["*"]);
3576
4487
  return { ...acc, [table]: [...items, item] };
3577
4488
  }, {});
4489
+ return { totalCount, records };
3578
4490
  }
3579
4491
  };
3580
4492
  }
3581
4493
  }
3582
- _schemaTables = new WeakMap();
3583
4494
  _search = new WeakSet();
3584
4495
  search_fn = async function(query, options, pluginOptions) {
3585
4496
  const { tables, fuzziness, highlight, prefix, page } = options ?? {};
3586
- const { records } = await searchBranch({
4497
+ const { records, totalCount } = await searchBranch({
3587
4498
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4499
+ // @ts-expect-error Filter properties do not match inferred type
3588
4500
  body: { tables, query, fuzziness, prefix, highlight, page },
3589
4501
  ...pluginOptions
3590
4502
  });
3591
- return records;
3592
- };
3593
- _getSchemaTables = new WeakSet();
3594
- getSchemaTables_fn = async function(pluginOptions) {
3595
- if (__privateGet$1(this, _schemaTables))
3596
- return __privateGet$1(this, _schemaTables);
3597
- const { schema } = await getBranchDetails({
3598
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3599
- ...pluginOptions
3600
- });
3601
- __privateSet$1(this, _schemaTables, schema.tables);
3602
- return schema.tables;
4503
+ return { records, totalCount };
3603
4504
  };
3604
4505
 
4506
+ function escapeElement(elementRepresentation) {
4507
+ const escaped = elementRepresentation.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
4508
+ return '"' + escaped + '"';
4509
+ }
4510
+ function arrayString(val) {
4511
+ let result = "{";
4512
+ for (let i = 0; i < val.length; i++) {
4513
+ if (i > 0) {
4514
+ result = result + ",";
4515
+ }
4516
+ if (val[i] === null || typeof val[i] === "undefined") {
4517
+ result = result + "NULL";
4518
+ } else if (Array.isArray(val[i])) {
4519
+ result = result + arrayString(val[i]);
4520
+ } else if (val[i] instanceof Buffer) {
4521
+ result += "\\\\x" + val[i].toString("hex");
4522
+ } else {
4523
+ result += escapeElement(prepareValue(val[i]));
4524
+ }
4525
+ }
4526
+ result = result + "}";
4527
+ return result;
4528
+ }
4529
+ function prepareValue(value) {
4530
+ if (!isDefined(value))
4531
+ return null;
4532
+ if (value instanceof Date) {
4533
+ return value.toISOString();
4534
+ }
4535
+ if (Array.isArray(value)) {
4536
+ return arrayString(value);
4537
+ }
4538
+ if (isObject(value)) {
4539
+ return JSON.stringify(value);
4540
+ }
4541
+ try {
4542
+ return value.toString();
4543
+ } catch (e) {
4544
+ return value;
4545
+ }
4546
+ }
4547
+ function prepareParams(param1, param2) {
4548
+ if (isString(param1)) {
4549
+ return { statement: param1, params: param2?.map((value) => prepareValue(value)) };
4550
+ }
4551
+ if (isStringArray(param1)) {
4552
+ const statement = param1.reduce((acc, curr, index) => {
4553
+ return acc + curr + (index < (param2?.length ?? 0) ? "$" + (index + 1) : "");
4554
+ }, "");
4555
+ return { statement, params: param2?.map((value) => prepareValue(value)) };
4556
+ }
4557
+ if (isObject(param1)) {
4558
+ const { statement, params, consistency } = param1;
4559
+ return { statement, params: params?.map((value) => prepareValue(value)), consistency };
4560
+ }
4561
+ throw new Error("Invalid query");
4562
+ }
4563
+
4564
+ class SQLPlugin extends XataPlugin {
4565
+ build(pluginOptions) {
4566
+ return async (query, ...parameters) => {
4567
+ if (!isParamsObject(query) && (!isTemplateStringsArray(query) || !Array.isArray(parameters))) {
4568
+ throw new Error("Invalid usage of `xata.sql`. Please use it as a tagged template or with an object.");
4569
+ }
4570
+ const { statement, params, consistency } = prepareParams(query, parameters);
4571
+ const { records, warning, columns } = await sqlQuery({
4572
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4573
+ body: { statement, params, consistency },
4574
+ ...pluginOptions
4575
+ });
4576
+ return { records, warning, columns };
4577
+ };
4578
+ }
4579
+ }
4580
+ function isTemplateStringsArray(strings) {
4581
+ return Array.isArray(strings) && "raw" in strings && Array.isArray(strings.raw);
4582
+ }
4583
+ function isParamsObject(params) {
4584
+ return isObject(params) && "statement" in params;
4585
+ }
4586
+
3605
4587
  class TransactionPlugin extends XataPlugin {
3606
4588
  build(pluginOptions) {
3607
4589
  return {
@@ -3642,7 +4624,7 @@ var __privateMethod = (obj, member, method) => {
3642
4624
  const buildClient = (plugins) => {
3643
4625
  var _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _a;
3644
4626
  return _a = class {
3645
- constructor(options = {}, schemaTables) {
4627
+ constructor(options = {}, tables) {
3646
4628
  __privateAdd(this, _parseOptions);
3647
4629
  __privateAdd(this, _getFetchProps);
3648
4630
  __privateAdd(this, _options, void 0);
@@ -3651,14 +4633,20 @@ const buildClient = (plugins) => {
3651
4633
  const pluginOptions = {
3652
4634
  ...__privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
3653
4635
  cache: safeOptions.cache,
3654
- host: safeOptions.host
4636
+ host: safeOptions.host,
4637
+ tables
3655
4638
  };
3656
- const db = new SchemaPlugin(schemaTables).build(pluginOptions);
3657
- const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
4639
+ const db = new SchemaPlugin().build(pluginOptions);
4640
+ const search = new SearchPlugin(db).build(pluginOptions);
3658
4641
  const transactions = new TransactionPlugin().build(pluginOptions);
4642
+ const sql = new SQLPlugin().build(pluginOptions);
4643
+ const files = new FilesPlugin().build(pluginOptions);
4644
+ this.schema = { tables };
3659
4645
  this.db = db;
3660
4646
  this.search = search;
3661
4647
  this.transactions = transactions;
4648
+ this.sql = sql;
4649
+ this.files = files;
3662
4650
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
3663
4651
  if (namespace === void 0)
3664
4652
  continue;
@@ -3739,6 +4727,7 @@ const buildClient = (plugins) => {
3739
4727
  fetch,
3740
4728
  apiKey,
3741
4729
  apiUrl: "",
4730
+ // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
3742
4731
  workspacesApiUrl: (path, params) => {
3743
4732
  const hasBranch = params.dbBranchName ?? params.branch;
3744
4733
  const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branch}` : "");
@@ -3821,21 +4810,6 @@ const deserialize = (json) => {
3821
4810
  return defaultSerializer.fromJSON(json);
3822
4811
  };
3823
4812
 
3824
- function buildWorkerRunner(config) {
3825
- return function xataWorker(name, worker) {
3826
- return async (...args) => {
3827
- const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
3828
- const result = await fetch(url, {
3829
- method: "POST",
3830
- headers: { "Content-Type": "application/json" },
3831
- body: serialize({ args })
3832
- });
3833
- const text = await result.text();
3834
- return deserialize(text);
3835
- };
3836
- };
3837
- }
3838
-
3839
4813
  class XataError extends Error {
3840
4814
  constructor(message, status) {
3841
4815
  super(message);
@@ -3843,5 +4817,5 @@ class XataError extends Error {
3843
4817
  }
3844
4818
  }
3845
4819
 
3846
- export { BaseClient, FetcherError, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, Serializer, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, aggregateTable, applyBranchSchemaEdit, askTable, branchTransaction, buildClient, buildPreviewBranchName, buildProviderString, buildWorkerRunner, bulkInsertTableRecords, cancelWorkspaceMemberInvite, compareBranchSchemas, compareBranchWithUserSchema, compareMigrationRequest, contains, copyBranch, createBranch, createDatabase, createMigrationRequest, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteDatabaseGithubSettings, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, deserialize, endsWith, equals, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranch, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchSchemaHistory, getBranchStats, getColumn, getDatabaseGithubSettings, getDatabaseList, getDatabaseMetadata, getDatabaseURL, getGitBranchesMapping, getHostUrl, getMigrationRequest, getMigrationRequestIsMerged, getPreviewBranch, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, greaterEquals, greaterThan, greaterThanEquals, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isHostProviderAlias, isHostProviderBuilder, isIdentifiable, isNot, isXataRecord, le, lessEquals, lessThan, lessThanEquals, listMigrationRequestsCommits, listRegions, lt, lte, mergeMigrationRequest, notExists, operationsByTag, parseProviderString, parseWorkspacesUrlParts, pattern, previewBranchSchemaEdit, pushBranchMigrations, queryMigrationRequests, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, serialize, setTableSchema, sqlQuery, startsWith, summarizeTable, updateBranchMetadata, updateBranchSchema, updateColumn, updateDatabaseGithubSettings, updateDatabaseMetadata, updateMigrationRequest, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID, vectorSearchTable };
4820
+ export { BaseClient, FetcherError, FilesPlugin, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, RecordColumnTypes, Repository, RestRepository, SQLPlugin, SchemaPlugin, SearchPlugin, Serializer, SimpleCache, TransactionPlugin, XataApiClient, XataApiPlugin, XataError, XataFile, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, aggregateTable, applyBranchSchemaEdit, applyMigration, askTable, askTableSession, branchTransaction, buildClient, buildPreviewBranchName, buildProviderString, bulkInsertTableRecords, cancelWorkspaceMemberInvite, compareBranchSchemas, compareBranchWithUserSchema, compareMigrationRequest, contains, copyBranch, createBranch, createCluster, createDatabase, createMigrationRequest, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteDatabaseGithubSettings, deleteFile, deleteFileItem, deleteOAuthAccessToken, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteUserOAuthClient, deleteWorkspace, deserialize, endsWith, equals, executeBranchMigrationPlan, exists, fileAccess, fileUpload, ge, getAPIKey, getAuthorizationCode, getBranch, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchSchemaHistory, getBranchStats, getCluster, getColumn, getDatabaseGithubSettings, getDatabaseList, getDatabaseMetadata, getDatabaseURL, getFile, getFileItem, getGitBranchesMapping, getHostUrl, getMigrationRequest, getMigrationRequestIsMerged, getPreviewBranch, getRecord, getSchema, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getUserOAuthAccessTokens, getUserOAuthClients, getWorkspace, getWorkspaceMembersList, getWorkspacesList, grantAuthorizationCode, greaterEquals, greaterThan, greaterThanEquals, gt, gte, iContains, iPattern, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isHostProviderAlias, isHostProviderBuilder, isIdentifiable, isNot, isValidExpandedColumn, isValidSelectableColumns, isXataRecord, le, lessEquals, lessThan, lessThanEquals, listClusters, listMigrationRequestsCommits, listRegions, lt, lte, mergeMigrationRequest, notExists, operationsByTag, parseProviderString, parseWorkspacesUrlParts, pattern, pgRollJobStatus, pgRollMigrationHistory, pgRollStatus, previewBranchSchemaEdit, pushBranchMigrations, putFile, putFileItem, queryMigrationRequests, queryTable, removeGitBranchesEntry, removeWorkspaceMember, renameDatabase, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, serialize, setTableSchema, sqlQuery, startsWith, summarizeTable, transformImage, updateBranchMetadata, updateBranchSchema, updateCluster, updateColumn, updateDatabaseGithubSettings, updateDatabaseMetadata, updateMigrationRequest, updateOAuthAccessToken, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID, vectorSearchTable };
3847
4821
  //# sourceMappingURL=index.mjs.map