@xata.io/client 0.0.0-alpha.vf350c0a → 0.0.0-alpha.vf38b6da

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
@@ -7,46 +7,101 @@ function compact(arr) {
7
7
  function isObject(value) {
8
8
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
9
9
  }
10
+ function isDefined(value) {
11
+ return value !== null && value !== void 0;
12
+ }
10
13
  function isString(value) {
11
- return value !== void 0 && value !== null && typeof value === "string";
14
+ return isDefined(value) && typeof value === "string";
15
+ }
16
+ function isStringArray(value) {
17
+ return isDefined(value) && Array.isArray(value) && value.every(isString);
12
18
  }
13
19
  function toBase64(value) {
14
20
  try {
15
21
  return btoa(value);
16
22
  } catch (err) {
17
- return Buffer.from(value).toString("base64");
23
+ const buf = Buffer;
24
+ return buf.from(value).toString("base64");
18
25
  }
19
26
  }
20
27
 
21
- function getEnvVariable(name) {
28
+ function getEnvironment() {
22
29
  try {
23
- if (isObject(process) && isString(process?.env?.[name])) {
24
- return process.env[name];
30
+ if (isObject(process) && isObject(process.env)) {
31
+ return {
32
+ apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
33
+ databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
34
+ branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
35
+ envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
36
+ fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
37
+ };
25
38
  }
26
39
  } catch (err) {
27
40
  }
28
41
  try {
29
- if (isObject(Deno) && isString(Deno?.env?.get(name))) {
30
- return Deno.env.get(name);
42
+ if (isObject(Deno) && isObject(Deno.env)) {
43
+ return {
44
+ apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
45
+ databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
46
+ branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
47
+ envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
48
+ fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
49
+ };
31
50
  }
32
51
  } catch (err) {
33
52
  }
53
+ return {
54
+ apiKey: getGlobalApiKey(),
55
+ databaseURL: getGlobalDatabaseURL(),
56
+ branch: getGlobalBranch(),
57
+ envBranch: void 0,
58
+ fallbackBranch: getGlobalFallbackBranch()
59
+ };
60
+ }
61
+ function getGlobalApiKey() {
62
+ try {
63
+ return XATA_API_KEY;
64
+ } catch (err) {
65
+ return void 0;
66
+ }
67
+ }
68
+ function getGlobalDatabaseURL() {
69
+ try {
70
+ return XATA_DATABASE_URL;
71
+ } catch (err) {
72
+ return void 0;
73
+ }
74
+ }
75
+ function getGlobalBranch() {
76
+ try {
77
+ return XATA_BRANCH;
78
+ } catch (err) {
79
+ return void 0;
80
+ }
81
+ }
82
+ function getGlobalFallbackBranch() {
83
+ try {
84
+ return XATA_FALLBACK_BRANCH;
85
+ } catch (err) {
86
+ return void 0;
87
+ }
34
88
  }
35
89
  async function getGitBranch() {
90
+ const cmd = ["git", "branch", "--show-current"];
91
+ const fullCmd = cmd.join(" ");
92
+ const nodeModule = ["child", "process"].join("_");
93
+ const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
36
94
  try {
37
95
  if (typeof require === "function") {
38
- const req = require;
39
- return req("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
96
+ return require(nodeModule).execSync(fullCmd, execOptions).trim();
40
97
  }
98
+ const { execSync } = await import(nodeModule);
99
+ return execSync(fullCmd, execOptions).toString().trim();
41
100
  } catch (err) {
42
101
  }
43
102
  try {
44
103
  if (isObject(Deno)) {
45
- const process2 = Deno.run({
46
- cmd: ["git", "branch", "--show-current"],
47
- stdout: "piped",
48
- stderr: "piped"
49
- });
104
+ const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
50
105
  return new TextDecoder().decode(await process2.output()).trim();
51
106
  }
52
107
  } catch (err) {
@@ -55,7 +110,8 @@ async function getGitBranch() {
55
110
 
56
111
  function getAPIKey() {
57
112
  try {
58
- return getEnvVariable("XATA_API_KEY") ?? XATA_API_KEY;
113
+ const { apiKey } = getEnvironment();
114
+ return apiKey;
59
115
  } catch (err) {
60
116
  return void 0;
61
117
  }
@@ -65,21 +121,35 @@ function getFetchImplementation(userFetch) {
65
121
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
66
122
  const fetchImpl = userFetch ?? globalFetch;
67
123
  if (!fetchImpl) {
68
- throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
124
+ throw new Error(
125
+ `The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`
126
+ );
69
127
  }
70
128
  return fetchImpl;
71
129
  }
72
130
 
73
- class FetcherError extends Error {
74
- constructor(status, data) {
131
+ const VERSION = "0.0.0-alpha.vf38b6da";
132
+
133
+ class ErrorWithCause extends Error {
134
+ constructor(message, options) {
135
+ super(message, options);
136
+ }
137
+ }
138
+ class FetcherError extends ErrorWithCause {
139
+ constructor(status, data, requestId) {
75
140
  super(getMessage(data));
76
141
  this.status = status;
77
142
  this.errors = isBulkError(data) ? data.errors : void 0;
143
+ this.requestId = requestId;
78
144
  if (data instanceof Error) {
79
145
  this.stack = data.stack;
80
146
  this.cause = data.cause;
81
147
  }
82
148
  }
149
+ toString() {
150
+ const error = super.toString();
151
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
152
+ }
83
153
  }
84
154
  function isBulkError(error) {
85
155
  return isObject(error) && Array.isArray(error.errors);
@@ -102,7 +172,12 @@ function getMessage(data) {
102
172
  }
103
173
 
104
174
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
105
- const query = new URLSearchParams(queryParams).toString();
175
+ const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
176
+ if (value === void 0 || value === null)
177
+ return acc;
178
+ return { ...acc, [key]: value };
179
+ }, {});
180
+ const query = new URLSearchParams(cleanQueryParams).toString();
106
181
  const queryString = query.length > 0 ? `?${query}` : "";
107
182
  return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
108
183
  };
@@ -142,6 +217,7 @@ async function fetch$1({
142
217
  body: body ? JSON.stringify(body) : void 0,
143
218
  headers: {
144
219
  "Content-Type": "application/json",
220
+ "User-Agent": `Xata client-ts/${VERSION}`,
145
221
  ...headers,
146
222
  ...hostHeader(fullUrl),
147
223
  Authorization: `Bearer ${apiKey}`
@@ -150,14 +226,15 @@ async function fetch$1({
150
226
  if (response.status === 204) {
151
227
  return {};
152
228
  }
229
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
153
230
  try {
154
231
  const jsonResponse = await response.json();
155
232
  if (response.ok) {
156
233
  return jsonResponse;
157
234
  }
158
- throw new FetcherError(response.status, jsonResponse);
235
+ throw new FetcherError(response.status, jsonResponse, requestId);
159
236
  } catch (error) {
160
- throw new FetcherError(response.status, error);
237
+ throw new FetcherError(response.status, error, requestId);
161
238
  }
162
239
  }
163
240
 
@@ -216,6 +293,7 @@ const removeWorkspaceMember = (variables) => fetch$1({
216
293
  ...variables
217
294
  });
218
295
  const inviteWorkspaceMember = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables });
296
+ const updateWorkspaceMemberInvite = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables });
219
297
  const cancelWorkspaceMemberInvite = (variables) => fetch$1({
220
298
  url: "/workspaces/{workspaceId}/invites/{inviteId}",
221
299
  method: "delete",
@@ -251,6 +329,11 @@ const deleteDatabase = (variables) => fetch$1({
251
329
  method: "delete",
252
330
  ...variables
253
331
  });
332
+ const getDatabaseMetadata = (variables) => fetch$1({
333
+ url: "/dbs/{dbName}/metadata",
334
+ method: "get",
335
+ ...variables
336
+ });
254
337
  const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
255
338
  const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
256
339
  const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
@@ -264,11 +347,7 @@ const getBranchDetails = (variables) => fetch$1({
264
347
  method: "get",
265
348
  ...variables
266
349
  });
267
- const createBranch = (variables) => fetch$1({
268
- url: "/db/{dbBranchName}",
269
- method: "put",
270
- ...variables
271
- });
350
+ const createBranch = (variables) => fetch$1({ url: "/db/{dbBranchName}", method: "put", ...variables });
272
351
  const deleteBranch = (variables) => fetch$1({
273
352
  url: "/db/{dbBranchName}",
274
353
  method: "delete",
@@ -342,11 +421,7 @@ const updateColumn = (variables) => fetch$1({
342
421
  method: "patch",
343
422
  ...variables
344
423
  });
345
- const insertRecord = (variables) => fetch$1({
346
- url: "/db/{dbBranchName}/tables/{tableName}/data",
347
- method: "post",
348
- ...variables
349
- });
424
+ const insertRecord = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables });
350
425
  const insertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables });
351
426
  const updateRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables });
352
427
  const upsertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables });
@@ -366,6 +441,11 @@ const queryTable = (variables) => fetch$1({
366
441
  method: "post",
367
442
  ...variables
368
443
  });
444
+ const searchTable = (variables) => fetch$1({
445
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
446
+ method: "post",
447
+ ...variables
448
+ });
369
449
  const searchBranch = (variables) => fetch$1({
370
450
  url: "/db/{dbBranchName}/search",
371
451
  method: "post",
@@ -383,6 +463,7 @@ const operationsByTag = {
383
463
  updateWorkspaceMemberRole,
384
464
  removeWorkspaceMember,
385
465
  inviteWorkspaceMember,
466
+ updateWorkspaceMemberInvite,
386
467
  cancelWorkspaceMemberInvite,
387
468
  resendWorkspaceMemberInvite,
388
469
  acceptWorkspaceMemberInvite
@@ -391,6 +472,7 @@ const operationsByTag = {
391
472
  getDatabaseList,
392
473
  createDatabase,
393
474
  deleteDatabase,
475
+ getDatabaseMetadata,
394
476
  getGitBranchesMapping,
395
477
  addGitBranchesEntry,
396
478
  removeGitBranchesEntry,
@@ -429,6 +511,7 @@ const operationsByTag = {
429
511
  getRecord,
430
512
  bulkInsertTableRecords,
431
513
  queryTable,
514
+ searchTable,
432
515
  searchBranch
433
516
  }
434
517
  };
@@ -471,7 +554,7 @@ var __privateAdd$7 = (obj, member, value) => {
471
554
  throw TypeError("Cannot add the same private member more than once");
472
555
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
473
556
  };
474
- var __privateSet$6 = (obj, member, value, setter) => {
557
+ var __privateSet$7 = (obj, member, value, setter) => {
475
558
  __accessCheck$7(obj, member, "write to private field");
476
559
  setter ? setter.call(obj, value) : member.set(obj, value);
477
560
  return value;
@@ -486,7 +569,7 @@ class XataApiClient {
486
569
  if (!apiKey) {
487
570
  throw new Error("Could not resolve a valid apiKey");
488
571
  }
489
- __privateSet$6(this, _extraProps, {
572
+ __privateSet$7(this, _extraProps, {
490
573
  apiUrl: getHostUrl(provider, "main"),
491
574
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
492
575
  fetchImpl: getFetchImplementation(options.fetch),
@@ -613,6 +696,13 @@ class WorkspaceApi {
613
696
  ...this.extraProps
614
697
  });
615
698
  }
699
+ updateWorkspaceMemberInvite(workspaceId, inviteId, role) {
700
+ return operationsByTag.workspaces.updateWorkspaceMemberInvite({
701
+ pathParams: { workspaceId, inviteId },
702
+ body: { role },
703
+ ...this.extraProps
704
+ });
705
+ }
616
706
  cancelWorkspaceMemberInvite(workspaceId, inviteId) {
617
707
  return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
618
708
  pathParams: { workspaceId, inviteId },
@@ -655,6 +745,12 @@ class DatabaseApi {
655
745
  ...this.extraProps
656
746
  });
657
747
  }
748
+ getDatabaseMetadata(workspace, dbName) {
749
+ return operationsByTag.database.getDatabaseMetadata({
750
+ pathParams: { workspace, dbName },
751
+ ...this.extraProps
752
+ });
753
+ }
658
754
  getGitBranchesMapping(workspace, dbName) {
659
755
  return operationsByTag.database.getGitBranchesMapping({
660
756
  pathParams: { workspace, dbName },
@@ -675,10 +771,10 @@ class DatabaseApi {
675
771
  ...this.extraProps
676
772
  });
677
773
  }
678
- resolveBranch(workspace, dbName, gitBranch) {
774
+ resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
679
775
  return operationsByTag.database.resolveBranch({
680
776
  pathParams: { workspace, dbName },
681
- queryParams: { gitBranch },
777
+ queryParams: { gitBranch, fallbackBranch },
682
778
  ...this.extraProps
683
779
  });
684
780
  }
@@ -699,10 +795,10 @@ class BranchApi {
699
795
  ...this.extraProps
700
796
  });
701
797
  }
702
- createBranch(workspace, database, branch, from = "", options = {}) {
798
+ createBranch(workspace, database, branch, from, options = {}) {
703
799
  return operationsByTag.branch.createBranch({
704
800
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
705
- queryParams: { from },
801
+ queryParams: isString(from) ? { from } : void 0,
706
802
  body: options,
707
803
  ...this.extraProps
708
804
  });
@@ -827,9 +923,10 @@ class RecordsApi {
827
923
  constructor(extraProps) {
828
924
  this.extraProps = extraProps;
829
925
  }
830
- insertRecord(workspace, database, branch, tableName, record) {
926
+ insertRecord(workspace, database, branch, tableName, record, options = {}) {
831
927
  return operationsByTag.records.insertRecord({
832
928
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
929
+ queryParams: options,
833
930
  body: record,
834
931
  ...this.extraProps
835
932
  });
@@ -858,21 +955,24 @@ class RecordsApi {
858
955
  ...this.extraProps
859
956
  });
860
957
  }
861
- deleteRecord(workspace, database, branch, tableName, recordId) {
958
+ deleteRecord(workspace, database, branch, tableName, recordId, options = {}) {
862
959
  return operationsByTag.records.deleteRecord({
863
960
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
961
+ queryParams: options,
864
962
  ...this.extraProps
865
963
  });
866
964
  }
867
965
  getRecord(workspace, database, branch, tableName, recordId, options = {}) {
868
966
  return operationsByTag.records.getRecord({
869
967
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
968
+ queryParams: options,
870
969
  ...this.extraProps
871
970
  });
872
971
  }
873
- bulkInsertTableRecords(workspace, database, branch, tableName, records) {
972
+ bulkInsertTableRecords(workspace, database, branch, tableName, records, options = {}) {
874
973
  return operationsByTag.records.bulkInsertTableRecords({
875
974
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
975
+ queryParams: options,
876
976
  body: { records },
877
977
  ...this.extraProps
878
978
  });
@@ -884,6 +984,13 @@ class RecordsApi {
884
984
  ...this.extraProps
885
985
  });
886
986
  }
987
+ searchTable(workspace, database, branch, tableName, query) {
988
+ return operationsByTag.records.searchTable({
989
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
990
+ body: query,
991
+ ...this.extraProps
992
+ });
993
+ }
887
994
  searchBranch(workspace, database, branch, query) {
888
995
  return operationsByTag.records.searchBranch({
889
996
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -916,30 +1023,30 @@ var __privateAdd$6 = (obj, member, value) => {
916
1023
  throw TypeError("Cannot add the same private member more than once");
917
1024
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
918
1025
  };
919
- var __privateSet$5 = (obj, member, value, setter) => {
1026
+ var __privateSet$6 = (obj, member, value, setter) => {
920
1027
  __accessCheck$6(obj, member, "write to private field");
921
1028
  setter ? setter.call(obj, value) : member.set(obj, value);
922
1029
  return value;
923
1030
  };
924
- var _query;
1031
+ var _query, _page;
925
1032
  class Page {
926
1033
  constructor(query, meta, records = []) {
927
1034
  __privateAdd$6(this, _query, void 0);
928
- __privateSet$5(this, _query, query);
1035
+ __privateSet$6(this, _query, query);
929
1036
  this.meta = meta;
930
- this.records = records;
1037
+ this.records = new RecordArray(this, records);
931
1038
  }
932
1039
  async nextPage(size, offset) {
933
- return __privateGet$6(this, _query).getPaginated({ page: { size, offset, after: this.meta.page.cursor } });
1040
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
934
1041
  }
935
1042
  async previousPage(size, offset) {
936
- return __privateGet$6(this, _query).getPaginated({ page: { size, offset, before: this.meta.page.cursor } });
1043
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
937
1044
  }
938
1045
  async firstPage(size, offset) {
939
- return __privateGet$6(this, _query).getPaginated({ page: { size, offset, first: this.meta.page.cursor } });
1046
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
940
1047
  }
941
1048
  async lastPage(size, offset) {
942
- return __privateGet$6(this, _query).getPaginated({ page: { size, offset, last: this.meta.page.cursor } });
1049
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
943
1050
  }
944
1051
  hasNextPage() {
945
1052
  return this.meta.page.more;
@@ -947,9 +1054,56 @@ class Page {
947
1054
  }
948
1055
  _query = new WeakMap();
949
1056
  const PAGINATION_MAX_SIZE = 200;
950
- const PAGINATION_DEFAULT_SIZE = 200;
1057
+ const PAGINATION_DEFAULT_SIZE = 20;
951
1058
  const PAGINATION_MAX_OFFSET = 800;
952
1059
  const PAGINATION_DEFAULT_OFFSET = 0;
1060
+ function isCursorPaginationOptions(options) {
1061
+ return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
1062
+ }
1063
+ const _RecordArray = class extends Array {
1064
+ constructor(...args) {
1065
+ super(..._RecordArray.parseConstructorParams(...args));
1066
+ __privateAdd$6(this, _page, void 0);
1067
+ __privateSet$6(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
1068
+ }
1069
+ static parseConstructorParams(...args) {
1070
+ if (args.length === 1 && typeof args[0] === "number") {
1071
+ return new Array(args[0]);
1072
+ }
1073
+ if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
1074
+ const result = args[1] ?? args[0].records ?? [];
1075
+ return new Array(...result);
1076
+ }
1077
+ return new Array(...args);
1078
+ }
1079
+ toArray() {
1080
+ return new Array(...this);
1081
+ }
1082
+ map(callbackfn, thisArg) {
1083
+ return this.toArray().map(callbackfn, thisArg);
1084
+ }
1085
+ async nextPage(size, offset) {
1086
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1087
+ return new _RecordArray(newPage);
1088
+ }
1089
+ async previousPage(size, offset) {
1090
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1091
+ return new _RecordArray(newPage);
1092
+ }
1093
+ async firstPage(size, offset) {
1094
+ const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1095
+ return new _RecordArray(newPage);
1096
+ }
1097
+ async lastPage(size, offset) {
1098
+ const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1099
+ return new _RecordArray(newPage);
1100
+ }
1101
+ hasNextPage() {
1102
+ return __privateGet$6(this, _page).meta.page.more;
1103
+ }
1104
+ };
1105
+ let RecordArray = _RecordArray;
1106
+ _page = new WeakMap();
953
1107
 
954
1108
  var __accessCheck$5 = (obj, member, msg) => {
955
1109
  if (!member.has(obj))
@@ -964,25 +1118,26 @@ var __privateAdd$5 = (obj, member, value) => {
964
1118
  throw TypeError("Cannot add the same private member more than once");
965
1119
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
966
1120
  };
967
- var __privateSet$4 = (obj, member, value, setter) => {
1121
+ var __privateSet$5 = (obj, member, value, setter) => {
968
1122
  __accessCheck$5(obj, member, "write to private field");
969
1123
  setter ? setter.call(obj, value) : member.set(obj, value);
970
1124
  return value;
971
1125
  };
972
1126
  var _table$1, _repository, _data;
973
1127
  const _Query = class {
974
- constructor(repository, table, data, parent) {
1128
+ constructor(repository, table, data, rawParent) {
975
1129
  __privateAdd$5(this, _table$1, void 0);
976
1130
  __privateAdd$5(this, _repository, void 0);
977
1131
  __privateAdd$5(this, _data, { filter: {} });
978
1132
  this.meta = { page: { cursor: "start", more: true } };
979
- this.records = [];
980
- __privateSet$4(this, _table$1, table);
1133
+ this.records = new RecordArray(this, []);
1134
+ __privateSet$5(this, _table$1, table);
981
1135
  if (repository) {
982
- __privateSet$4(this, _repository, repository);
1136
+ __privateSet$5(this, _repository, repository);
983
1137
  } else {
984
- __privateSet$4(this, _repository, this);
1138
+ __privateSet$5(this, _repository, this);
985
1139
  }
1140
+ const parent = cleanParent(data, rawParent);
986
1141
  __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
987
1142
  __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
988
1143
  __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
@@ -990,7 +1145,7 @@ const _Query = class {
990
1145
  __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
991
1146
  __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
992
1147
  __privateGet$5(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
993
- __privateGet$5(this, _data).page = data.page ?? parent?.page;
1148
+ __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
994
1149
  __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
995
1150
  this.any = this.any.bind(this);
996
1151
  this.all = this.all.bind(this);
@@ -1005,8 +1160,8 @@ const _Query = class {
1005
1160
  return __privateGet$5(this, _data);
1006
1161
  }
1007
1162
  key() {
1008
- const { columns = [], filter = {}, sort = [], page = {} } = __privateGet$5(this, _data);
1009
- const key = JSON.stringify({ columns, filter, sort, page });
1163
+ const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$5(this, _data);
1164
+ const key = JSON.stringify({ columns, filter, sort, pagination });
1010
1165
  return toBase64(key);
1011
1166
  }
1012
1167
  any(...queries) {
@@ -1035,47 +1190,57 @@ const _Query = class {
1035
1190
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1036
1191
  }
1037
1192
  }
1038
- sort(column, direction) {
1193
+ sort(column, direction = "asc") {
1039
1194
  const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
1040
1195
  const sort = [...originalSort, { column, direction }];
1041
1196
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
1042
1197
  }
1043
1198
  select(columns) {
1044
- return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { columns }, __privateGet$5(this, _data));
1199
+ return new _Query(
1200
+ __privateGet$5(this, _repository),
1201
+ __privateGet$5(this, _table$1),
1202
+ { columns },
1203
+ __privateGet$5(this, _data)
1204
+ );
1045
1205
  }
1046
1206
  getPaginated(options = {}) {
1047
1207
  const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
1048
1208
  return __privateGet$5(this, _repository).query(query);
1049
1209
  }
1050
1210
  async *[Symbol.asyncIterator]() {
1051
- for await (const [record] of this.getIterator(1)) {
1211
+ for await (const [record] of this.getIterator({ batchSize: 1 })) {
1052
1212
  yield record;
1053
1213
  }
1054
1214
  }
1055
- async *getIterator(chunk, options = {}) {
1056
- let offset = 0;
1057
- let end = false;
1058
- while (!end) {
1059
- const { records, meta } = await this.getPaginated({ ...options, page: { size: chunk, offset } });
1060
- yield records;
1061
- offset += chunk;
1062
- end = !meta.page.more;
1215
+ async *getIterator(options = {}) {
1216
+ const { batchSize = 1 } = options;
1217
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
1218
+ let more = page.hasNextPage();
1219
+ yield page.records;
1220
+ while (more) {
1221
+ page = await page.nextPage();
1222
+ more = page.hasNextPage();
1223
+ yield page.records;
1063
1224
  }
1064
1225
  }
1065
1226
  async getMany(options = {}) {
1066
- const { records } = await this.getPaginated(options);
1067
- return records;
1227
+ const page = await this.getPaginated(options);
1228
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1229
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1230
+ }
1231
+ return page.records;
1068
1232
  }
1069
- async getAll(chunk = PAGINATION_MAX_SIZE, options = {}) {
1233
+ async getAll(options = {}) {
1234
+ const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
1070
1235
  const results = [];
1071
- for await (const page of this.getIterator(chunk, options)) {
1236
+ for await (const page of this.getIterator({ ...rest, batchSize })) {
1072
1237
  results.push(...page);
1073
1238
  }
1074
1239
  return results;
1075
1240
  }
1076
1241
  async getFirst(options = {}) {
1077
- const records = await this.getMany({ ...options, page: { size: 1 } });
1078
- return records[0] || null;
1242
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1243
+ return records[0] ?? null;
1079
1244
  }
1080
1245
  cache(ttl) {
1081
1246
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
@@ -1087,10 +1252,10 @@ const _Query = class {
1087
1252
  return this.firstPage(size, offset);
1088
1253
  }
1089
1254
  firstPage(size, offset) {
1090
- return this.getPaginated({ page: { size, offset } });
1255
+ return this.getPaginated({ pagination: { size, offset } });
1091
1256
  }
1092
1257
  lastPage(size, offset) {
1093
- return this.getPaginated({ page: { size, offset, before: "end" } });
1258
+ return this.getPaginated({ pagination: { size, offset, before: "end" } });
1094
1259
  }
1095
1260
  hasNextPage() {
1096
1261
  return this.meta.page.more;
@@ -1100,12 +1265,20 @@ let Query = _Query;
1100
1265
  _table$1 = new WeakMap();
1101
1266
  _repository = new WeakMap();
1102
1267
  _data = new WeakMap();
1268
+ function cleanParent(data, parent) {
1269
+ if (isCursorPaginationOptions(data.pagination)) {
1270
+ return { ...parent, sorting: void 0, filter: void 0 };
1271
+ }
1272
+ return parent;
1273
+ }
1103
1274
 
1104
1275
  function isIdentifiable(x) {
1105
1276
  return isObject(x) && isString(x?.id);
1106
1277
  }
1107
1278
  function isXataRecord(x) {
1108
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1279
+ const record = x;
1280
+ const metadata = record?.getMetadata();
1281
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1109
1282
  }
1110
1283
 
1111
1284
  function isSortFilterString(value) {
@@ -1144,7 +1317,7 @@ var __privateAdd$4 = (obj, member, value) => {
1144
1317
  throw TypeError("Cannot add the same private member more than once");
1145
1318
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1146
1319
  };
1147
- var __privateSet$3 = (obj, member, value, setter) => {
1320
+ var __privateSet$4 = (obj, member, value, setter) => {
1148
1321
  __accessCheck$4(obj, member, "write to private field");
1149
1322
  setter ? setter.call(obj, value) : member.set(obj, value);
1150
1323
  return value;
@@ -1153,7 +1326,7 @@ var __privateMethod$2 = (obj, member, method) => {
1153
1326
  __accessCheck$4(obj, member, "access private method");
1154
1327
  return method;
1155
1328
  };
1156
- var _table, _getFetchProps, _cache, _schemaColumns, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _invalidateCache, invalidateCache_fn, _setCacheRecord, setCacheRecord_fn, _getCacheRecord, getCacheRecord_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaColumns, getSchemaColumns_fn;
1329
+ var _table, _getFetchProps, _db, _cache, _schemaTables$2, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaTables$1, getSchemaTables_fn$1;
1157
1330
  class Repository extends Query {
1158
1331
  }
1159
1332
  class RestRepository extends Query {
@@ -1165,111 +1338,122 @@ class RestRepository extends Query {
1165
1338
  __privateAdd$4(this, _updateRecordWithID);
1166
1339
  __privateAdd$4(this, _upsertRecordWithID);
1167
1340
  __privateAdd$4(this, _deleteRecord);
1168
- __privateAdd$4(this, _invalidateCache);
1169
- __privateAdd$4(this, _setCacheRecord);
1170
- __privateAdd$4(this, _getCacheRecord);
1171
1341
  __privateAdd$4(this, _setCacheQuery);
1172
1342
  __privateAdd$4(this, _getCacheQuery);
1173
- __privateAdd$4(this, _getSchemaColumns);
1343
+ __privateAdd$4(this, _getSchemaTables$1);
1174
1344
  __privateAdd$4(this, _table, void 0);
1175
1345
  __privateAdd$4(this, _getFetchProps, void 0);
1346
+ __privateAdd$4(this, _db, void 0);
1176
1347
  __privateAdd$4(this, _cache, void 0);
1177
- __privateAdd$4(this, _schemaColumns, void 0);
1178
- __privateSet$3(this, _table, options.table);
1179
- __privateSet$3(this, _getFetchProps, options.pluginOptions.getFetchProps);
1180
- this.db = options.db;
1181
- __privateSet$3(this, _cache, options.pluginOptions.cache);
1182
- }
1183
- async create(a, b) {
1348
+ __privateAdd$4(this, _schemaTables$2, void 0);
1349
+ __privateSet$4(this, _table, options.table);
1350
+ __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1351
+ __privateSet$4(this, _db, options.db);
1352
+ __privateSet$4(this, _cache, options.pluginOptions.cache);
1353
+ __privateSet$4(this, _schemaTables$2, options.schemaTables);
1354
+ }
1355
+ async create(a, b, c) {
1184
1356
  if (Array.isArray(a)) {
1185
- const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1186
- await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1187
- return records;
1357
+ if (a.length === 0)
1358
+ return [];
1359
+ const columns = isStringArray(b) ? b : void 0;
1360
+ return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
1188
1361
  }
1189
1362
  if (isString(a) && isObject(b)) {
1190
1363
  if (a === "")
1191
1364
  throw new Error("The id can't be empty");
1192
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1193
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1194
- return record;
1365
+ const columns = isStringArray(c) ? c : void 0;
1366
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns);
1195
1367
  }
1196
1368
  if (isObject(a) && isString(a.id)) {
1197
1369
  if (a.id === "")
1198
1370
  throw new Error("The id can't be empty");
1199
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1200
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1201
- return record;
1371
+ const columns = isStringArray(b) ? b : void 0;
1372
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1202
1373
  }
1203
1374
  if (isObject(a)) {
1204
- const record = await __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1205
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1206
- return record;
1375
+ const columns = isStringArray(b) ? b : void 0;
1376
+ return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
1207
1377
  }
1208
1378
  throw new Error("Invalid arguments for create method");
1209
1379
  }
1210
- async read(recordId) {
1211
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, recordId);
1212
- if (cacheRecord)
1213
- return cacheRecord;
1214
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1215
- try {
1216
- const response = await getRecord({
1217
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1218
- ...fetchProps
1219
- });
1220
- const columns = await __privateMethod$2(this, _getSchemaColumns, getSchemaColumns_fn).call(this);
1221
- return initObject(this.db, columns, __privateGet$4(this, _table), response);
1222
- } catch (e) {
1223
- if (isObject(e) && e.status === 404) {
1224
- return null;
1380
+ async read(a, b) {
1381
+ const columns = isStringArray(b) ? b : ["*"];
1382
+ if (Array.isArray(a)) {
1383
+ if (a.length === 0)
1384
+ return [];
1385
+ const ids = a.map((item) => isString(item) ? item : item.id).filter((id2) => isString(id2));
1386
+ const finalObjects = await this.getAll({ filter: { id: { $any: ids } }, columns });
1387
+ const dictionary = finalObjects.reduce((acc, object) => {
1388
+ acc[object.id] = object;
1389
+ return acc;
1390
+ }, {});
1391
+ return ids.map((id2) => dictionary[id2] ?? null);
1392
+ }
1393
+ const id = isString(a) ? a : a.id;
1394
+ if (isString(id)) {
1395
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1396
+ try {
1397
+ const response = await getRecord({
1398
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: id },
1399
+ queryParams: { columns },
1400
+ ...fetchProps
1401
+ });
1402
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1403
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1404
+ } catch (e) {
1405
+ if (isObject(e) && e.status === 404) {
1406
+ return null;
1407
+ }
1408
+ throw e;
1225
1409
  }
1226
- throw e;
1227
1410
  }
1411
+ return null;
1228
1412
  }
1229
- async update(a, b) {
1413
+ async update(a, b, c) {
1230
1414
  if (Array.isArray(a)) {
1415
+ if (a.length === 0)
1416
+ return [];
1231
1417
  if (a.length > 100) {
1232
1418
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1233
1419
  }
1234
- return Promise.all(a.map((object) => this.update(object)));
1420
+ const columns = isStringArray(b) ? b : ["*"];
1421
+ return Promise.all(a.map((object) => this.update(object, columns)));
1235
1422
  }
1236
1423
  if (isString(a) && isObject(b)) {
1237
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1238
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1239
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1240
- return record;
1424
+ const columns = isStringArray(c) ? c : void 0;
1425
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns);
1241
1426
  }
1242
1427
  if (isObject(a) && isString(a.id)) {
1243
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1244
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1245
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1246
- return record;
1428
+ const columns = isStringArray(b) ? b : void 0;
1429
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1247
1430
  }
1248
1431
  throw new Error("Invalid arguments for update method");
1249
1432
  }
1250
- async createOrUpdate(a, b) {
1433
+ async createOrUpdate(a, b, c) {
1251
1434
  if (Array.isArray(a)) {
1435
+ if (a.length === 0)
1436
+ return [];
1252
1437
  if (a.length > 100) {
1253
1438
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1254
1439
  }
1255
- return Promise.all(a.map((object) => this.createOrUpdate(object)));
1440
+ const columns = isStringArray(b) ? b : ["*"];
1441
+ return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
1256
1442
  }
1257
1443
  if (isString(a) && isObject(b)) {
1258
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1259
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1260
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1261
- return record;
1444
+ const columns = isStringArray(c) ? c : void 0;
1445
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns);
1262
1446
  }
1263
1447
  if (isObject(a) && isString(a.id)) {
1264
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1265
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1266
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1267
- return record;
1448
+ const columns = isStringArray(c) ? c : void 0;
1449
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1268
1450
  }
1269
1451
  throw new Error("Invalid arguments for createOrUpdate method");
1270
1452
  }
1271
1453
  async delete(a) {
1272
1454
  if (Array.isArray(a)) {
1455
+ if (a.length === 0)
1456
+ return;
1273
1457
  if (a.length > 100) {
1274
1458
  console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1275
1459
  }
@@ -1278,25 +1462,30 @@ class RestRepository extends Query {
1278
1462
  }
1279
1463
  if (isString(a)) {
1280
1464
  await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1281
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1282
1465
  return;
1283
1466
  }
1284
1467
  if (isObject(a) && isString(a.id)) {
1285
1468
  await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1286
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1287
1469
  return;
1288
1470
  }
1289
1471
  throw new Error("Invalid arguments for delete method");
1290
1472
  }
1291
1473
  async search(query, options = {}) {
1292
1474
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1293
- const { records } = await searchBranch({
1294
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1295
- body: { tables: [__privateGet$4(this, _table)], query, fuzziness: options.fuzziness },
1475
+ const { records } = await searchTable({
1476
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1477
+ body: {
1478
+ query,
1479
+ fuzziness: options.fuzziness,
1480
+ prefix: options.prefix,
1481
+ highlight: options.highlight,
1482
+ filter: options.filter,
1483
+ boosters: options.boosters
1484
+ },
1296
1485
  ...fetchProps
1297
1486
  });
1298
- const columns = await __privateMethod$2(this, _getSchemaColumns, getSchemaColumns_fn).call(this);
1299
- return records.map((item) => initObject(this.db, columns, __privateGet$4(this, _table), item));
1487
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1488
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1300
1489
  }
1301
1490
  async query(query) {
1302
1491
  const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
@@ -1305,8 +1494,8 @@ class RestRepository extends Query {
1305
1494
  const data = query.getQueryOptions();
1306
1495
  const body = {
1307
1496
  filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1308
- sort: data.sort ? buildSortFilter(data.sort) : void 0,
1309
- page: data.page,
1497
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1498
+ page: data.pagination,
1310
1499
  columns: data.columns
1311
1500
  };
1312
1501
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
@@ -1315,18 +1504,19 @@ class RestRepository extends Query {
1315
1504
  body,
1316
1505
  ...fetchProps
1317
1506
  });
1318
- const columns = await __privateMethod$2(this, _getSchemaColumns, getSchemaColumns_fn).call(this);
1319
- const records = objects.map((record) => initObject(this.db, columns, __privateGet$4(this, _table), record));
1507
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1508
+ const records = objects.map((record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record));
1320
1509
  await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1321
1510
  return new Page(query, meta, records);
1322
1511
  }
1323
1512
  }
1324
1513
  _table = new WeakMap();
1325
1514
  _getFetchProps = new WeakMap();
1515
+ _db = new WeakMap();
1326
1516
  _cache = new WeakMap();
1327
- _schemaColumns = new WeakMap();
1517
+ _schemaTables$2 = new WeakMap();
1328
1518
  _insertRecordWithoutId = new WeakSet();
1329
- insertRecordWithoutId_fn = async function(object) {
1519
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1330
1520
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1331
1521
  const record = transformObjectLinks(object);
1332
1522
  const response = await insertRecord({
@@ -1335,17 +1525,15 @@ insertRecordWithoutId_fn = async function(object) {
1335
1525
  dbBranchName: "{dbBranch}",
1336
1526
  tableName: __privateGet$4(this, _table)
1337
1527
  },
1528
+ queryParams: { columns },
1338
1529
  body: record,
1339
1530
  ...fetchProps
1340
1531
  });
1341
- const finalObject = await this.read(response.id);
1342
- if (!finalObject) {
1343
- throw new Error("The server failed to save the record");
1344
- }
1345
- return finalObject;
1532
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1533
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1346
1534
  };
1347
1535
  _insertRecordWithId = new WeakSet();
1348
- insertRecordWithId_fn = async function(recordId, object) {
1536
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
1349
1537
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1350
1538
  const record = transformObjectLinks(object);
1351
1539
  const response = await insertRecordWithID({
@@ -1356,56 +1544,52 @@ insertRecordWithId_fn = async function(recordId, object) {
1356
1544
  recordId
1357
1545
  },
1358
1546
  body: record,
1359
- queryParams: { createOnly: true },
1547
+ queryParams: { createOnly: true, columns },
1360
1548
  ...fetchProps
1361
1549
  });
1362
- const finalObject = await this.read(response.id);
1363
- if (!finalObject) {
1364
- throw new Error("The server failed to save the record");
1365
- }
1366
- return finalObject;
1550
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1551
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1367
1552
  };
1368
1553
  _bulkInsertTableRecords = new WeakSet();
1369
- bulkInsertTableRecords_fn = async function(objects) {
1554
+ bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
1370
1555
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1371
1556
  const records = objects.map((object) => transformObjectLinks(object));
1372
1557
  const response = await bulkInsertTableRecords({
1373
1558
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1559
+ queryParams: { columns },
1374
1560
  body: { records },
1375
1561
  ...fetchProps
1376
1562
  });
1377
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1378
- if (finalObjects.length !== objects.length) {
1379
- throw new Error("The server failed to save some records");
1563
+ if (!isResponseWithRecords(response)) {
1564
+ throw new Error("Request included columns but server didn't include them");
1380
1565
  }
1381
- return finalObjects;
1566
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1567
+ return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1382
1568
  };
1383
1569
  _updateRecordWithID = new WeakSet();
1384
- updateRecordWithID_fn = async function(recordId, object) {
1570
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1385
1571
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1386
1572
  const record = transformObjectLinks(object);
1387
1573
  const response = await updateRecordWithID({
1388
1574
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1575
+ queryParams: { columns },
1389
1576
  body: record,
1390
1577
  ...fetchProps
1391
1578
  });
1392
- const item = await this.read(response.id);
1393
- if (!item)
1394
- throw new Error("The server failed to save the record");
1395
- return item;
1579
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1580
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1396
1581
  };
1397
1582
  _upsertRecordWithID = new WeakSet();
1398
- upsertRecordWithID_fn = async function(recordId, object) {
1583
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1399
1584
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1400
1585
  const response = await upsertRecordWithID({
1401
1586
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1587
+ queryParams: { columns },
1402
1588
  body: object,
1403
1589
  ...fetchProps
1404
1590
  });
1405
- const item = await this.read(response.id);
1406
- if (!item)
1407
- throw new Error("The server failed to save the record");
1408
- return item;
1591
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1592
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1409
1593
  };
1410
1594
  _deleteRecord = new WeakSet();
1411
1595
  deleteRecord_fn = async function(recordId) {
@@ -1415,29 +1599,6 @@ deleteRecord_fn = async function(recordId) {
1415
1599
  ...fetchProps
1416
1600
  });
1417
1601
  };
1418
- _invalidateCache = new WeakSet();
1419
- invalidateCache_fn = async function(recordId) {
1420
- await __privateGet$4(this, _cache).delete(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1421
- const cacheItems = await __privateGet$4(this, _cache).getAll();
1422
- const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1423
- for (const [key, value] of queries) {
1424
- const ids = getIds(value);
1425
- if (ids.includes(recordId))
1426
- await __privateGet$4(this, _cache).delete(key);
1427
- }
1428
- };
1429
- _setCacheRecord = new WeakSet();
1430
- setCacheRecord_fn = async function(record) {
1431
- if (!__privateGet$4(this, _cache).cacheRecords)
1432
- return;
1433
- await __privateGet$4(this, _cache).set(`rec_${__privateGet$4(this, _table)}:${record.id}`, record);
1434
- };
1435
- _getCacheRecord = new WeakSet();
1436
- getCacheRecord_fn = async function(recordId) {
1437
- if (!__privateGet$4(this, _cache).cacheRecords)
1438
- return null;
1439
- return __privateGet$4(this, _cache).get(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1440
- };
1441
1602
  _setCacheQuery = new WeakSet();
1442
1603
  setCacheQuery_fn = async function(query, meta, records) {
1443
1604
  await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
@@ -1449,21 +1610,22 @@ getCacheQuery_fn = async function(query) {
1449
1610
  if (!result)
1450
1611
  return null;
1451
1612
  const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1452
- if (!ttl || ttl < 0)
1453
- return result;
1613
+ if (ttl < 0)
1614
+ return null;
1454
1615
  const hasExpired = result.date.getTime() + ttl < Date.now();
1455
1616
  return hasExpired ? null : result;
1456
1617
  };
1457
- _getSchemaColumns = new WeakSet();
1458
- getSchemaColumns_fn = async function() {
1459
- if (__privateGet$4(this, _schemaColumns))
1460
- return __privateGet$4(this, _schemaColumns);
1461
- const { columns } = await getTableSchema({
1462
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1463
- ...await __privateGet$4(this, _getFetchProps).call(this)
1618
+ _getSchemaTables$1 = new WeakSet();
1619
+ getSchemaTables_fn$1 = async function() {
1620
+ if (__privateGet$4(this, _schemaTables$2))
1621
+ return __privateGet$4(this, _schemaTables$2);
1622
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1623
+ const { schema } = await getBranchDetails({
1624
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1625
+ ...fetchProps
1464
1626
  });
1465
- __privateSet$3(this, _schemaColumns, columns);
1466
- return columns;
1627
+ __privateSet$4(this, _schemaTables$2, schema.tables);
1628
+ return schema.tables;
1467
1629
  };
1468
1630
  const transformObjectLinks = (object) => {
1469
1631
  return Object.entries(object).reduce((acc, [key, value]) => {
@@ -1472,17 +1634,21 @@ const transformObjectLinks = (object) => {
1472
1634
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1473
1635
  }, {});
1474
1636
  };
1475
- const initObject = (db, columns, table, object) => {
1637
+ const initObject = (db, schemaTables, table, object) => {
1476
1638
  const result = {};
1477
- Object.assign(result, object);
1478
- for (const column of columns) {
1639
+ const { xata, ...rest } = object ?? {};
1640
+ Object.assign(result, rest);
1641
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
1642
+ if (!columns)
1643
+ console.error(`Table ${table} not found in schema`);
1644
+ for (const column of columns ?? []) {
1479
1645
  const value = result[column.name];
1480
1646
  switch (column.type) {
1481
1647
  case "datetime": {
1482
- const date = new Date(value);
1483
- if (isNaN(date.getTime())) {
1648
+ const date = value !== void 0 ? new Date(value) : void 0;
1649
+ if (date && isNaN(date.getTime())) {
1484
1650
  console.error(`Failed to parse date ${value} for field ${column.name}`);
1485
- } else {
1651
+ } else if (date) {
1486
1652
  result[column.name] = date;
1487
1653
  }
1488
1654
  break;
@@ -1491,36 +1657,33 @@ const initObject = (db, columns, table, object) => {
1491
1657
  const linkTable = column.link?.table;
1492
1658
  if (!linkTable) {
1493
1659
  console.error(`Failed to parse link for field ${column.name}`);
1494
- } else if (value && isObject(value)) {
1495
- result[column.name] = initObject(db, columns, linkTable, value);
1660
+ } else if (isObject(value)) {
1661
+ result[column.name] = initObject(db, schemaTables, linkTable, value);
1496
1662
  }
1497
1663
  break;
1498
1664
  }
1499
1665
  }
1500
1666
  }
1501
- result.read = function() {
1502
- return db[table].read(result["id"]);
1667
+ result.read = function(columns2) {
1668
+ return db[table].read(result["id"], columns2);
1503
1669
  };
1504
- result.update = function(data) {
1505
- return db[table].update(result["id"], data);
1670
+ result.update = function(data, columns2) {
1671
+ return db[table].update(result["id"], data, columns2);
1506
1672
  };
1507
1673
  result.delete = function() {
1508
1674
  return db[table].delete(result["id"]);
1509
1675
  };
1510
- for (const prop of ["read", "update", "delete"]) {
1676
+ result.getMetadata = function() {
1677
+ return xata;
1678
+ };
1679
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1511
1680
  Object.defineProperty(result, prop, { enumerable: false });
1512
1681
  }
1513
1682
  Object.freeze(result);
1514
1683
  return result;
1515
1684
  };
1516
- function getIds(value) {
1517
- if (Array.isArray(value)) {
1518
- return value.map((item) => getIds(item)).flat();
1519
- }
1520
- if (!isObject(value))
1521
- return [];
1522
- const nestedIds = Object.values(value).map((item) => getIds(item)).flat();
1523
- return isString(value.id) ? [value.id, ...nestedIds] : nestedIds;
1685
+ function isResponseWithRecords(value) {
1686
+ return isObject(value) && Array.isArray(value.records);
1524
1687
  }
1525
1688
 
1526
1689
  var __accessCheck$3 = (obj, member, msg) => {
@@ -1536,7 +1699,7 @@ var __privateAdd$3 = (obj, member, value) => {
1536
1699
  throw TypeError("Cannot add the same private member more than once");
1537
1700
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1538
1701
  };
1539
- var __privateSet$2 = (obj, member, value, setter) => {
1702
+ var __privateSet$3 = (obj, member, value, setter) => {
1540
1703
  __accessCheck$3(obj, member, "write to private field");
1541
1704
  setter ? setter.call(obj, value) : member.set(obj, value);
1542
1705
  return value;
@@ -1545,9 +1708,8 @@ var _map;
1545
1708
  class SimpleCache {
1546
1709
  constructor(options = {}) {
1547
1710
  __privateAdd$3(this, _map, void 0);
1548
- __privateSet$2(this, _map, /* @__PURE__ */ new Map());
1711
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1549
1712
  this.capacity = options.max ?? 500;
1550
- this.cacheRecords = options.cacheRecords ?? true;
1551
1713
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1552
1714
  }
1553
1715
  async getAll() {
@@ -1605,31 +1767,42 @@ var __privateAdd$2 = (obj, member, value) => {
1605
1767
  throw TypeError("Cannot add the same private member more than once");
1606
1768
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1607
1769
  };
1608
- var _tables;
1770
+ var __privateSet$2 = (obj, member, value, setter) => {
1771
+ __accessCheck$2(obj, member, "write to private field");
1772
+ setter ? setter.call(obj, value) : member.set(obj, value);
1773
+ return value;
1774
+ };
1775
+ var _tables, _schemaTables$1;
1609
1776
  class SchemaPlugin extends XataPlugin {
1610
- constructor(tableNames) {
1777
+ constructor(schemaTables) {
1611
1778
  super();
1612
- this.tableNames = tableNames;
1613
1779
  __privateAdd$2(this, _tables, {});
1780
+ __privateAdd$2(this, _schemaTables$1, void 0);
1781
+ __privateSet$2(this, _schemaTables$1, schemaTables);
1614
1782
  }
1615
1783
  build(pluginOptions) {
1616
- const db = new Proxy({}, {
1617
- get: (_target, table) => {
1618
- if (!isString(table))
1619
- throw new Error("Invalid table name");
1620
- if (!__privateGet$2(this, _tables)[table]) {
1621
- __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table });
1784
+ const db = new Proxy(
1785
+ {},
1786
+ {
1787
+ get: (_target, table) => {
1788
+ if (!isString(table))
1789
+ throw new Error("Invalid table name");
1790
+ if (__privateGet$2(this, _tables)[table] === void 0) {
1791
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1792
+ }
1793
+ return __privateGet$2(this, _tables)[table];
1622
1794
  }
1623
- return __privateGet$2(this, _tables)[table];
1624
1795
  }
1625
- });
1626
- for (const table of this.tableNames ?? []) {
1627
- db[table] = new RestRepository({ db, pluginOptions, table });
1796
+ );
1797
+ const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
1798
+ for (const table of tableNames) {
1799
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1628
1800
  }
1629
1801
  return db;
1630
1802
  }
1631
1803
  }
1632
1804
  _tables = new WeakMap();
1805
+ _schemaTables$1 = new WeakMap();
1633
1806
 
1634
1807
  var __accessCheck$1 = (obj, member, msg) => {
1635
1808
  if (!member.has(obj))
@@ -1653,113 +1826,118 @@ var __privateMethod$1 = (obj, member, method) => {
1653
1826
  __accessCheck$1(obj, member, "access private method");
1654
1827
  return method;
1655
1828
  };
1656
- var _schema, _search, search_fn, _getSchema, getSchema_fn;
1829
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1657
1830
  class SearchPlugin extends XataPlugin {
1658
- constructor(db) {
1831
+ constructor(db, schemaTables) {
1659
1832
  super();
1660
1833
  this.db = db;
1661
1834
  __privateAdd$1(this, _search);
1662
- __privateAdd$1(this, _getSchema);
1663
- __privateAdd$1(this, _schema, void 0);
1835
+ __privateAdd$1(this, _getSchemaTables);
1836
+ __privateAdd$1(this, _schemaTables, void 0);
1837
+ __privateSet$1(this, _schemaTables, schemaTables);
1664
1838
  }
1665
1839
  build({ getFetchProps }) {
1666
1840
  return {
1667
1841
  all: async (query, options = {}) => {
1668
1842
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1669
- const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
1843
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1670
1844
  return records.map((record) => {
1671
1845
  const { table = "orphan" } = record.xata;
1672
- const columns = schema.tables.find((t) => t.name === table)?.columns;
1673
- if (!columns) {
1674
- console.error(`No schema columns found for table ${table}`);
1675
- }
1676
- return { table, record: initObject(this.db, columns ?? [], table, record) };
1846
+ return { table, record: initObject(this.db, schemaTables, table, record) };
1677
1847
  });
1678
1848
  },
1679
1849
  byTable: async (query, options = {}) => {
1680
1850
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1681
- const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
1851
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1682
1852
  return records.reduce((acc, record) => {
1683
1853
  const { table = "orphan" } = record.xata;
1684
- const columns = schema.tables.find((t) => t.name === table)?.columns;
1685
- if (!columns) {
1686
- console.error(`No schema columns found for table ${table}`);
1687
- }
1688
1854
  const items = acc[table] ?? [];
1689
- const item = initObject(this.db, columns ?? [], table, record);
1855
+ const item = initObject(this.db, schemaTables, table, record);
1690
1856
  return { ...acc, [table]: [...items, item] };
1691
1857
  }, {});
1692
1858
  }
1693
1859
  };
1694
1860
  }
1695
1861
  }
1696
- _schema = new WeakMap();
1862
+ _schemaTables = new WeakMap();
1697
1863
  _search = new WeakSet();
1698
1864
  search_fn = async function(query, options, getFetchProps) {
1699
1865
  const fetchProps = await getFetchProps();
1700
- const { tables, fuzziness } = options ?? {};
1866
+ const { tables, fuzziness, highlight, prefix } = options ?? {};
1701
1867
  const { records } = await searchBranch({
1702
1868
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1703
- body: { tables, query, fuzziness },
1869
+ body: { tables, query, fuzziness, prefix, highlight },
1704
1870
  ...fetchProps
1705
1871
  });
1706
1872
  return records;
1707
1873
  };
1708
- _getSchema = new WeakSet();
1709
- getSchema_fn = async function(getFetchProps) {
1710
- if (__privateGet$1(this, _schema))
1711
- return __privateGet$1(this, _schema);
1874
+ _getSchemaTables = new WeakSet();
1875
+ getSchemaTables_fn = async function(getFetchProps) {
1876
+ if (__privateGet$1(this, _schemaTables))
1877
+ return __privateGet$1(this, _schemaTables);
1712
1878
  const fetchProps = await getFetchProps();
1713
1879
  const { schema } = await getBranchDetails({
1714
1880
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1715
1881
  ...fetchProps
1716
1882
  });
1717
- __privateSet$1(this, _schema, schema);
1718
- return schema;
1883
+ __privateSet$1(this, _schemaTables, schema.tables);
1884
+ return schema.tables;
1719
1885
  };
1720
1886
 
1721
1887
  const isBranchStrategyBuilder = (strategy) => {
1722
1888
  return typeof strategy === "function";
1723
1889
  };
1724
1890
 
1725
- const envBranchNames = [
1726
- "XATA_BRANCH",
1727
- "VERCEL_GIT_COMMIT_REF",
1728
- "CF_PAGES_BRANCH",
1729
- "BRANCH"
1730
- ];
1731
- const defaultBranch = "main";
1732
1891
  async function getCurrentBranchName(options) {
1733
- const env = await getBranchByEnvVariable();
1734
- if (env)
1735
- return env;
1736
- const branch = await getGitBranch();
1737
- if (!branch)
1738
- return defaultBranch;
1739
- const details = await getDatabaseBranch(branch, options);
1740
- if (details)
1741
- return branch;
1742
- return defaultBranch;
1892
+ const { branch, envBranch } = getEnvironment();
1893
+ if (branch) {
1894
+ const details = await getDatabaseBranch(branch, options);
1895
+ if (details)
1896
+ return branch;
1897
+ console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
1898
+ }
1899
+ const gitBranch = envBranch || await getGitBranch();
1900
+ return resolveXataBranch(gitBranch, options);
1743
1901
  }
1744
1902
  async function getCurrentBranchDetails(options) {
1745
- const env = await getBranchByEnvVariable();
1746
- if (env)
1747
- return getDatabaseBranch(env, options);
1748
- const branch = await getGitBranch();
1749
- if (!branch)
1750
- return getDatabaseBranch(defaultBranch, options);
1751
- const details = await getDatabaseBranch(branch, options);
1752
- if (details)
1753
- return details;
1754
- return getDatabaseBranch(defaultBranch, options);
1903
+ const branch = await getCurrentBranchName(options);
1904
+ return getDatabaseBranch(branch, options);
1905
+ }
1906
+ async function resolveXataBranch(gitBranch, options) {
1907
+ const databaseURL = options?.databaseURL || getDatabaseURL();
1908
+ const apiKey = options?.apiKey || getAPIKey();
1909
+ if (!databaseURL)
1910
+ throw new Error(
1911
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
1912
+ );
1913
+ if (!apiKey)
1914
+ throw new Error(
1915
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
1916
+ );
1917
+ const [protocol, , host, , dbName] = databaseURL.split("/");
1918
+ const [workspace] = host.split(".");
1919
+ const { fallbackBranch } = getEnvironment();
1920
+ const { branch } = await resolveBranch({
1921
+ apiKey,
1922
+ apiUrl: databaseURL,
1923
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
1924
+ workspacesApiUrl: `${protocol}//${host}`,
1925
+ pathParams: { dbName, workspace },
1926
+ queryParams: { gitBranch, fallbackBranch }
1927
+ });
1928
+ return branch;
1755
1929
  }
1756
1930
  async function getDatabaseBranch(branch, options) {
1757
1931
  const databaseURL = options?.databaseURL || getDatabaseURL();
1758
1932
  const apiKey = options?.apiKey || getAPIKey();
1759
1933
  if (!databaseURL)
1760
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
1934
+ throw new Error(
1935
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
1936
+ );
1761
1937
  if (!apiKey)
1762
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
1938
+ throw new Error(
1939
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
1940
+ );
1763
1941
  const [protocol, , host, , database] = databaseURL.split("/");
1764
1942
  const [workspace] = host.split(".");
1765
1943
  const dbBranchName = `${database}:${branch}`;
@@ -1769,10 +1947,7 @@ async function getDatabaseBranch(branch, options) {
1769
1947
  apiUrl: databaseURL,
1770
1948
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1771
1949
  workspacesApiUrl: `${protocol}//${host}`,
1772
- pathParams: {
1773
- dbBranchName,
1774
- workspace
1775
- }
1950
+ pathParams: { dbBranchName, workspace }
1776
1951
  });
1777
1952
  } catch (err) {
1778
1953
  if (isObject(err) && err.status === 404)
@@ -1780,21 +1955,10 @@ async function getDatabaseBranch(branch, options) {
1780
1955
  throw err;
1781
1956
  }
1782
1957
  }
1783
- function getBranchByEnvVariable() {
1784
- for (const name of envBranchNames) {
1785
- const value = getEnvVariable(name);
1786
- if (value) {
1787
- return value;
1788
- }
1789
- }
1790
- try {
1791
- return XATA_BRANCH;
1792
- } catch (err) {
1793
- }
1794
- }
1795
1958
  function getDatabaseURL() {
1796
1959
  try {
1797
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
1960
+ const { databaseURL } = getEnvironment();
1961
+ return databaseURL;
1798
1962
  } catch (err) {
1799
1963
  return void 0;
1800
1964
  }
@@ -1823,24 +1987,26 @@ var __privateMethod = (obj, member, method) => {
1823
1987
  return method;
1824
1988
  };
1825
1989
  const buildClient = (plugins) => {
1826
- var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1990
+ var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1827
1991
  return _a = class {
1828
- constructor(options = {}, tables) {
1992
+ constructor(options = {}, schemaTables) {
1829
1993
  __privateAdd(this, _parseOptions);
1830
1994
  __privateAdd(this, _getFetchProps);
1831
1995
  __privateAdd(this, _evaluateBranch);
1832
1996
  __privateAdd(this, _branch, void 0);
1997
+ __privateAdd(this, _options, void 0);
1833
1998
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
1999
+ __privateSet(this, _options, safeOptions);
1834
2000
  const pluginOptions = {
1835
2001
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1836
2002
  cache: safeOptions.cache
1837
2003
  };
1838
- const db = new SchemaPlugin(tables).build(pluginOptions);
1839
- const search = new SearchPlugin(db).build(pluginOptions);
2004
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2005
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1840
2006
  this.db = db;
1841
2007
  this.search = search;
1842
2008
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
1843
- if (!namespace)
2009
+ if (namespace === void 0)
1844
2010
  continue;
1845
2011
  const result = namespace.build(pluginOptions);
1846
2012
  if (result instanceof Promise) {
@@ -1852,22 +2018,22 @@ const buildClient = (plugins) => {
1852
2018
  }
1853
2019
  }
1854
2020
  }
1855
- }, _branch = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
2021
+ async getConfig() {
2022
+ const databaseURL = __privateGet(this, _options).databaseURL;
2023
+ const branch = await __privateGet(this, _options).branch();
2024
+ return { databaseURL, branch };
2025
+ }
2026
+ }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
1856
2027
  const fetch = getFetchImplementation(options?.fetch);
1857
2028
  const databaseURL = options?.databaseURL || getDatabaseURL();
1858
2029
  const apiKey = options?.apiKey || getAPIKey();
1859
- const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
1860
- const branch = async () => options?.branch ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
2030
+ const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
2031
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1861
2032
  if (!databaseURL || !apiKey) {
1862
2033
  throw new Error("Options databaseURL and apiKey are required");
1863
2034
  }
1864
2035
  return { fetch, databaseURL, apiKey, branch, cache };
1865
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
1866
- fetch,
1867
- apiKey,
1868
- databaseURL,
1869
- branch
1870
- }) {
2036
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch }) {
1871
2037
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
1872
2038
  if (!branchValue)
1873
2039
  throw new Error("Unable to resolve branch value");
@@ -1884,7 +2050,7 @@ const buildClient = (plugins) => {
1884
2050
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1885
2051
  if (__privateGet(this, _branch))
1886
2052
  return __privateGet(this, _branch);
1887
- if (!param)
2053
+ if (param === void 0)
1888
2054
  return void 0;
1889
2055
  const strategies = Array.isArray(param) ? [...param] : [param];
1890
2056
  const evaluateBranch = async (strategy) => {
@@ -1902,6 +2068,88 @@ const buildClient = (plugins) => {
1902
2068
  class BaseClient extends buildClient() {
1903
2069
  }
1904
2070
 
2071
+ const META = "__";
2072
+ const VALUE = "___";
2073
+ class Serializer {
2074
+ constructor() {
2075
+ this.classes = {};
2076
+ }
2077
+ add(clazz) {
2078
+ this.classes[clazz.name] = clazz;
2079
+ }
2080
+ toJSON(data) {
2081
+ function visit(obj) {
2082
+ if (Array.isArray(obj))
2083
+ return obj.map(visit);
2084
+ const type = typeof obj;
2085
+ if (type === "undefined")
2086
+ return { [META]: "undefined" };
2087
+ if (type === "bigint")
2088
+ return { [META]: "bigint", [VALUE]: obj.toString() };
2089
+ if (obj === null || type !== "object")
2090
+ return obj;
2091
+ const constructor = obj.constructor;
2092
+ const o = { [META]: constructor.name };
2093
+ for (const [key, value] of Object.entries(obj)) {
2094
+ o[key] = visit(value);
2095
+ }
2096
+ if (constructor === Date)
2097
+ o[VALUE] = obj.toISOString();
2098
+ if (constructor === Map)
2099
+ o[VALUE] = Object.fromEntries(obj);
2100
+ if (constructor === Set)
2101
+ o[VALUE] = [...obj];
2102
+ return o;
2103
+ }
2104
+ return JSON.stringify(visit(data));
2105
+ }
2106
+ fromJSON(json) {
2107
+ return JSON.parse(json, (key, value) => {
2108
+ if (value && typeof value === "object" && !Array.isArray(value)) {
2109
+ const { [META]: clazz, [VALUE]: val, ...rest } = value;
2110
+ const constructor = this.classes[clazz];
2111
+ if (constructor) {
2112
+ return Object.assign(Object.create(constructor.prototype), rest);
2113
+ }
2114
+ if (clazz === "Date")
2115
+ return new Date(val);
2116
+ if (clazz === "Set")
2117
+ return new Set(val);
2118
+ if (clazz === "Map")
2119
+ return new Map(Object.entries(val));
2120
+ if (clazz === "bigint")
2121
+ return BigInt(val);
2122
+ if (clazz === "undefined")
2123
+ return void 0;
2124
+ return rest;
2125
+ }
2126
+ return value;
2127
+ });
2128
+ }
2129
+ }
2130
+ const defaultSerializer = new Serializer();
2131
+ const serialize = (data) => {
2132
+ return defaultSerializer.toJSON(data);
2133
+ };
2134
+ const deserialize = (json) => {
2135
+ return defaultSerializer.fromJSON(json);
2136
+ };
2137
+
2138
+ function buildWorkerRunner(config) {
2139
+ return function xataWorker(name, _worker) {
2140
+ return async (...args) => {
2141
+ const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
2142
+ const result = await fetch(url, {
2143
+ method: "POST",
2144
+ headers: { "Content-Type": "application/json" },
2145
+ body: serialize({ args })
2146
+ });
2147
+ const text = await result.text();
2148
+ return deserialize(text);
2149
+ };
2150
+ };
2151
+ }
2152
+
1905
2153
  class XataError extends Error {
1906
2154
  constructor(message, status) {
1907
2155
  super(message);
@@ -1909,5 +2157,5 @@ class XataError extends Error {
1909
2157
  }
1910
2158
  }
1911
2159
 
1912
- export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, Repository, RestRepository, SchemaPlugin, SearchPlugin, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, buildClient, bulkInsertTableRecords, cancelWorkspaceMemberInvite, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, endsWith, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseURL, getGitBranchesMapping, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isIdentifiable, isNot, isXataRecord, le, lt, lte, notExists, operationsByTag, pattern, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberRole, upsertRecordWithID };
2160
+ export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, Serializer, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, buildClient, buildWorkerRunner, bulkInsertTableRecords, cancelWorkspaceMemberInvite, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, deserialize, endsWith, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseMetadata, getDatabaseURL, getGitBranchesMapping, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isIdentifiable, isNot, isXataRecord, le, lt, lte, notExists, operationsByTag, pattern, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, serialize, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID };
1913
2161
  //# sourceMappingURL=index.mjs.map