@xata.io/client 0.0.0-alpha.vf286f7d → 0.0.0-alpha.vf2894b5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -20,7 +20,8 @@ const TraceAttributes = {
20
20
  HTTP_METHOD: "http.method",
21
21
  HTTP_URL: "http.url",
22
22
  HTTP_ROUTE: "http.route",
23
- HTTP_TARGET: "http.target"
23
+ HTTP_TARGET: "http.target",
24
+ CLOUDFLARE_RAY_ID: "cf.ray"
24
25
  };
25
26
 
26
27
  function notEmpty(value) {
@@ -29,8 +30,18 @@ function notEmpty(value) {
29
30
  function compact(arr) {
30
31
  return arr.filter(notEmpty);
31
32
  }
33
+ function compactObject(obj) {
34
+ return Object.fromEntries(Object.entries(obj).filter(([, value]) => notEmpty(value)));
35
+ }
36
+ function isBlob(value) {
37
+ try {
38
+ return value instanceof Blob;
39
+ } catch (error) {
40
+ return false;
41
+ }
42
+ }
32
43
  function isObject(value) {
33
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
44
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date) && !isBlob(value);
34
45
  }
35
46
  function isDefined(value) {
36
47
  return value !== null && value !== void 0;
@@ -85,6 +96,27 @@ function chunk(array, chunkSize) {
85
96
  async function timeout(ms) {
86
97
  return new Promise((resolve) => setTimeout(resolve, ms));
87
98
  }
99
+ function timeoutWithCancel(ms) {
100
+ let timeoutId;
101
+ const promise = new Promise((resolve) => {
102
+ timeoutId = setTimeout(() => {
103
+ resolve();
104
+ }, ms);
105
+ });
106
+ return {
107
+ cancel: () => clearTimeout(timeoutId),
108
+ promise
109
+ };
110
+ }
111
+ function promiseMap(inputValues, mapper) {
112
+ const reducer = (acc$, inputValue) => acc$.then(
113
+ (acc) => mapper(inputValue).then((result) => {
114
+ acc.push(result);
115
+ return acc;
116
+ })
117
+ );
118
+ return inputValues.reduce(reducer, Promise.resolve([]));
119
+ }
88
120
 
89
121
  function getEnvironment() {
90
122
  try {
@@ -184,7 +216,7 @@ function getAPIKey() {
184
216
  function getBranch() {
185
217
  try {
186
218
  const { branch } = getEnvironment();
187
- return branch ?? "main";
219
+ return branch;
188
220
  } catch (err) {
189
221
  return void 0;
190
222
  }
@@ -235,13 +267,13 @@ var __privateMethod$4 = (obj, member, method) => {
235
267
  return method;
236
268
  };
237
269
  var _fetch, _queue, _concurrency, _enqueue, enqueue_fn;
270
+ const REQUEST_TIMEOUT = 5 * 60 * 1e3;
238
271
  function getFetchImplementation(userFetch) {
239
272
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
240
- const fetchImpl = userFetch ?? globalFetch;
273
+ const globalThisFetch = typeof globalThis !== "undefined" ? globalThis.fetch : void 0;
274
+ const fetchImpl = userFetch ?? globalFetch ?? globalThisFetch;
241
275
  if (!fetchImpl) {
242
- throw new Error(
243
- `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
244
- );
276
+ throw new Error(`Couldn't find a global \`fetch\`. Pass a fetch implementation explicitly.`);
245
277
  }
246
278
  return fetchImpl;
247
279
  }
@@ -267,9 +299,13 @@ class ApiRequestPool {
267
299
  }
268
300
  request(url, options) {
269
301
  const start = /* @__PURE__ */ new Date();
270
- const fetch2 = this.getFetch();
302
+ const fetchImpl = this.getFetch();
271
303
  const runRequest = async (stalled = false) => {
272
- const response = await fetch2(url, options);
304
+ const { promise, cancel } = timeoutWithCancel(REQUEST_TIMEOUT);
305
+ const response = await Promise.race([fetchImpl(url, options), promise.then(() => null)]).finally(cancel);
306
+ if (!response) {
307
+ throw new Error("Request timed out");
308
+ }
273
309
  if (response.status === 429) {
274
310
  const rateLimitReset = parseNumber(response.headers?.get("x-ratelimit-reset")) ?? 1;
275
311
  await timeout(rateLimitReset * 1e3);
@@ -277,7 +313,7 @@ class ApiRequestPool {
277
313
  }
278
314
  if (stalled) {
279
315
  const stalledTime = (/* @__PURE__ */ new Date()).getTime() - start.getTime();
280
- console.warn(`A request to Xata hit your workspace limits, was retried and stalled for ${stalledTime}ms`);
316
+ console.warn(`A request to Xata hit branch rate limits, was retried and stalled for ${stalledTime}ms`);
281
317
  }
282
318
  return response;
283
319
  };
@@ -492,7 +528,7 @@ function defaultOnOpen(response) {
492
528
  }
493
529
  }
494
530
 
495
- const VERSION = "0.24.0";
531
+ const VERSION = "0.26.6";
496
532
 
497
533
  class ErrorWithCause extends Error {
498
534
  constructor(message, options) {
@@ -568,6 +604,18 @@ function hostHeader(url) {
568
604
  const { groups } = pattern.exec(url) ?? {};
569
605
  return groups?.host ? { Host: groups.host } : {};
570
606
  }
607
+ async function parseBody(body, headers) {
608
+ if (!isDefined(body))
609
+ return void 0;
610
+ if (isBlob(body) || typeof body.text === "function") {
611
+ return body;
612
+ }
613
+ const { "Content-Type": contentType } = headers ?? {};
614
+ if (String(contentType).toLowerCase() === "application/json" && isObject(body)) {
615
+ return JSON.stringify(body);
616
+ }
617
+ return body;
618
+ }
571
619
  const defaultClientID = generateUUID();
572
620
  async function fetch$1({
573
621
  url: path,
@@ -587,7 +635,8 @@ async function fetch$1({
587
635
  sessionID,
588
636
  clientName,
589
637
  xataAgentExtra,
590
- fetchOptions = {}
638
+ fetchOptions = {},
639
+ rawResponse = false
591
640
  }) {
592
641
  pool.setFetch(fetch2);
593
642
  return await trace(
@@ -606,7 +655,7 @@ async function fetch$1({
606
655
  isDefined(clientName) ? ["service", clientName] : void 0,
607
656
  ...Object.entries(xataAgentExtra ?? {})
608
657
  ]).map(([key, value]) => `${key}=${value}`).join("; ");
609
- const headers = {
658
+ const headers = compactObject({
610
659
  "Accept-Encoding": "identity",
611
660
  "Content-Type": "application/json",
612
661
  "X-Xata-Client-ID": clientID ?? defaultClientID,
@@ -615,11 +664,11 @@ async function fetch$1({
615
664
  ...customHeaders,
616
665
  ...hostHeader(fullUrl),
617
666
  Authorization: `Bearer ${apiKey}`
618
- };
667
+ });
619
668
  const response = await pool.request(url, {
620
669
  ...fetchOptions,
621
670
  method: method.toUpperCase(),
622
- body: body ? JSON.stringify(body) : void 0,
671
+ body: await parseBody(body, headers),
623
672
  headers,
624
673
  signal
625
674
  });
@@ -630,8 +679,12 @@ async function fetch$1({
630
679
  [TraceAttributes.HTTP_REQUEST_ID]: requestId,
631
680
  [TraceAttributes.HTTP_STATUS_CODE]: response.status,
632
681
  [TraceAttributes.HTTP_HOST]: host,
633
- [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
682
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", ""),
683
+ [TraceAttributes.CLOUDFLARE_RAY_ID]: response.headers?.get("cf-ray") ?? void 0
634
684
  });
685
+ const message = response.headers?.get("x-xata-message");
686
+ if (message)
687
+ console.warn(message);
635
688
  if (response.status === 204) {
636
689
  return {};
637
690
  }
@@ -639,7 +692,7 @@ async function fetch$1({
639
692
  throw new FetcherError(response.status, "Rate limit exceeded", requestId);
640
693
  }
641
694
  try {
642
- const jsonResponse = await response.json();
695
+ const jsonResponse = rawResponse ? await response.blob() : await response.json();
643
696
  if (response.ok) {
644
697
  return jsonResponse;
645
698
  }
@@ -899,12 +952,6 @@ const searchTable = (variables, signal) => dataPlaneFetch({
899
952
  ...variables,
900
953
  signal
901
954
  });
902
- const sqlQuery = (variables, signal) => dataPlaneFetch({
903
- url: "/db/{dbBranchName}/sql",
904
- method: "post",
905
- ...variables,
906
- signal
907
- });
908
955
  const vectorSearchTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/vectorSearch", method: "post", ...variables, signal });
909
956
  const askTable = (variables, signal) => dataPlaneFetch({
910
957
  url: "/db/{dbBranchName}/tables/{tableName}/ask",
@@ -912,6 +959,7 @@ const askTable = (variables, signal) => dataPlaneFetch({
912
959
  ...variables,
913
960
  signal
914
961
  });
962
+ const askTableSession = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}", method: "post", ...variables, signal });
915
963
  const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
916
964
  const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
917
965
  const fileAccess = (variables, signal) => dataPlaneFetch({
@@ -920,6 +968,12 @@ const fileAccess = (variables, signal) => dataPlaneFetch({
920
968
  ...variables,
921
969
  signal
922
970
  });
971
+ const sqlQuery = (variables, signal) => dataPlaneFetch({
972
+ url: "/db/{dbBranchName}/sql",
973
+ method: "post",
974
+ ...variables,
975
+ signal
976
+ });
923
977
  const operationsByTag$2 = {
924
978
  branch: {
925
979
  getBranchList,
@@ -984,16 +1038,19 @@ const operationsByTag$2 = {
984
1038
  queryTable,
985
1039
  searchBranch,
986
1040
  searchTable,
987
- sqlQuery,
988
1041
  vectorSearchTable,
989
1042
  askTable,
1043
+ askTableSession,
990
1044
  summarizeTable,
991
1045
  aggregateTable
992
- }
1046
+ },
1047
+ sql: { sqlQuery }
993
1048
  };
994
1049
 
995
1050
  const controlPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "controlPlane" });
996
1051
 
1052
+ const getAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "get", ...variables, signal });
1053
+ const grantAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "post", ...variables, signal });
997
1054
  const getUser = (variables, signal) => controlPlaneFetch({
998
1055
  url: "/user",
999
1056
  method: "get",
@@ -1030,6 +1087,31 @@ const deleteUserAPIKey = (variables, signal) => controlPlaneFetch({
1030
1087
  ...variables,
1031
1088
  signal
1032
1089
  });
1090
+ const getUserOAuthClients = (variables, signal) => controlPlaneFetch({
1091
+ url: "/user/oauth/clients",
1092
+ method: "get",
1093
+ ...variables,
1094
+ signal
1095
+ });
1096
+ const deleteUserOAuthClient = (variables, signal) => controlPlaneFetch({
1097
+ url: "/user/oauth/clients/{clientId}",
1098
+ method: "delete",
1099
+ ...variables,
1100
+ signal
1101
+ });
1102
+ const getUserOAuthAccessTokens = (variables, signal) => controlPlaneFetch({
1103
+ url: "/user/oauth/tokens",
1104
+ method: "get",
1105
+ ...variables,
1106
+ signal
1107
+ });
1108
+ const deleteOAuthAccessToken = (variables, signal) => controlPlaneFetch({
1109
+ url: "/user/oauth/tokens/{token}",
1110
+ method: "delete",
1111
+ ...variables,
1112
+ signal
1113
+ });
1114
+ const updateOAuthAccessToken = (variables, signal) => controlPlaneFetch({ url: "/user/oauth/tokens/{token}", method: "patch", ...variables, signal });
1033
1115
  const getWorkspacesList = (variables, signal) => controlPlaneFetch({
1034
1116
  url: "/workspaces",
1035
1117
  method: "get",
@@ -1073,6 +1155,20 @@ const updateWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ u
1073
1155
  const cancelWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "delete", ...variables, signal });
1074
1156
  const acceptWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept", method: "post", ...variables, signal });
1075
1157
  const resendWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}/resend", method: "post", ...variables, signal });
1158
+ const listClusters = (variables, signal) => controlPlaneFetch({
1159
+ url: "/workspaces/{workspaceId}/clusters",
1160
+ method: "get",
1161
+ ...variables,
1162
+ signal
1163
+ });
1164
+ const createCluster = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/clusters", method: "post", ...variables, signal });
1165
+ const getCluster = (variables, signal) => controlPlaneFetch({
1166
+ url: "/workspaces/{workspaceId}/clusters/{clusterId}",
1167
+ method: "get",
1168
+ ...variables,
1169
+ signal
1170
+ });
1171
+ const updateCluster = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/clusters/{clusterId}", method: "patch", ...variables, signal });
1076
1172
  const getDatabaseList = (variables, signal) => controlPlaneFetch({
1077
1173
  url: "/workspaces/{workspaceId}/dbs",
1078
1174
  method: "get",
@@ -1099,6 +1195,15 @@ const listRegions = (variables, signal) => controlPlaneFetch({
1099
1195
  signal
1100
1196
  });
1101
1197
  const operationsByTag$1 = {
1198
+ oAuth: {
1199
+ getAuthorizationCode,
1200
+ grantAuthorizationCode,
1201
+ getUserOAuthClients,
1202
+ deleteUserOAuthClient,
1203
+ getUserOAuthAccessTokens,
1204
+ deleteOAuthAccessToken,
1205
+ updateOAuthAccessToken
1206
+ },
1102
1207
  users: { getUser, updateUser, deleteUser },
1103
1208
  authentication: { getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
1104
1209
  workspaces: {
@@ -1118,6 +1223,7 @@ const operationsByTag$1 = {
1118
1223
  acceptWorkspaceMemberInvite,
1119
1224
  resendWorkspaceMemberInvite
1120
1225
  },
1226
+ xbcontrolOther: { listClusters, createCluster, getCluster, updateCluster },
1121
1227
  databases: {
1122
1228
  getDatabaseList,
1123
1229
  createDatabase,
@@ -2111,6 +2217,21 @@ class SearchAndFilterApi {
2111
2217
  ...this.extraProps
2112
2218
  });
2113
2219
  }
2220
+ askTableSession({
2221
+ workspace,
2222
+ region,
2223
+ database,
2224
+ branch,
2225
+ table,
2226
+ sessionId,
2227
+ message
2228
+ }) {
2229
+ return operationsByTag.searchAndFilter.askTableSession({
2230
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, sessionId },
2231
+ body: { message },
2232
+ ...this.extraProps
2233
+ });
2234
+ }
2114
2235
  summarizeTable({
2115
2236
  workspace,
2116
2237
  region,
@@ -2402,11 +2523,13 @@ class DatabaseApi {
2402
2523
  createDatabase({
2403
2524
  workspace,
2404
2525
  database,
2405
- data
2526
+ data,
2527
+ headers
2406
2528
  }) {
2407
2529
  return operationsByTag.databases.createDatabase({
2408
2530
  pathParams: { workspaceId: workspace, dbName: database },
2409
2531
  body: data,
2532
+ headers,
2410
2533
  ...this.extraProps
2411
2534
  });
2412
2535
  }
@@ -2496,11 +2619,261 @@ class XataApiPlugin {
2496
2619
  class XataPlugin {
2497
2620
  }
2498
2621
 
2622
+ class FilesPlugin extends XataPlugin {
2623
+ build(pluginOptions) {
2624
+ return {
2625
+ download: async (location) => {
2626
+ const { table, record, column, fileId = "" } = location ?? {};
2627
+ return await getFileItem({
2628
+ pathParams: {
2629
+ workspace: "{workspaceId}",
2630
+ dbBranchName: "{dbBranch}",
2631
+ region: "{region}",
2632
+ tableName: table ?? "",
2633
+ recordId: record ?? "",
2634
+ columnName: column ?? "",
2635
+ fileId
2636
+ },
2637
+ ...pluginOptions,
2638
+ rawResponse: true
2639
+ });
2640
+ },
2641
+ upload: async (location, file) => {
2642
+ const { table, record, column, fileId = "" } = location ?? {};
2643
+ const contentType = getContentType(file);
2644
+ return await putFileItem({
2645
+ ...pluginOptions,
2646
+ pathParams: {
2647
+ workspace: "{workspaceId}",
2648
+ dbBranchName: "{dbBranch}",
2649
+ region: "{region}",
2650
+ tableName: table ?? "",
2651
+ recordId: record ?? "",
2652
+ columnName: column ?? "",
2653
+ fileId
2654
+ },
2655
+ body: file,
2656
+ headers: { "Content-Type": contentType }
2657
+ });
2658
+ },
2659
+ delete: async (location) => {
2660
+ const { table, record, column, fileId = "" } = location ?? {};
2661
+ return await deleteFileItem({
2662
+ pathParams: {
2663
+ workspace: "{workspaceId}",
2664
+ dbBranchName: "{dbBranch}",
2665
+ region: "{region}",
2666
+ tableName: table ?? "",
2667
+ recordId: record ?? "",
2668
+ columnName: column ?? "",
2669
+ fileId
2670
+ },
2671
+ ...pluginOptions
2672
+ });
2673
+ }
2674
+ };
2675
+ }
2676
+ }
2677
+ function getContentType(file) {
2678
+ if (typeof file === "string") {
2679
+ return "text/plain";
2680
+ }
2681
+ if (isBlob(file)) {
2682
+ return file.type;
2683
+ }
2684
+ try {
2685
+ return file.type;
2686
+ } catch (e) {
2687
+ }
2688
+ return "application/octet-stream";
2689
+ }
2690
+
2691
+ function buildTransformString(transformations) {
2692
+ return transformations.flatMap(
2693
+ (t) => Object.entries(t).map(([key, value]) => {
2694
+ if (key === "trim") {
2695
+ const { left = 0, top = 0, right = 0, bottom = 0 } = value;
2696
+ return `${key}=${[top, right, bottom, left].join(";")}`;
2697
+ }
2698
+ if (key === "gravity" && typeof value === "object") {
2699
+ const { x = 0.5, y = 0.5 } = value;
2700
+ return `${key}=${[x, y].join("x")}`;
2701
+ }
2702
+ return `${key}=${value}`;
2703
+ })
2704
+ ).join(",");
2705
+ }
2706
+ function transformImage(url, ...transformations) {
2707
+ if (!isDefined(url))
2708
+ return void 0;
2709
+ const newTransformations = buildTransformString(transformations);
2710
+ const { hostname, pathname, search } = new URL(url);
2711
+ const pathParts = pathname.split("/");
2712
+ const transformIndex = pathParts.findIndex((part) => part === "transform");
2713
+ const removedItems = transformIndex >= 0 ? pathParts.splice(transformIndex, 2) : [];
2714
+ const transform = `/transform/${[removedItems[1], newTransformations].filter(isDefined).join(",")}`;
2715
+ const path = pathParts.join("/");
2716
+ return `https://${hostname}${transform}${path}${search}`;
2717
+ }
2718
+
2719
+ class XataFile {
2720
+ constructor(file) {
2721
+ this.id = file.id;
2722
+ this.name = file.name || "";
2723
+ this.mediaType = file.mediaType || "application/octet-stream";
2724
+ this.base64Content = file.base64Content;
2725
+ this.enablePublicUrl = file.enablePublicUrl ?? false;
2726
+ this.signedUrlTimeout = file.signedUrlTimeout ?? 300;
2727
+ this.size = file.size ?? 0;
2728
+ this.version = file.version ?? 1;
2729
+ this.url = file.url || "";
2730
+ this.signedUrl = file.signedUrl;
2731
+ this.attributes = file.attributes || {};
2732
+ }
2733
+ static fromBuffer(buffer, options = {}) {
2734
+ const base64Content = buffer.toString("base64");
2735
+ return new XataFile({ ...options, base64Content });
2736
+ }
2737
+ toBuffer() {
2738
+ if (!this.base64Content) {
2739
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2740
+ }
2741
+ return Buffer.from(this.base64Content, "base64");
2742
+ }
2743
+ static fromArrayBuffer(arrayBuffer, options = {}) {
2744
+ const uint8Array = new Uint8Array(arrayBuffer);
2745
+ return this.fromUint8Array(uint8Array, options);
2746
+ }
2747
+ toArrayBuffer() {
2748
+ if (!this.base64Content) {
2749
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2750
+ }
2751
+ const binary = atob(this.base64Content);
2752
+ return new ArrayBuffer(binary.length);
2753
+ }
2754
+ static fromUint8Array(uint8Array, options = {}) {
2755
+ let binary = "";
2756
+ for (let i = 0; i < uint8Array.byteLength; i++) {
2757
+ binary += String.fromCharCode(uint8Array[i]);
2758
+ }
2759
+ const base64Content = btoa(binary);
2760
+ return new XataFile({ ...options, base64Content });
2761
+ }
2762
+ toUint8Array() {
2763
+ if (!this.base64Content) {
2764
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2765
+ }
2766
+ const binary = atob(this.base64Content);
2767
+ const uint8Array = new Uint8Array(binary.length);
2768
+ for (let i = 0; i < binary.length; i++) {
2769
+ uint8Array[i] = binary.charCodeAt(i);
2770
+ }
2771
+ return uint8Array;
2772
+ }
2773
+ static async fromBlob(file, options = {}) {
2774
+ const name = options.name ?? file.name;
2775
+ const mediaType = file.type;
2776
+ const arrayBuffer = await file.arrayBuffer();
2777
+ return this.fromArrayBuffer(arrayBuffer, { ...options, name, mediaType });
2778
+ }
2779
+ toBlob() {
2780
+ if (!this.base64Content) {
2781
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2782
+ }
2783
+ const binary = atob(this.base64Content);
2784
+ const uint8Array = new Uint8Array(binary.length);
2785
+ for (let i = 0; i < binary.length; i++) {
2786
+ uint8Array[i] = binary.charCodeAt(i);
2787
+ }
2788
+ return new Blob([uint8Array], { type: this.mediaType });
2789
+ }
2790
+ static fromString(string, options = {}) {
2791
+ const base64Content = btoa(string);
2792
+ return new XataFile({ ...options, base64Content });
2793
+ }
2794
+ toString() {
2795
+ if (!this.base64Content) {
2796
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2797
+ }
2798
+ return atob(this.base64Content);
2799
+ }
2800
+ static fromBase64(base64Content, options = {}) {
2801
+ return new XataFile({ ...options, base64Content });
2802
+ }
2803
+ toBase64() {
2804
+ if (!this.base64Content) {
2805
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2806
+ }
2807
+ return this.base64Content;
2808
+ }
2809
+ transform(...options) {
2810
+ return {
2811
+ url: transformImage(this.url, ...options),
2812
+ signedUrl: transformImage(this.signedUrl, ...options),
2813
+ metadataUrl: transformImage(this.url, ...options, { format: "json" }),
2814
+ metadataSignedUrl: transformImage(this.signedUrl, ...options, { format: "json" })
2815
+ };
2816
+ }
2817
+ }
2818
+ const parseInputFileEntry = async (entry) => {
2819
+ if (!isDefined(entry))
2820
+ return null;
2821
+ const { id, name, mediaType, base64Content, enablePublicUrl, signedUrlTimeout } = await entry;
2822
+ return compactObject({
2823
+ id,
2824
+ // Name cannot be an empty string in our API
2825
+ name: name ? name : void 0,
2826
+ mediaType,
2827
+ base64Content,
2828
+ enablePublicUrl,
2829
+ signedUrlTimeout
2830
+ });
2831
+ };
2832
+
2499
2833
  function cleanFilter(filter) {
2500
- if (!filter)
2834
+ if (!isDefined(filter))
2501
2835
  return void 0;
2502
- const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
2503
- return values.length > 0 ? filter : void 0;
2836
+ if (!isObject(filter))
2837
+ return filter;
2838
+ const values = Object.fromEntries(
2839
+ Object.entries(filter).reduce((acc, [key, value]) => {
2840
+ if (!isDefined(value))
2841
+ return acc;
2842
+ if (Array.isArray(value)) {
2843
+ const clean = value.map((item) => cleanFilter(item)).filter((item) => isDefined(item));
2844
+ if (clean.length === 0)
2845
+ return acc;
2846
+ return [...acc, [key, clean]];
2847
+ }
2848
+ if (isObject(value)) {
2849
+ const clean = cleanFilter(value);
2850
+ if (!isDefined(clean))
2851
+ return acc;
2852
+ return [...acc, [key, clean]];
2853
+ }
2854
+ return [...acc, [key, value]];
2855
+ }, [])
2856
+ );
2857
+ return Object.keys(values).length > 0 ? values : void 0;
2858
+ }
2859
+
2860
+ function stringifyJson(value) {
2861
+ if (!isDefined(value))
2862
+ return value;
2863
+ if (isString(value))
2864
+ return value;
2865
+ try {
2866
+ return JSON.stringify(value);
2867
+ } catch (e) {
2868
+ return value;
2869
+ }
2870
+ }
2871
+ function parseJson(value) {
2872
+ try {
2873
+ return JSON.parse(value);
2874
+ } catch (e) {
2875
+ return value;
2876
+ }
2504
2877
  }
2505
2878
 
2506
2879
  var __accessCheck$6 = (obj, member, msg) => {
@@ -2574,14 +2947,14 @@ class Page {
2574
2947
  }
2575
2948
  }
2576
2949
  _query = new WeakMap();
2577
- const PAGINATION_MAX_SIZE = 200;
2950
+ const PAGINATION_MAX_SIZE = 1e3;
2578
2951
  const PAGINATION_DEFAULT_SIZE = 20;
2579
- const PAGINATION_MAX_OFFSET = 800;
2952
+ const PAGINATION_MAX_OFFSET = 49e3;
2580
2953
  const PAGINATION_DEFAULT_OFFSET = 0;
2581
2954
  function isCursorPaginationOptions(options) {
2582
2955
  return isDefined(options) && (isDefined(options.start) || isDefined(options.end) || isDefined(options.after) || isDefined(options.before));
2583
2956
  }
2584
- const _RecordArray = class extends Array {
2957
+ const _RecordArray = class _RecordArray extends Array {
2585
2958
  constructor(...args) {
2586
2959
  super(..._RecordArray.parseConstructorParams(...args));
2587
2960
  __privateAdd$6(this, _page, void 0);
@@ -2652,8 +3025,8 @@ const _RecordArray = class extends Array {
2652
3025
  return __privateGet$6(this, _page).meta.page.more;
2653
3026
  }
2654
3027
  };
2655
- let RecordArray = _RecordArray;
2656
3028
  _page = new WeakMap();
3029
+ let RecordArray = _RecordArray;
2657
3030
 
2658
3031
  var __accessCheck$5 = (obj, member, msg) => {
2659
3032
  if (!member.has(obj))
@@ -2678,7 +3051,7 @@ var __privateMethod$3 = (obj, member, method) => {
2678
3051
  return method;
2679
3052
  };
2680
3053
  var _table$1, _repository, _data, _cleanFilterConstraint, cleanFilterConstraint_fn;
2681
- const _Query = class {
3054
+ const _Query = class _Query {
2682
3055
  constructor(repository, table, data, rawParent) {
2683
3056
  __privateAdd$5(this, _cleanFilterConstraint);
2684
3057
  __privateAdd$5(this, _table$1, void 0);
@@ -2906,7 +3279,6 @@ const _Query = class {
2906
3279
  return this.meta.page.more;
2907
3280
  }
2908
3281
  };
2909
- let Query = _Query;
2910
3282
  _table$1 = new WeakMap();
2911
3283
  _repository = new WeakMap();
2912
3284
  _data = new WeakMap();
@@ -2921,6 +3293,7 @@ cleanFilterConstraint_fn = function(column, value) {
2921
3293
  }
2922
3294
  return value;
2923
3295
  };
3296
+ let Query = _Query;
2924
3297
  function cleanParent(data, parent) {
2925
3298
  if (isCursorPaginationOptions(data.pagination)) {
2926
3299
  return { ...parent, sort: void 0, filter: void 0 };
@@ -2928,6 +3301,22 @@ function cleanParent(data, parent) {
2928
3301
  return parent;
2929
3302
  }
2930
3303
 
3304
+ const RecordColumnTypes = [
3305
+ "bool",
3306
+ "int",
3307
+ "float",
3308
+ "string",
3309
+ "text",
3310
+ "email",
3311
+ "multiple",
3312
+ "link",
3313
+ "object",
3314
+ "datetime",
3315
+ "vector",
3316
+ "file[]",
3317
+ "file",
3318
+ "json"
3319
+ ];
2931
3320
  function isIdentifiable(x) {
2932
3321
  return isObject(x) && isString(x?.id);
2933
3322
  }
@@ -2937,6 +3326,24 @@ function isXataRecord(x) {
2937
3326
  return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
2938
3327
  }
2939
3328
 
3329
+ function isValidExpandedColumn(column) {
3330
+ return isObject(column) && isString(column.name);
3331
+ }
3332
+ function isValidSelectableColumns(columns) {
3333
+ if (!Array.isArray(columns)) {
3334
+ return false;
3335
+ }
3336
+ return columns.every((column) => {
3337
+ if (typeof column === "string") {
3338
+ return true;
3339
+ }
3340
+ if (typeof column === "object") {
3341
+ return isValidExpandedColumn(column);
3342
+ }
3343
+ return false;
3344
+ });
3345
+ }
3346
+
2940
3347
  function isSortFilterString(value) {
2941
3348
  return isString(value);
2942
3349
  }
@@ -2986,7 +3393,7 @@ var __privateMethod$2 = (obj, member, method) => {
2986
3393
  __accessCheck$4(obj, member, "access private method");
2987
3394
  return method;
2988
3395
  };
2989
- 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;
3396
+ var _table, _getFetchProps, _db, _cache, _schemaTables$2, _trace, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _insertRecords, insertRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _updateRecords, updateRecords_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _deleteRecords, deleteRecords_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaTables$1, getSchemaTables_fn$1, _transformObjectToApi, transformObjectToApi_fn;
2990
3397
  const BULK_OPERATION_MAX_SIZE = 1e3;
2991
3398
  class Repository extends Query {
2992
3399
  }
@@ -3008,6 +3415,7 @@ class RestRepository extends Query {
3008
3415
  __privateAdd$4(this, _setCacheQuery);
3009
3416
  __privateAdd$4(this, _getCacheQuery);
3010
3417
  __privateAdd$4(this, _getSchemaTables$1);
3418
+ __privateAdd$4(this, _transformObjectToApi);
3011
3419
  __privateAdd$4(this, _table, void 0);
3012
3420
  __privateAdd$4(this, _getFetchProps, void 0);
3013
3421
  __privateAdd$4(this, _db, void 0);
@@ -3036,24 +3444,24 @@ class RestRepository extends Query {
3036
3444
  if (a.length === 0)
3037
3445
  return [];
3038
3446
  const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: true });
3039
- const columns = isStringArray(b) ? b : ["*"];
3447
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3040
3448
  const result = await this.read(ids, columns);
3041
3449
  return result;
3042
3450
  }
3043
3451
  if (isString(a) && isObject(b)) {
3044
3452
  if (a === "")
3045
3453
  throw new Error("The id can't be empty");
3046
- const columns = isStringArray(c) ? c : void 0;
3454
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3047
3455
  return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
3048
3456
  }
3049
3457
  if (isObject(a) && isString(a.id)) {
3050
3458
  if (a.id === "")
3051
3459
  throw new Error("The id can't be empty");
3052
- const columns = isStringArray(b) ? b : void 0;
3460
+ const columns = isValidSelectableColumns(b) ? b : void 0;
3053
3461
  return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
3054
3462
  }
3055
3463
  if (isObject(a)) {
3056
- const columns = isStringArray(b) ? b : void 0;
3464
+ const columns = isValidSelectableColumns(b) ? b : void 0;
3057
3465
  return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
3058
3466
  }
3059
3467
  throw new Error("Invalid arguments for create method");
@@ -3061,7 +3469,7 @@ class RestRepository extends Query {
3061
3469
  }
3062
3470
  async read(a, b) {
3063
3471
  return __privateGet$4(this, _trace).call(this, "read", async () => {
3064
- const columns = isStringArray(b) ? b : ["*"];
3472
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3065
3473
  if (Array.isArray(a)) {
3066
3474
  if (a.length === 0)
3067
3475
  return [];
@@ -3088,7 +3496,13 @@ class RestRepository extends Query {
3088
3496
  ...__privateGet$4(this, _getFetchProps).call(this)
3089
3497
  });
3090
3498
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3091
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
3499
+ return initObject(
3500
+ __privateGet$4(this, _db),
3501
+ schemaTables,
3502
+ __privateGet$4(this, _table),
3503
+ response,
3504
+ columns
3505
+ );
3092
3506
  } catch (e) {
3093
3507
  if (isObject(e) && e.status === 404) {
3094
3508
  return null;
@@ -3130,17 +3544,17 @@ class RestRepository extends Query {
3130
3544
  ifVersion,
3131
3545
  upsert: false
3132
3546
  });
3133
- const columns = isStringArray(b) ? b : ["*"];
3547
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3134
3548
  const result = await this.read(a, columns);
3135
3549
  return result;
3136
3550
  }
3137
3551
  try {
3138
3552
  if (isString(a) && isObject(b)) {
3139
- const columns = isStringArray(c) ? c : void 0;
3553
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3140
3554
  return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3141
3555
  }
3142
3556
  if (isObject(a) && isString(a.id)) {
3143
- const columns = isStringArray(b) ? b : void 0;
3557
+ const columns = isValidSelectableColumns(b) ? b : void 0;
3144
3558
  return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3145
3559
  }
3146
3560
  } catch (error) {
@@ -3180,17 +3594,27 @@ class RestRepository extends Query {
3180
3594
  ifVersion,
3181
3595
  upsert: true
3182
3596
  });
3183
- const columns = isStringArray(b) ? b : ["*"];
3597
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3184
3598
  const result = await this.read(a, columns);
3185
3599
  return result;
3186
3600
  }
3187
3601
  if (isString(a) && isObject(b)) {
3188
- const columns = isStringArray(c) ? c : void 0;
3189
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3602
+ if (a === "")
3603
+ throw new Error("The id can't be empty");
3604
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3605
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3190
3606
  }
3191
3607
  if (isObject(a) && isString(a.id)) {
3192
- const columns = isStringArray(c) ? c : void 0;
3193
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3608
+ if (a.id === "")
3609
+ throw new Error("The id can't be empty");
3610
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3611
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3612
+ }
3613
+ if (!isDefined(a) && isObject(b)) {
3614
+ return await this.create(b, c);
3615
+ }
3616
+ if (isObject(a) && !isDefined(a.id)) {
3617
+ return await this.create(a, b);
3194
3618
  }
3195
3619
  throw new Error("Invalid arguments for createOrUpdate method");
3196
3620
  });
@@ -3202,17 +3626,27 @@ class RestRepository extends Query {
3202
3626
  if (a.length === 0)
3203
3627
  return [];
3204
3628
  const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: false });
3205
- const columns = isStringArray(b) ? b : ["*"];
3629
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3206
3630
  const result = await this.read(ids, columns);
3207
3631
  return result;
3208
3632
  }
3209
3633
  if (isString(a) && isObject(b)) {
3210
- const columns = isStringArray(c) ? c : void 0;
3211
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
3634
+ if (a === "")
3635
+ throw new Error("The id can't be empty");
3636
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3637
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
3212
3638
  }
3213
3639
  if (isObject(a) && isString(a.id)) {
3214
- const columns = isStringArray(c) ? c : void 0;
3215
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3640
+ if (a.id === "")
3641
+ throw new Error("The id can't be empty");
3642
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3643
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3644
+ }
3645
+ if (!isDefined(a) && isObject(b)) {
3646
+ return await this.create(b, c);
3647
+ }
3648
+ if (isObject(a) && !isDefined(a.id)) {
3649
+ return await this.create(a, b);
3216
3650
  }
3217
3651
  throw new Error("Invalid arguments for createOrReplace method");
3218
3652
  });
@@ -3229,7 +3663,7 @@ class RestRepository extends Query {
3229
3663
  return o.id;
3230
3664
  throw new Error("Invalid arguments for delete method");
3231
3665
  });
3232
- const columns = isStringArray(b) ? b : ["*"];
3666
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3233
3667
  const result = await this.read(a, columns);
3234
3668
  await __privateMethod$2(this, _deleteRecords, deleteRecords_fn).call(this, ids);
3235
3669
  return result;
@@ -3348,7 +3782,13 @@ class RestRepository extends Query {
3348
3782
  });
3349
3783
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3350
3784
  const records = objects.map(
3351
- (record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record, data.columns ?? ["*"])
3785
+ (record) => initObject(
3786
+ __privateGet$4(this, _db),
3787
+ schemaTables,
3788
+ __privateGet$4(this, _table),
3789
+ record,
3790
+ data.columns ?? ["*"]
3791
+ )
3352
3792
  );
3353
3793
  await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
3354
3794
  return new Page(query, meta, records);
@@ -3379,23 +3819,28 @@ class RestRepository extends Query {
3379
3819
  });
3380
3820
  }
3381
3821
  ask(question, options) {
3822
+ const questionParam = options?.sessionId ? { message: question } : { question };
3382
3823
  const params = {
3383
3824
  pathParams: {
3384
3825
  workspace: "{workspaceId}",
3385
3826
  dbBranchName: "{dbBranch}",
3386
3827
  region: "{region}",
3387
- tableName: __privateGet$4(this, _table)
3828
+ tableName: __privateGet$4(this, _table),
3829
+ sessionId: options?.sessionId
3388
3830
  },
3389
3831
  body: {
3390
- question,
3391
- ...options
3832
+ ...questionParam,
3833
+ rules: options?.rules,
3834
+ searchType: options?.searchType,
3835
+ search: options?.searchType === "keyword" ? options?.search : void 0,
3836
+ vectorSearch: options?.searchType === "vector" ? options?.vectorSearch : void 0
3392
3837
  },
3393
3838
  ...__privateGet$4(this, _getFetchProps).call(this)
3394
3839
  };
3395
3840
  if (options?.onMessage) {
3396
3841
  fetchSSERequest({
3397
3842
  endpoint: "dataPlane",
3398
- url: "/db/{dbBranchName}/tables/{tableName}/ask",
3843
+ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}",
3399
3844
  method: "POST",
3400
3845
  onMessage: (message) => {
3401
3846
  options.onMessage?.({ answer: message.text, records: message.records });
@@ -3403,7 +3848,7 @@ class RestRepository extends Query {
3403
3848
  ...params
3404
3849
  });
3405
3850
  } else {
3406
- return askTable(params);
3851
+ return askTableSession(params);
3407
3852
  }
3408
3853
  }
3409
3854
  }
@@ -3415,7 +3860,7 @@ _schemaTables$2 = new WeakMap();
3415
3860
  _trace = new WeakMap();
3416
3861
  _insertRecordWithoutId = new WeakSet();
3417
3862
  insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
3418
- const record = transformObjectLinks(object);
3863
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3419
3864
  const response = await insertRecord({
3420
3865
  pathParams: {
3421
3866
  workspace: "{workspaceId}",
@@ -3432,7 +3877,9 @@ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
3432
3877
  };
3433
3878
  _insertRecordWithId = new WeakSet();
3434
3879
  insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { createOnly, ifVersion }) {
3435
- const record = transformObjectLinks(object);
3880
+ if (!recordId)
3881
+ return null;
3882
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3436
3883
  const response = await insertRecordWithID({
3437
3884
  pathParams: {
3438
3885
  workspace: "{workspaceId}",
@@ -3450,21 +3897,20 @@ insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { crea
3450
3897
  };
3451
3898
  _insertRecords = new WeakSet();
3452
3899
  insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
3453
- const chunkedOperations = chunk(
3454
- objects.map((object) => ({
3455
- insert: { table: __privateGet$4(this, _table), record: transformObjectLinks(object), createOnly, ifVersion }
3456
- })),
3457
- BULK_OPERATION_MAX_SIZE
3458
- );
3900
+ const operations = await promiseMap(objects, async (object) => {
3901
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3902
+ return { insert: { table: __privateGet$4(this, _table), record, createOnly, ifVersion } };
3903
+ });
3904
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
3459
3905
  const ids = [];
3460
- for (const operations of chunkedOperations) {
3906
+ for (const operations2 of chunkedOperations) {
3461
3907
  const { results } = await branchTransaction({
3462
3908
  pathParams: {
3463
3909
  workspace: "{workspaceId}",
3464
3910
  dbBranchName: "{dbBranch}",
3465
3911
  region: "{region}"
3466
3912
  },
3467
- body: { operations },
3913
+ body: { operations: operations2 },
3468
3914
  ...__privateGet$4(this, _getFetchProps).call(this)
3469
3915
  });
3470
3916
  for (const result of results) {
@@ -3479,7 +3925,9 @@ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
3479
3925
  };
3480
3926
  _updateRecordWithID = new WeakSet();
3481
3927
  updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
3482
- const { id: _id, ...record } = transformObjectLinks(object);
3928
+ if (!recordId)
3929
+ return null;
3930
+ const { id: _id, ...record } = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3483
3931
  try {
3484
3932
  const response = await updateRecordWithID({
3485
3933
  pathParams: {
@@ -3504,21 +3952,20 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
3504
3952
  };
3505
3953
  _updateRecords = new WeakSet();
3506
3954
  updateRecords_fn = async function(objects, { ifVersion, upsert }) {
3507
- const chunkedOperations = chunk(
3508
- objects.map(({ id, ...object }) => ({
3509
- update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields: transformObjectLinks(object) }
3510
- })),
3511
- BULK_OPERATION_MAX_SIZE
3512
- );
3955
+ const operations = await promiseMap(objects, async ({ id, ...object }) => {
3956
+ const fields = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3957
+ return { update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields } };
3958
+ });
3959
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
3513
3960
  const ids = [];
3514
- for (const operations of chunkedOperations) {
3961
+ for (const operations2 of chunkedOperations) {
3515
3962
  const { results } = await branchTransaction({
3516
3963
  pathParams: {
3517
3964
  workspace: "{workspaceId}",
3518
3965
  dbBranchName: "{dbBranch}",
3519
3966
  region: "{region}"
3520
3967
  },
3521
- body: { operations },
3968
+ body: { operations: operations2 },
3522
3969
  ...__privateGet$4(this, _getFetchProps).call(this)
3523
3970
  });
3524
3971
  for (const result of results) {
@@ -3533,6 +3980,8 @@ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
3533
3980
  };
3534
3981
  _upsertRecordWithID = new WeakSet();
3535
3982
  upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
3983
+ if (!recordId)
3984
+ return null;
3536
3985
  const response = await upsertRecordWithID({
3537
3986
  pathParams: {
3538
3987
  workspace: "{workspaceId}",
@@ -3550,6 +3999,8 @@ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
3550
3999
  };
3551
4000
  _deleteRecord = new WeakSet();
3552
4001
  deleteRecord_fn = async function(recordId, columns = ["*"]) {
4002
+ if (!recordId)
4003
+ return null;
3553
4004
  try {
3554
4005
  const response = await deleteRecord({
3555
4006
  pathParams: {
@@ -3574,7 +4025,7 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
3574
4025
  _deleteRecords = new WeakSet();
3575
4026
  deleteRecords_fn = async function(recordIds) {
3576
4027
  const chunkedOperations = chunk(
3577
- recordIds.map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
4028
+ compact(recordIds).map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
3578
4029
  BULK_OPERATION_MAX_SIZE
3579
4030
  );
3580
4031
  for (const operations of chunkedOperations) {
@@ -3617,12 +4068,40 @@ getSchemaTables_fn$1 = async function() {
3617
4068
  __privateSet$4(this, _schemaTables$2, schema.tables);
3618
4069
  return schema.tables;
3619
4070
  };
3620
- const transformObjectLinks = (object) => {
3621
- return Object.entries(object).reduce((acc, [key, value]) => {
4071
+ _transformObjectToApi = new WeakSet();
4072
+ transformObjectToApi_fn = async function(object) {
4073
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
4074
+ const schema = schemaTables.find((table) => table.name === __privateGet$4(this, _table));
4075
+ if (!schema)
4076
+ throw new Error(`Table ${__privateGet$4(this, _table)} not found in schema`);
4077
+ const result = {};
4078
+ for (const [key, value] of Object.entries(object)) {
3622
4079
  if (key === "xata")
3623
- return acc;
3624
- return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
3625
- }, {});
4080
+ continue;
4081
+ const type = schema.columns.find((column) => column.name === key)?.type;
4082
+ switch (type) {
4083
+ case "link": {
4084
+ result[key] = isIdentifiable(value) ? value.id : value;
4085
+ break;
4086
+ }
4087
+ case "datetime": {
4088
+ result[key] = value instanceof Date ? value.toISOString() : value;
4089
+ break;
4090
+ }
4091
+ case `file`:
4092
+ result[key] = await parseInputFileEntry(value);
4093
+ break;
4094
+ case "file[]":
4095
+ result[key] = await promiseMap(value, (item) => parseInputFileEntry(item));
4096
+ break;
4097
+ case "json":
4098
+ result[key] = stringifyJson(value);
4099
+ break;
4100
+ default:
4101
+ result[key] = value;
4102
+ }
4103
+ }
4104
+ return result;
3626
4105
  };
3627
4106
  const initObject = (db, schemaTables, table, object, selectedColumns) => {
3628
4107
  const data = {};
@@ -3654,18 +4133,33 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
3654
4133
  if (item === column.name) {
3655
4134
  return [...acc, "*"];
3656
4135
  }
3657
- if (item.startsWith(`${column.name}.`)) {
4136
+ if (isString(item) && item.startsWith(`${column.name}.`)) {
3658
4137
  const [, ...path] = item.split(".");
3659
4138
  return [...acc, path.join(".")];
3660
4139
  }
3661
4140
  return acc;
3662
4141
  }, []);
3663
- data[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
4142
+ data[column.name] = initObject(
4143
+ db,
4144
+ schemaTables,
4145
+ linkTable,
4146
+ value,
4147
+ selectedLinkColumns
4148
+ );
3664
4149
  } else {
3665
4150
  data[column.name] = null;
3666
4151
  }
3667
4152
  break;
3668
4153
  }
4154
+ case "file":
4155
+ data[column.name] = isDefined(value) ? new XataFile(value) : null;
4156
+ break;
4157
+ case "file[]":
4158
+ data[column.name] = value?.map((item) => new XataFile(item)) ?? null;
4159
+ break;
4160
+ case "json":
4161
+ data[column.name] = parseJson(value);
4162
+ break;
3669
4163
  default:
3670
4164
  data[column.name] = value ?? null;
3671
4165
  if (column.notNull === true && value === null) {
@@ -3675,18 +4169,17 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
3675
4169
  }
3676
4170
  }
3677
4171
  const record = { ...data };
3678
- const serializable = { xata, ...transformObjectLinks(data) };
3679
4172
  const metadata = xata !== void 0 ? { ...xata, createdAt: new Date(xata.createdAt), updatedAt: new Date(xata.updatedAt) } : void 0;
3680
4173
  record.read = function(columns2) {
3681
4174
  return db[table].read(record["id"], columns2);
3682
4175
  };
3683
4176
  record.update = function(data2, b, c) {
3684
- const columns2 = isStringArray(b) ? b : ["*"];
4177
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
3685
4178
  const ifVersion = parseIfVersion(b, c);
3686
4179
  return db[table].update(record["id"], data2, columns2, { ifVersion });
3687
4180
  };
3688
4181
  record.replace = function(data2, b, c) {
3689
- const columns2 = isStringArray(b) ? b : ["*"];
4182
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
3690
4183
  const ifVersion = parseIfVersion(b, c);
3691
4184
  return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
3692
4185
  };
@@ -3698,10 +4191,10 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
3698
4191
  return record.xata;
3699
4192
  };
3700
4193
  record.toSerializable = function() {
3701
- return JSON.parse(JSON.stringify(serializable));
4194
+ return JSON.parse(JSON.stringify(record));
3702
4195
  };
3703
4196
  record.toString = function() {
3704
- return JSON.stringify(transformObjectLinks(serializable));
4197
+ return JSON.stringify(record);
3705
4198
  };
3706
4199
  for (const prop of ["read", "update", "replace", "delete", "getMetadata", "toSerializable", "toString"]) {
3707
4200
  Object.defineProperty(record, prop, { enumerable: false });
@@ -3719,11 +4212,7 @@ function extractId(value) {
3719
4212
  function isValidColumn(columns, column) {
3720
4213
  if (columns.includes("*"))
3721
4214
  return true;
3722
- if (column.type === "link") {
3723
- const linkColumns = columns.filter((item) => item.startsWith(column.name));
3724
- return linkColumns.length > 0;
3725
- }
3726
- return columns.includes(column.name);
4215
+ return columns.filter((item) => isString(item) && item.startsWith(column.name)).length > 0;
3727
4216
  }
3728
4217
  function parseIfVersion(...args) {
3729
4218
  for (const arg of args) {
@@ -3938,6 +4427,78 @@ getSchemaTables_fn = async function(pluginOptions) {
3938
4427
  return schema.tables;
3939
4428
  };
3940
4429
 
4430
+ function escapeElement(elementRepresentation) {
4431
+ const escaped = elementRepresentation.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
4432
+ return '"' + escaped + '"';
4433
+ }
4434
+ function arrayString(val) {
4435
+ let result = "{";
4436
+ for (let i = 0; i < val.length; i++) {
4437
+ if (i > 0) {
4438
+ result = result + ",";
4439
+ }
4440
+ if (val[i] === null || typeof val[i] === "undefined") {
4441
+ result = result + "NULL";
4442
+ } else if (Array.isArray(val[i])) {
4443
+ result = result + arrayString(val[i]);
4444
+ } else if (val[i] instanceof Buffer) {
4445
+ result += "\\\\x" + val[i].toString("hex");
4446
+ } else {
4447
+ result += escapeElement(prepareValue(val[i]));
4448
+ }
4449
+ }
4450
+ result = result + "}";
4451
+ return result;
4452
+ }
4453
+ function prepareValue(value) {
4454
+ if (!isDefined(value))
4455
+ return null;
4456
+ if (value instanceof Date) {
4457
+ return value.toISOString();
4458
+ }
4459
+ if (Array.isArray(value)) {
4460
+ return arrayString(value);
4461
+ }
4462
+ if (isObject(value)) {
4463
+ return JSON.stringify(value);
4464
+ }
4465
+ try {
4466
+ return value.toString();
4467
+ } catch (e) {
4468
+ return value;
4469
+ }
4470
+ }
4471
+ function prepareParams(param1, param2) {
4472
+ if (isString(param1)) {
4473
+ return { statement: param1, params: param2?.map((value) => prepareValue(value)) };
4474
+ }
4475
+ if (isStringArray(param1)) {
4476
+ const statement = param1.reduce((acc, curr, index) => {
4477
+ return acc + curr + (index < (param2?.length ?? 0) ? "$" + (index + 1) : "");
4478
+ }, "");
4479
+ return { statement, params: param2?.map((value) => prepareValue(value)) };
4480
+ }
4481
+ if (isObject(param1)) {
4482
+ const { statement, params, consistency } = param1;
4483
+ return { statement, params: params?.map((value) => prepareValue(value)), consistency };
4484
+ }
4485
+ throw new Error("Invalid query");
4486
+ }
4487
+
4488
+ class SQLPlugin extends XataPlugin {
4489
+ build(pluginOptions) {
4490
+ return async (param1, ...param2) => {
4491
+ const { statement, params, consistency } = prepareParams(param1, param2);
4492
+ const { records, warning } = await sqlQuery({
4493
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4494
+ body: { statement, params, consistency },
4495
+ ...pluginOptions
4496
+ });
4497
+ return { records, warning };
4498
+ };
4499
+ }
4500
+ }
4501
+
3941
4502
  class TransactionPlugin extends XataPlugin {
3942
4503
  build(pluginOptions) {
3943
4504
  return {
@@ -3992,9 +4553,13 @@ const buildClient = (plugins) => {
3992
4553
  const db = new SchemaPlugin(schemaTables).build(pluginOptions);
3993
4554
  const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
3994
4555
  const transactions = new TransactionPlugin().build(pluginOptions);
4556
+ const sql = new SQLPlugin().build(pluginOptions);
4557
+ const files = new FilesPlugin().build(pluginOptions);
3995
4558
  this.db = db;
3996
4559
  this.search = search;
3997
4560
  this.transactions = transactions;
4561
+ this.sql = sql;
4562
+ this.files = files;
3998
4563
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
3999
4564
  if (namespace === void 0)
4000
4565
  continue;
@@ -4182,6 +4747,7 @@ class XataError extends Error {
4182
4747
 
4183
4748
  exports.BaseClient = BaseClient;
4184
4749
  exports.FetcherError = FetcherError;
4750
+ exports.FilesPlugin = FilesPlugin;
4185
4751
  exports.Operations = operationsByTag;
4186
4752
  exports.PAGINATION_DEFAULT_OFFSET = PAGINATION_DEFAULT_OFFSET;
4187
4753
  exports.PAGINATION_DEFAULT_SIZE = PAGINATION_DEFAULT_SIZE;
@@ -4190,8 +4756,10 @@ exports.PAGINATION_MAX_SIZE = PAGINATION_MAX_SIZE;
4190
4756
  exports.Page = Page;
4191
4757
  exports.Query = Query;
4192
4758
  exports.RecordArray = RecordArray;
4759
+ exports.RecordColumnTypes = RecordColumnTypes;
4193
4760
  exports.Repository = Repository;
4194
4761
  exports.RestRepository = RestRepository;
4762
+ exports.SQLPlugin = SQLPlugin;
4195
4763
  exports.SchemaPlugin = SchemaPlugin;
4196
4764
  exports.SearchPlugin = SearchPlugin;
4197
4765
  exports.Serializer = Serializer;
@@ -4199,6 +4767,7 @@ exports.SimpleCache = SimpleCache;
4199
4767
  exports.XataApiClient = XataApiClient;
4200
4768
  exports.XataApiPlugin = XataApiPlugin;
4201
4769
  exports.XataError = XataError;
4770
+ exports.XataFile = XataFile;
4202
4771
  exports.XataPlugin = XataPlugin;
4203
4772
  exports.acceptWorkspaceMemberInvite = acceptWorkspaceMemberInvite;
4204
4773
  exports.addGitBranchesEntry = addGitBranchesEntry;
@@ -4206,6 +4775,7 @@ exports.addTableColumn = addTableColumn;
4206
4775
  exports.aggregateTable = aggregateTable;
4207
4776
  exports.applyBranchSchemaEdit = applyBranchSchemaEdit;
4208
4777
  exports.askTable = askTable;
4778
+ exports.askTableSession = askTableSession;
4209
4779
  exports.branchTransaction = branchTransaction;
4210
4780
  exports.buildClient = buildClient;
4211
4781
  exports.buildPreviewBranchName = buildPreviewBranchName;
@@ -4219,6 +4789,7 @@ exports.compareMigrationRequest = compareMigrationRequest;
4219
4789
  exports.contains = contains;
4220
4790
  exports.copyBranch = copyBranch;
4221
4791
  exports.createBranch = createBranch;
4792
+ exports.createCluster = createCluster;
4222
4793
  exports.createDatabase = createDatabase;
4223
4794
  exports.createMigrationRequest = createMigrationRequest;
4224
4795
  exports.createTable = createTable;
@@ -4230,10 +4801,12 @@ exports.deleteDatabase = deleteDatabase;
4230
4801
  exports.deleteDatabaseGithubSettings = deleteDatabaseGithubSettings;
4231
4802
  exports.deleteFile = deleteFile;
4232
4803
  exports.deleteFileItem = deleteFileItem;
4804
+ exports.deleteOAuthAccessToken = deleteOAuthAccessToken;
4233
4805
  exports.deleteRecord = deleteRecord;
4234
4806
  exports.deleteTable = deleteTable;
4235
4807
  exports.deleteUser = deleteUser;
4236
4808
  exports.deleteUserAPIKey = deleteUserAPIKey;
4809
+ exports.deleteUserOAuthClient = deleteUserOAuthClient;
4237
4810
  exports.deleteWorkspace = deleteWorkspace;
4238
4811
  exports.deserialize = deserialize;
4239
4812
  exports.endsWith = endsWith;
@@ -4243,6 +4816,7 @@ exports.exists = exists;
4243
4816
  exports.fileAccess = fileAccess;
4244
4817
  exports.ge = ge;
4245
4818
  exports.getAPIKey = getAPIKey;
4819
+ exports.getAuthorizationCode = getAuthorizationCode;
4246
4820
  exports.getBranch = getBranch;
4247
4821
  exports.getBranchDetails = getBranchDetails;
4248
4822
  exports.getBranchList = getBranchList;
@@ -4251,6 +4825,7 @@ exports.getBranchMigrationHistory = getBranchMigrationHistory;
4251
4825
  exports.getBranchMigrationPlan = getBranchMigrationPlan;
4252
4826
  exports.getBranchSchemaHistory = getBranchSchemaHistory;
4253
4827
  exports.getBranchStats = getBranchStats;
4828
+ exports.getCluster = getCluster;
4254
4829
  exports.getColumn = getColumn;
4255
4830
  exports.getDatabaseGithubSettings = getDatabaseGithubSettings;
4256
4831
  exports.getDatabaseList = getDatabaseList;
@@ -4268,9 +4843,12 @@ exports.getTableColumns = getTableColumns;
4268
4843
  exports.getTableSchema = getTableSchema;
4269
4844
  exports.getUser = getUser;
4270
4845
  exports.getUserAPIKeys = getUserAPIKeys;
4846
+ exports.getUserOAuthAccessTokens = getUserOAuthAccessTokens;
4847
+ exports.getUserOAuthClients = getUserOAuthClients;
4271
4848
  exports.getWorkspace = getWorkspace;
4272
4849
  exports.getWorkspaceMembersList = getWorkspaceMembersList;
4273
4850
  exports.getWorkspacesList = getWorkspacesList;
4851
+ exports.grantAuthorizationCode = grantAuthorizationCode;
4274
4852
  exports.greaterEquals = greaterEquals;
4275
4853
  exports.greaterThan = greaterThan;
4276
4854
  exports.greaterThanEquals = greaterThanEquals;
@@ -4289,11 +4867,14 @@ exports.isHostProviderAlias = isHostProviderAlias;
4289
4867
  exports.isHostProviderBuilder = isHostProviderBuilder;
4290
4868
  exports.isIdentifiable = isIdentifiable;
4291
4869
  exports.isNot = isNot;
4870
+ exports.isValidExpandedColumn = isValidExpandedColumn;
4871
+ exports.isValidSelectableColumns = isValidSelectableColumns;
4292
4872
  exports.isXataRecord = isXataRecord;
4293
4873
  exports.le = le;
4294
4874
  exports.lessEquals = lessEquals;
4295
4875
  exports.lessThan = lessThan;
4296
4876
  exports.lessThanEquals = lessThanEquals;
4877
+ exports.listClusters = listClusters;
4297
4878
  exports.listMigrationRequestsCommits = listMigrationRequestsCommits;
4298
4879
  exports.listRegions = listRegions;
4299
4880
  exports.lt = lt;
@@ -4322,12 +4903,15 @@ exports.setTableSchema = setTableSchema;
4322
4903
  exports.sqlQuery = sqlQuery;
4323
4904
  exports.startsWith = startsWith;
4324
4905
  exports.summarizeTable = summarizeTable;
4906
+ exports.transformImage = transformImage;
4325
4907
  exports.updateBranchMetadata = updateBranchMetadata;
4326
4908
  exports.updateBranchSchema = updateBranchSchema;
4909
+ exports.updateCluster = updateCluster;
4327
4910
  exports.updateColumn = updateColumn;
4328
4911
  exports.updateDatabaseGithubSettings = updateDatabaseGithubSettings;
4329
4912
  exports.updateDatabaseMetadata = updateDatabaseMetadata;
4330
4913
  exports.updateMigrationRequest = updateMigrationRequest;
4914
+ exports.updateOAuthAccessToken = updateOAuthAccessToken;
4331
4915
  exports.updateRecordWithID = updateRecordWithID;
4332
4916
  exports.updateTable = updateTable;
4333
4917
  exports.updateUser = updateUser;