@xata.io/client 0.0.0-alpha.vfb4a018 → 0.0.0-alpha.vfd6aaf3

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
@@ -11,14 +11,18 @@ function compact(arr) {
11
11
  function isObject(value) {
12
12
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
13
13
  }
14
+ function isDefined(value) {
15
+ return value !== null && value !== void 0;
16
+ }
14
17
  function isString(value) {
15
- return value !== void 0 && value !== null && typeof value === "string";
18
+ return isDefined(value) && typeof value === "string";
16
19
  }
17
20
  function toBase64(value) {
18
21
  try {
19
22
  return btoa(value);
20
23
  } catch (err) {
21
- return Buffer.from(value).toString("base64");
24
+ const buf = Buffer;
25
+ return buf.from(value).toString("base64");
22
26
  }
23
27
  }
24
28
 
@@ -74,16 +78,28 @@ function getFetchImplementation(userFetch) {
74
78
  return fetchImpl;
75
79
  }
76
80
 
77
- class FetcherError extends Error {
78
- constructor(status, data) {
81
+ const VERSION = "0.0.0-alpha.vfd6aaf3";
82
+
83
+ class ErrorWithCause extends Error {
84
+ constructor(message, options) {
85
+ super(message, options);
86
+ }
87
+ }
88
+ class FetcherError extends ErrorWithCause {
89
+ constructor(status, data, requestId) {
79
90
  super(getMessage(data));
80
91
  this.status = status;
81
92
  this.errors = isBulkError(data) ? data.errors : void 0;
93
+ this.requestId = requestId;
82
94
  if (data instanceof Error) {
83
95
  this.stack = data.stack;
84
96
  this.cause = data.cause;
85
97
  }
86
98
  }
99
+ toString() {
100
+ const error = super.toString();
101
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
102
+ }
87
103
  }
88
104
  function isBulkError(error) {
89
105
  return isObject(error) && Array.isArray(error.errors);
@@ -106,7 +122,12 @@ function getMessage(data) {
106
122
  }
107
123
 
108
124
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
109
- const query = new URLSearchParams(queryParams).toString();
125
+ const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
126
+ if (value === void 0 || value === null)
127
+ return acc;
128
+ return { ...acc, [key]: value };
129
+ }, {});
130
+ const query = new URLSearchParams(cleanQueryParams).toString();
110
131
  const queryString = query.length > 0 ? `?${query}` : "";
111
132
  return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
112
133
  };
@@ -146,6 +167,7 @@ async function fetch$1({
146
167
  body: body ? JSON.stringify(body) : void 0,
147
168
  headers: {
148
169
  "Content-Type": "application/json",
170
+ "User-Agent": `Xata client-ts/${VERSION}`,
149
171
  ...headers,
150
172
  ...hostHeader(fullUrl),
151
173
  Authorization: `Bearer ${apiKey}`
@@ -154,14 +176,15 @@ async function fetch$1({
154
176
  if (response.status === 204) {
155
177
  return {};
156
178
  }
179
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
157
180
  try {
158
181
  const jsonResponse = await response.json();
159
182
  if (response.ok) {
160
183
  return jsonResponse;
161
184
  }
162
- throw new FetcherError(response.status, jsonResponse);
185
+ throw new FetcherError(response.status, jsonResponse, requestId);
163
186
  } catch (error) {
164
- throw new FetcherError(response.status, error);
187
+ throw new FetcherError(response.status, error, requestId);
165
188
  }
166
189
  }
167
190
 
@@ -370,6 +393,11 @@ const queryTable = (variables) => fetch$1({
370
393
  method: "post",
371
394
  ...variables
372
395
  });
396
+ const searchTable = (variables) => fetch$1({
397
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
398
+ method: "post",
399
+ ...variables
400
+ });
373
401
  const searchBranch = (variables) => fetch$1({
374
402
  url: "/db/{dbBranchName}/search",
375
403
  method: "post",
@@ -433,6 +461,7 @@ const operationsByTag = {
433
461
  getRecord,
434
462
  bulkInsertTableRecords,
435
463
  queryTable,
464
+ searchTable,
436
465
  searchBranch
437
466
  }
438
467
  };
@@ -466,7 +495,7 @@ var __accessCheck$7 = (obj, member, msg) => {
466
495
  if (!member.has(obj))
467
496
  throw TypeError("Cannot " + msg);
468
497
  };
469
- var __privateGet$6 = (obj, member, getter) => {
498
+ var __privateGet$7 = (obj, member, getter) => {
470
499
  __accessCheck$7(obj, member, "read from private field");
471
500
  return getter ? getter.call(obj) : member.get(obj);
472
501
  };
@@ -475,7 +504,7 @@ var __privateAdd$7 = (obj, member, value) => {
475
504
  throw TypeError("Cannot add the same private member more than once");
476
505
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
477
506
  };
478
- var __privateSet$5 = (obj, member, value, setter) => {
507
+ var __privateSet$6 = (obj, member, value, setter) => {
479
508
  __accessCheck$7(obj, member, "write to private field");
480
509
  setter ? setter.call(obj, value) : member.set(obj, value);
481
510
  return value;
@@ -490,7 +519,7 @@ class XataApiClient {
490
519
  if (!apiKey) {
491
520
  throw new Error("Could not resolve a valid apiKey");
492
521
  }
493
- __privateSet$5(this, _extraProps, {
522
+ __privateSet$6(this, _extraProps, {
494
523
  apiUrl: getHostUrl(provider, "main"),
495
524
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
496
525
  fetchImpl: getFetchImplementation(options.fetch),
@@ -498,34 +527,34 @@ class XataApiClient {
498
527
  });
499
528
  }
500
529
  get user() {
501
- if (!__privateGet$6(this, _namespaces).user)
502
- __privateGet$6(this, _namespaces).user = new UserApi(__privateGet$6(this, _extraProps));
503
- return __privateGet$6(this, _namespaces).user;
530
+ if (!__privateGet$7(this, _namespaces).user)
531
+ __privateGet$7(this, _namespaces).user = new UserApi(__privateGet$7(this, _extraProps));
532
+ return __privateGet$7(this, _namespaces).user;
504
533
  }
505
534
  get workspaces() {
506
- if (!__privateGet$6(this, _namespaces).workspaces)
507
- __privateGet$6(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$6(this, _extraProps));
508
- return __privateGet$6(this, _namespaces).workspaces;
535
+ if (!__privateGet$7(this, _namespaces).workspaces)
536
+ __privateGet$7(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$7(this, _extraProps));
537
+ return __privateGet$7(this, _namespaces).workspaces;
509
538
  }
510
539
  get databases() {
511
- if (!__privateGet$6(this, _namespaces).databases)
512
- __privateGet$6(this, _namespaces).databases = new DatabaseApi(__privateGet$6(this, _extraProps));
513
- return __privateGet$6(this, _namespaces).databases;
540
+ if (!__privateGet$7(this, _namespaces).databases)
541
+ __privateGet$7(this, _namespaces).databases = new DatabaseApi(__privateGet$7(this, _extraProps));
542
+ return __privateGet$7(this, _namespaces).databases;
514
543
  }
515
544
  get branches() {
516
- if (!__privateGet$6(this, _namespaces).branches)
517
- __privateGet$6(this, _namespaces).branches = new BranchApi(__privateGet$6(this, _extraProps));
518
- return __privateGet$6(this, _namespaces).branches;
545
+ if (!__privateGet$7(this, _namespaces).branches)
546
+ __privateGet$7(this, _namespaces).branches = new BranchApi(__privateGet$7(this, _extraProps));
547
+ return __privateGet$7(this, _namespaces).branches;
519
548
  }
520
549
  get tables() {
521
- if (!__privateGet$6(this, _namespaces).tables)
522
- __privateGet$6(this, _namespaces).tables = new TableApi(__privateGet$6(this, _extraProps));
523
- return __privateGet$6(this, _namespaces).tables;
550
+ if (!__privateGet$7(this, _namespaces).tables)
551
+ __privateGet$7(this, _namespaces).tables = new TableApi(__privateGet$7(this, _extraProps));
552
+ return __privateGet$7(this, _namespaces).tables;
524
553
  }
525
554
  get records() {
526
- if (!__privateGet$6(this, _namespaces).records)
527
- __privateGet$6(this, _namespaces).records = new RecordsApi(__privateGet$6(this, _extraProps));
528
- return __privateGet$6(this, _namespaces).records;
555
+ if (!__privateGet$7(this, _namespaces).records)
556
+ __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
557
+ return __privateGet$7(this, _namespaces).records;
529
558
  }
530
559
  }
531
560
  _extraProps = new WeakMap();
@@ -679,10 +708,10 @@ class DatabaseApi {
679
708
  ...this.extraProps
680
709
  });
681
710
  }
682
- resolveBranch(workspace, dbName, gitBranch) {
711
+ resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
683
712
  return operationsByTag.database.resolveBranch({
684
713
  pathParams: { workspace, dbName },
685
- queryParams: { gitBranch },
714
+ queryParams: { gitBranch, fallbackBranch },
686
715
  ...this.extraProps
687
716
  });
688
717
  }
@@ -703,10 +732,10 @@ class BranchApi {
703
732
  ...this.extraProps
704
733
  });
705
734
  }
706
- createBranch(workspace, database, branch, from = "", options = {}) {
735
+ createBranch(workspace, database, branch, from, options = {}) {
707
736
  return operationsByTag.branch.createBranch({
708
737
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
709
- queryParams: { from },
738
+ queryParams: isString(from) ? { from } : void 0,
710
739
  body: options,
711
740
  ...this.extraProps
712
741
  });
@@ -888,6 +917,13 @@ class RecordsApi {
888
917
  ...this.extraProps
889
918
  });
890
919
  }
920
+ searchTable(workspace, database, branch, tableName, query) {
921
+ return operationsByTag.records.searchTable({
922
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
923
+ body: query,
924
+ ...this.extraProps
925
+ });
926
+ }
891
927
  searchBranch(workspace, database, branch, query) {
892
928
  return operationsByTag.records.searchBranch({
893
929
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -911,7 +947,7 @@ var __accessCheck$6 = (obj, member, msg) => {
911
947
  if (!member.has(obj))
912
948
  throw TypeError("Cannot " + msg);
913
949
  };
914
- var __privateGet$5 = (obj, member, getter) => {
950
+ var __privateGet$6 = (obj, member, getter) => {
915
951
  __accessCheck$6(obj, member, "read from private field");
916
952
  return getter ? getter.call(obj) : member.get(obj);
917
953
  };
@@ -920,30 +956,30 @@ var __privateAdd$6 = (obj, member, value) => {
920
956
  throw TypeError("Cannot add the same private member more than once");
921
957
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
922
958
  };
923
- var __privateSet$4 = (obj, member, value, setter) => {
959
+ var __privateSet$5 = (obj, member, value, setter) => {
924
960
  __accessCheck$6(obj, member, "write to private field");
925
961
  setter ? setter.call(obj, value) : member.set(obj, value);
926
962
  return value;
927
963
  };
928
- var _query;
964
+ var _query, _page;
929
965
  class Page {
930
966
  constructor(query, meta, records = []) {
931
967
  __privateAdd$6(this, _query, void 0);
932
- __privateSet$4(this, _query, query);
968
+ __privateSet$5(this, _query, query);
933
969
  this.meta = meta;
934
- this.records = records;
970
+ this.records = new RecordArray(this, records);
935
971
  }
936
972
  async nextPage(size, offset) {
937
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, after: this.meta.page.cursor } });
973
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
938
974
  }
939
975
  async previousPage(size, offset) {
940
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, before: this.meta.page.cursor } });
976
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
941
977
  }
942
978
  async firstPage(size, offset) {
943
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, first: this.meta.page.cursor } });
979
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
944
980
  }
945
981
  async lastPage(size, offset) {
946
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, last: this.meta.page.cursor } });
982
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
947
983
  }
948
984
  hasNextPage() {
949
985
  return this.meta.page.more;
@@ -951,15 +987,56 @@ class Page {
951
987
  }
952
988
  _query = new WeakMap();
953
989
  const PAGINATION_MAX_SIZE = 200;
954
- const PAGINATION_DEFAULT_SIZE = 200;
990
+ const PAGINATION_DEFAULT_SIZE = 20;
955
991
  const PAGINATION_MAX_OFFSET = 800;
956
992
  const PAGINATION_DEFAULT_OFFSET = 0;
993
+ function isCursorPaginationOptions(options) {
994
+ return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
995
+ }
996
+ const _RecordArray = class extends Array {
997
+ constructor(page, overrideRecords) {
998
+ super(..._RecordArray.parseConstructorParams(page, overrideRecords));
999
+ __privateAdd$6(this, _page, void 0);
1000
+ __privateSet$5(this, _page, page);
1001
+ }
1002
+ static parseConstructorParams(...args) {
1003
+ if (args.length === 1 && typeof args[0] === "number") {
1004
+ return new Array(args[0]);
1005
+ }
1006
+ if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
1007
+ const result = args[1] ?? args[0].records ?? [];
1008
+ return new Array(...result);
1009
+ }
1010
+ return new Array(...args);
1011
+ }
1012
+ async nextPage(size, offset) {
1013
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1014
+ return new _RecordArray(newPage);
1015
+ }
1016
+ async previousPage(size, offset) {
1017
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1018
+ return new _RecordArray(newPage);
1019
+ }
1020
+ async firstPage(size, offset) {
1021
+ const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1022
+ return new _RecordArray(newPage);
1023
+ }
1024
+ async lastPage(size, offset) {
1025
+ const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1026
+ return new _RecordArray(newPage);
1027
+ }
1028
+ hasNextPage() {
1029
+ return __privateGet$6(this, _page).meta.page.more;
1030
+ }
1031
+ };
1032
+ let RecordArray = _RecordArray;
1033
+ _page = new WeakMap();
957
1034
 
958
1035
  var __accessCheck$5 = (obj, member, msg) => {
959
1036
  if (!member.has(obj))
960
1037
  throw TypeError("Cannot " + msg);
961
1038
  };
962
- var __privateGet$4 = (obj, member, getter) => {
1039
+ var __privateGet$5 = (obj, member, getter) => {
963
1040
  __accessCheck$5(obj, member, "read from private field");
964
1041
  return getter ? getter.call(obj) : member.get(obj);
965
1042
  };
@@ -968,34 +1045,35 @@ var __privateAdd$5 = (obj, member, value) => {
968
1045
  throw TypeError("Cannot add the same private member more than once");
969
1046
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
970
1047
  };
971
- var __privateSet$3 = (obj, member, value, setter) => {
1048
+ var __privateSet$4 = (obj, member, value, setter) => {
972
1049
  __accessCheck$5(obj, member, "write to private field");
973
1050
  setter ? setter.call(obj, value) : member.set(obj, value);
974
1051
  return value;
975
1052
  };
976
1053
  var _table$1, _repository, _data;
977
1054
  const _Query = class {
978
- constructor(repository, table, data, parent) {
1055
+ constructor(repository, table, data, rawParent) {
979
1056
  __privateAdd$5(this, _table$1, void 0);
980
1057
  __privateAdd$5(this, _repository, void 0);
981
1058
  __privateAdd$5(this, _data, { filter: {} });
982
1059
  this.meta = { page: { cursor: "start", more: true } };
983
- this.records = [];
984
- __privateSet$3(this, _table$1, table);
1060
+ this.records = new RecordArray(this, []);
1061
+ __privateSet$4(this, _table$1, table);
985
1062
  if (repository) {
986
- __privateSet$3(this, _repository, repository);
1063
+ __privateSet$4(this, _repository, repository);
987
1064
  } else {
988
- __privateSet$3(this, _repository, this);
1065
+ __privateSet$4(this, _repository, this);
989
1066
  }
990
- __privateGet$4(this, _data).filter = data.filter ?? parent?.filter ?? {};
991
- __privateGet$4(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
992
- __privateGet$4(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
993
- __privateGet$4(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
994
- __privateGet$4(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
995
- __privateGet$4(this, _data).sort = data.sort ?? parent?.sort;
996
- __privateGet$4(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
997
- __privateGet$4(this, _data).page = data.page ?? parent?.page;
998
- __privateGet$4(this, _data).cache = data.cache ?? parent?.cache;
1067
+ const parent = cleanParent(data, rawParent);
1068
+ __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
1069
+ __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
1070
+ __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
1071
+ __privateGet$5(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
1072
+ __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1073
+ __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1074
+ __privateGet$5(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
1075
+ __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1076
+ __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
999
1077
  this.any = this.any.bind(this);
1000
1078
  this.all = this.all.bind(this);
1001
1079
  this.not = this.not.bind(this);
@@ -1006,50 +1084,50 @@ const _Query = class {
1006
1084
  Object.defineProperty(this, "repository", { enumerable: false });
1007
1085
  }
1008
1086
  getQueryOptions() {
1009
- return __privateGet$4(this, _data);
1087
+ return __privateGet$5(this, _data);
1010
1088
  }
1011
1089
  key() {
1012
- const { columns = [], filter = {}, sort = [], page = {} } = __privateGet$4(this, _data);
1013
- const key = JSON.stringify({ columns, filter, sort, page });
1090
+ const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$5(this, _data);
1091
+ const key = JSON.stringify({ columns, filter, sort, pagination });
1014
1092
  return toBase64(key);
1015
1093
  }
1016
1094
  any(...queries) {
1017
1095
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
1018
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $any } }, __privateGet$4(this, _data));
1096
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
1019
1097
  }
1020
1098
  all(...queries) {
1021
1099
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
1022
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1100
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1023
1101
  }
1024
1102
  not(...queries) {
1025
1103
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
1026
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $not } }, __privateGet$4(this, _data));
1104
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
1027
1105
  }
1028
1106
  none(...queries) {
1029
1107
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
1030
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $none } }, __privateGet$4(this, _data));
1108
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
1031
1109
  }
1032
1110
  filter(a, b) {
1033
1111
  if (arguments.length === 1) {
1034
1112
  const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
1035
- const $all = compact([__privateGet$4(this, _data).filter?.$all].flat().concat(constraints));
1036
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1113
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1114
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1037
1115
  } else {
1038
- const $all = compact([__privateGet$4(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
1039
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1116
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
1117
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1040
1118
  }
1041
1119
  }
1042
1120
  sort(column, direction) {
1043
- const originalSort = [__privateGet$4(this, _data).sort ?? []].flat();
1121
+ const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
1044
1122
  const sort = [...originalSort, { column, direction }];
1045
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { sort }, __privateGet$4(this, _data));
1123
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
1046
1124
  }
1047
1125
  select(columns) {
1048
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { columns }, __privateGet$4(this, _data));
1126
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { columns }, __privateGet$5(this, _data));
1049
1127
  }
1050
1128
  getPaginated(options = {}) {
1051
- const query = new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), options, __privateGet$4(this, _data));
1052
- return __privateGet$4(this, _repository).query(query);
1129
+ const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
1130
+ return __privateGet$5(this, _repository).query(query);
1053
1131
  }
1054
1132
  async *[Symbol.asyncIterator]() {
1055
1133
  for await (const [record] of this.getIterator({ batchSize: 1 })) {
@@ -1058,18 +1136,21 @@ const _Query = class {
1058
1136
  }
1059
1137
  async *getIterator(options = {}) {
1060
1138
  const { batchSize = 1 } = options;
1061
- let offset = 0;
1062
- let end = false;
1063
- while (!end) {
1064
- const { records, meta } = await this.getPaginated({ ...options, page: { size: batchSize, offset } });
1065
- yield records;
1066
- offset += batchSize;
1067
- end = !meta.page.more;
1139
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
1140
+ let more = page.hasNextPage();
1141
+ yield page.records;
1142
+ while (more) {
1143
+ page = await page.nextPage();
1144
+ more = page.hasNextPage();
1145
+ yield page.records;
1068
1146
  }
1069
1147
  }
1070
1148
  async getMany(options = {}) {
1071
- const { records } = await this.getPaginated(options);
1072
- return records;
1149
+ const page = await this.getPaginated(options);
1150
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1151
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1152
+ }
1153
+ return page.records;
1073
1154
  }
1074
1155
  async getAll(options = {}) {
1075
1156
  const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
@@ -1080,11 +1161,11 @@ const _Query = class {
1080
1161
  return results;
1081
1162
  }
1082
1163
  async getFirst(options = {}) {
1083
- const records = await this.getMany({ ...options, page: { size: 1 } });
1084
- return records[0] || null;
1164
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1165
+ return records[0] ?? null;
1085
1166
  }
1086
1167
  cache(ttl) {
1087
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { cache: ttl }, __privateGet$4(this, _data));
1168
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1088
1169
  }
1089
1170
  nextPage(size, offset) {
1090
1171
  return this.firstPage(size, offset);
@@ -1093,10 +1174,10 @@ const _Query = class {
1093
1174
  return this.firstPage(size, offset);
1094
1175
  }
1095
1176
  firstPage(size, offset) {
1096
- return this.getPaginated({ page: { size, offset } });
1177
+ return this.getPaginated({ pagination: { size, offset } });
1097
1178
  }
1098
1179
  lastPage(size, offset) {
1099
- return this.getPaginated({ page: { size, offset, before: "end" } });
1180
+ return this.getPaginated({ pagination: { size, offset, before: "end" } });
1100
1181
  }
1101
1182
  hasNextPage() {
1102
1183
  return this.meta.page.more;
@@ -1106,12 +1187,20 @@ let Query = _Query;
1106
1187
  _table$1 = new WeakMap();
1107
1188
  _repository = new WeakMap();
1108
1189
  _data = new WeakMap();
1190
+ function cleanParent(data, parent) {
1191
+ if (isCursorPaginationOptions(data.pagination)) {
1192
+ return { ...parent, sorting: void 0, filter: void 0 };
1193
+ }
1194
+ return parent;
1195
+ }
1109
1196
 
1110
1197
  function isIdentifiable(x) {
1111
1198
  return isObject(x) && isString(x?.id);
1112
1199
  }
1113
1200
  function isXataRecord(x) {
1114
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1201
+ const record = x;
1202
+ const metadata = record?.getMetadata();
1203
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1115
1204
  }
1116
1205
 
1117
1206
  function isSortFilterString(value) {
@@ -1141,7 +1230,7 @@ var __accessCheck$4 = (obj, member, msg) => {
1141
1230
  if (!member.has(obj))
1142
1231
  throw TypeError("Cannot " + msg);
1143
1232
  };
1144
- var __privateGet$3 = (obj, member, getter) => {
1233
+ var __privateGet$4 = (obj, member, getter) => {
1145
1234
  __accessCheck$4(obj, member, "read from private field");
1146
1235
  return getter ? getter.call(obj) : member.get(obj);
1147
1236
  };
@@ -1150,7 +1239,7 @@ var __privateAdd$4 = (obj, member, value) => {
1150
1239
  throw TypeError("Cannot add the same private member more than once");
1151
1240
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1152
1241
  };
1153
- var __privateSet$2 = (obj, member, value, setter) => {
1242
+ var __privateSet$3 = (obj, member, value, setter) => {
1154
1243
  __accessCheck$4(obj, member, "write to private field");
1155
1244
  setter ? setter.call(obj, value) : member.set(obj, value);
1156
1245
  return value;
@@ -1159,7 +1248,7 @@ var __privateMethod$2 = (obj, member, method) => {
1159
1248
  __accessCheck$4(obj, member, "access private method");
1160
1249
  return method;
1161
1250
  };
1162
- var _table, _links, _getFetchProps, _cache, _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;
1251
+ var _table, _getFetchProps, _cache, _schema$1, _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, _getSchema$1, getSchema_fn$1;
1163
1252
  class Repository extends Query {
1164
1253
  }
1165
1254
  class RestRepository extends Query {
@@ -1176,21 +1265,43 @@ class RestRepository extends Query {
1176
1265
  __privateAdd$4(this, _getCacheRecord);
1177
1266
  __privateAdd$4(this, _setCacheQuery);
1178
1267
  __privateAdd$4(this, _getCacheQuery);
1268
+ __privateAdd$4(this, _getSchema$1);
1179
1269
  __privateAdd$4(this, _table, void 0);
1180
- __privateAdd$4(this, _links, void 0);
1181
1270
  __privateAdd$4(this, _getFetchProps, void 0);
1182
1271
  __privateAdd$4(this, _cache, void 0);
1183
- __privateSet$2(this, _table, options.table);
1184
- __privateSet$2(this, _links, options.links ?? {});
1185
- __privateSet$2(this, _getFetchProps, options.pluginOptions.getFetchProps);
1272
+ __privateAdd$4(this, _schema$1, void 0);
1273
+ __privateSet$3(this, _table, options.table);
1274
+ __privateSet$3(this, _getFetchProps, options.pluginOptions.getFetchProps);
1186
1275
  this.db = options.db;
1187
- __privateSet$2(this, _cache, options.pluginOptions.cache);
1276
+ __privateSet$3(this, _cache, options.pluginOptions.cache);
1188
1277
  }
1189
1278
  async create(a, b) {
1190
1279
  if (Array.isArray(a)) {
1191
- const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1192
- await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1193
- return records;
1280
+ if (a.length === 0)
1281
+ return [];
1282
+ const [itemsWithoutIds, itemsWithIds, order] = a.reduce(([accWithoutIds, accWithIds, accOrder], item) => {
1283
+ const condition = isString(item.id);
1284
+ accOrder.push(condition);
1285
+ if (condition) {
1286
+ accWithIds.push(item);
1287
+ } else {
1288
+ accWithoutIds.push(item);
1289
+ }
1290
+ return [accWithoutIds, accWithIds, accOrder];
1291
+ }, [[], [], []]);
1292
+ const recordsWithoutId = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, itemsWithoutIds);
1293
+ await Promise.all(recordsWithoutId.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1294
+ if (itemsWithIds.length > 100) {
1295
+ console.warn("Bulk create operation with id is not optimized in the Xata API yet, this request might be slow");
1296
+ }
1297
+ const recordsWithId = await Promise.all(itemsWithIds.map((object) => this.create(object)));
1298
+ return order.map((condition) => {
1299
+ if (condition) {
1300
+ return recordsWithId.shift();
1301
+ } else {
1302
+ return recordsWithoutId.shift();
1303
+ }
1304
+ }).filter((record) => !!record);
1194
1305
  }
1195
1306
  if (isString(a) && isObject(b)) {
1196
1307
  if (a === "")
@@ -1213,26 +1324,38 @@ class RestRepository extends Query {
1213
1324
  }
1214
1325
  throw new Error("Invalid arguments for create method");
1215
1326
  }
1216
- async read(recordId) {
1217
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, recordId);
1218
- if (cacheRecord)
1219
- return cacheRecord;
1220
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1221
- try {
1222
- const response = await getRecord({
1223
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1224
- ...fetchProps
1225
- });
1226
- return initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), response);
1227
- } catch (e) {
1228
- if (isObject(e) && e.status === 404) {
1229
- return null;
1327
+ async read(a) {
1328
+ if (Array.isArray(a)) {
1329
+ if (a.length === 0)
1330
+ return [];
1331
+ const ids = a.map((item) => isString(item) ? item : item.id).filter((id2) => isString(id2));
1332
+ return this.getAll({ filter: { id: { $any: ids } } });
1333
+ }
1334
+ const id = isString(a) ? a : a.id;
1335
+ if (isString(id)) {
1336
+ const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, id);
1337
+ if (cacheRecord)
1338
+ return cacheRecord;
1339
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1340
+ try {
1341
+ const response = await getRecord({
1342
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: id },
1343
+ ...fetchProps
1344
+ });
1345
+ const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1346
+ return initObject(this.db, schema, __privateGet$4(this, _table), response);
1347
+ } catch (e) {
1348
+ if (isObject(e) && e.status === 404) {
1349
+ return null;
1350
+ }
1351
+ throw e;
1230
1352
  }
1231
- throw e;
1232
1353
  }
1233
1354
  }
1234
1355
  async update(a, b) {
1235
1356
  if (Array.isArray(a)) {
1357
+ if (a.length === 0)
1358
+ return [];
1236
1359
  if (a.length > 100) {
1237
1360
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1238
1361
  }
@@ -1254,6 +1377,8 @@ class RestRepository extends Query {
1254
1377
  }
1255
1378
  async createOrUpdate(a, b) {
1256
1379
  if (Array.isArray(a)) {
1380
+ if (a.length === 0)
1381
+ return [];
1257
1382
  if (a.length > 100) {
1258
1383
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1259
1384
  }
@@ -1275,6 +1400,8 @@ class RestRepository extends Query {
1275
1400
  }
1276
1401
  async delete(a) {
1277
1402
  if (Array.isArray(a)) {
1403
+ if (a.length === 0)
1404
+ return;
1278
1405
  if (a.length > 100) {
1279
1406
  console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1280
1407
  }
@@ -1294,13 +1421,19 @@ class RestRepository extends Query {
1294
1421
  throw new Error("Invalid arguments for delete method");
1295
1422
  }
1296
1423
  async search(query, options = {}) {
1297
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1298
- const { records } = await searchBranch({
1299
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1300
- body: { tables: [__privateGet$3(this, _table)], query, fuzziness: options.fuzziness },
1424
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1425
+ const { records } = await searchTable({
1426
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1427
+ body: {
1428
+ query,
1429
+ fuzziness: options.fuzziness,
1430
+ highlight: options.highlight,
1431
+ filter: options.filter
1432
+ },
1301
1433
  ...fetchProps
1302
1434
  });
1303
- return records.map((item) => initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), item));
1435
+ const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1436
+ return records.map((item) => initObject(this.db, schema, __privateGet$4(this, _table), item));
1304
1437
  }
1305
1438
  async query(query) {
1306
1439
  const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
@@ -1309,34 +1442,35 @@ class RestRepository extends Query {
1309
1442
  const data = query.getQueryOptions();
1310
1443
  const body = {
1311
1444
  filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1312
- sort: data.sort ? buildSortFilter(data.sort) : void 0,
1313
- page: data.page,
1445
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1446
+ page: data.pagination,
1314
1447
  columns: data.columns
1315
1448
  };
1316
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1449
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1317
1450
  const { meta, records: objects } = await queryTable({
1318
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table) },
1451
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1319
1452
  body,
1320
1453
  ...fetchProps
1321
1454
  });
1322
- const records = objects.map((record) => initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), record));
1455
+ const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1456
+ const records = objects.map((record) => initObject(this.db, schema, __privateGet$4(this, _table), record));
1323
1457
  await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1324
1458
  return new Page(query, meta, records);
1325
1459
  }
1326
1460
  }
1327
1461
  _table = new WeakMap();
1328
- _links = new WeakMap();
1329
1462
  _getFetchProps = new WeakMap();
1330
1463
  _cache = new WeakMap();
1464
+ _schema$1 = new WeakMap();
1331
1465
  _insertRecordWithoutId = new WeakSet();
1332
1466
  insertRecordWithoutId_fn = async function(object) {
1333
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1467
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1334
1468
  const record = transformObjectLinks(object);
1335
1469
  const response = await insertRecord({
1336
1470
  pathParams: {
1337
1471
  workspace: "{workspaceId}",
1338
1472
  dbBranchName: "{dbBranch}",
1339
- tableName: __privateGet$3(this, _table)
1473
+ tableName: __privateGet$4(this, _table)
1340
1474
  },
1341
1475
  body: record,
1342
1476
  ...fetchProps
@@ -1349,13 +1483,13 @@ insertRecordWithoutId_fn = async function(object) {
1349
1483
  };
1350
1484
  _insertRecordWithId = new WeakSet();
1351
1485
  insertRecordWithId_fn = async function(recordId, object) {
1352
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1486
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1353
1487
  const record = transformObjectLinks(object);
1354
1488
  const response = await insertRecordWithID({
1355
1489
  pathParams: {
1356
1490
  workspace: "{workspaceId}",
1357
1491
  dbBranchName: "{dbBranch}",
1358
- tableName: __privateGet$3(this, _table),
1492
+ tableName: __privateGet$4(this, _table),
1359
1493
  recordId
1360
1494
  },
1361
1495
  body: record,
@@ -1370,14 +1504,14 @@ insertRecordWithId_fn = async function(recordId, object) {
1370
1504
  };
1371
1505
  _bulkInsertTableRecords = new WeakSet();
1372
1506
  bulkInsertTableRecords_fn = async function(objects) {
1373
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1507
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1374
1508
  const records = objects.map((object) => transformObjectLinks(object));
1375
1509
  const response = await bulkInsertTableRecords({
1376
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table) },
1510
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1377
1511
  body: { records },
1378
1512
  ...fetchProps
1379
1513
  });
1380
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1514
+ const finalObjects = await this.read(response.recordIDs);
1381
1515
  if (finalObjects.length !== objects.length) {
1382
1516
  throw new Error("The server failed to save some records");
1383
1517
  }
@@ -1385,10 +1519,10 @@ bulkInsertTableRecords_fn = async function(objects) {
1385
1519
  };
1386
1520
  _updateRecordWithID = new WeakSet();
1387
1521
  updateRecordWithID_fn = async function(recordId, object) {
1388
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1522
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1389
1523
  const record = transformObjectLinks(object);
1390
1524
  const response = await updateRecordWithID({
1391
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1525
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1392
1526
  body: record,
1393
1527
  ...fetchProps
1394
1528
  });
@@ -1399,9 +1533,9 @@ updateRecordWithID_fn = async function(recordId, object) {
1399
1533
  };
1400
1534
  _upsertRecordWithID = new WeakSet();
1401
1535
  upsertRecordWithID_fn = async function(recordId, object) {
1402
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1536
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1403
1537
  const response = await upsertRecordWithID({
1404
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1538
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1405
1539
  body: object,
1406
1540
  ...fetchProps
1407
1541
  });
@@ -1412,51 +1546,63 @@ upsertRecordWithID_fn = async function(recordId, object) {
1412
1546
  };
1413
1547
  _deleteRecord = new WeakSet();
1414
1548
  deleteRecord_fn = async function(recordId) {
1415
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1549
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1416
1550
  await deleteRecord({
1417
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1551
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1418
1552
  ...fetchProps
1419
1553
  });
1420
1554
  };
1421
1555
  _invalidateCache = new WeakSet();
1422
1556
  invalidateCache_fn = async function(recordId) {
1423
- await __privateGet$3(this, _cache).delete(`rec_${__privateGet$3(this, _table)}:${recordId}`);
1424
- const cacheItems = await __privateGet$3(this, _cache).getAll();
1557
+ await __privateGet$4(this, _cache).delete(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1558
+ const cacheItems = await __privateGet$4(this, _cache).getAll();
1425
1559
  const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1426
1560
  for (const [key, value] of queries) {
1427
1561
  const ids = getIds(value);
1428
1562
  if (ids.includes(recordId))
1429
- await __privateGet$3(this, _cache).delete(key);
1563
+ await __privateGet$4(this, _cache).delete(key);
1430
1564
  }
1431
1565
  };
1432
1566
  _setCacheRecord = new WeakSet();
1433
1567
  setCacheRecord_fn = async function(record) {
1434
- if (!__privateGet$3(this, _cache).cacheRecords)
1568
+ if (!__privateGet$4(this, _cache).cacheRecords)
1435
1569
  return;
1436
- await __privateGet$3(this, _cache).set(`rec_${__privateGet$3(this, _table)}:${record.id}`, record);
1570
+ await __privateGet$4(this, _cache).set(`rec_${__privateGet$4(this, _table)}:${record.id}`, record);
1437
1571
  };
1438
1572
  _getCacheRecord = new WeakSet();
1439
1573
  getCacheRecord_fn = async function(recordId) {
1440
- if (!__privateGet$3(this, _cache).cacheRecords)
1574
+ if (!__privateGet$4(this, _cache).cacheRecords)
1441
1575
  return null;
1442
- return __privateGet$3(this, _cache).get(`rec_${__privateGet$3(this, _table)}:${recordId}`);
1576
+ return __privateGet$4(this, _cache).get(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1443
1577
  };
1444
1578
  _setCacheQuery = new WeakSet();
1445
1579
  setCacheQuery_fn = async function(query, meta, records) {
1446
- await __privateGet$3(this, _cache).set(`query_${__privateGet$3(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1580
+ await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1447
1581
  };
1448
1582
  _getCacheQuery = new WeakSet();
1449
1583
  getCacheQuery_fn = async function(query) {
1450
- const key = `query_${__privateGet$3(this, _table)}:${query.key()}`;
1451
- const result = await __privateGet$3(this, _cache).get(key);
1584
+ const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
1585
+ const result = await __privateGet$4(this, _cache).get(key);
1452
1586
  if (!result)
1453
1587
  return null;
1454
- const { cache: ttl = __privateGet$3(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1455
- if (!ttl || ttl < 0)
1456
- return result;
1588
+ const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1589
+ if (ttl < 0)
1590
+ return null;
1457
1591
  const hasExpired = result.date.getTime() + ttl < Date.now();
1458
1592
  return hasExpired ? null : result;
1459
1593
  };
1594
+ _getSchema$1 = new WeakSet();
1595
+ getSchema_fn$1 = async function() {
1596
+ if (__privateGet$4(this, _schema$1))
1597
+ return __privateGet$4(this, _schema$1);
1598
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1599
+ const { schema } = await getBranchDetails({
1600
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1601
+ ...fetchProps
1602
+ });
1603
+ __privateSet$3(this, _schema$1, schema);
1604
+ return schema;
1605
+ };
1460
1606
  const transformObjectLinks = (object) => {
1461
1607
  return Object.entries(object).reduce((acc, [key, value]) => {
1462
1608
  if (key === "xata")
@@ -1464,15 +1610,34 @@ const transformObjectLinks = (object) => {
1464
1610
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1465
1611
  }, {});
1466
1612
  };
1467
- const initObject = (db, links, table, object) => {
1613
+ const initObject = (db, schema, table, object) => {
1468
1614
  const result = {};
1469
- Object.assign(result, object);
1470
- const tableLinks = links[table] || [];
1471
- for (const link of tableLinks) {
1472
- const [field, linkTable] = link;
1473
- const value = result[field];
1474
- if (value && isObject(value)) {
1475
- result[field] = initObject(db, links, linkTable, value);
1615
+ const { xata, ...rest } = object ?? {};
1616
+ Object.assign(result, rest);
1617
+ const { columns } = schema.tables.find(({ name }) => name === table) ?? {};
1618
+ if (!columns)
1619
+ console.error(`Table ${table} not found in schema`);
1620
+ for (const column of columns ?? []) {
1621
+ const value = result[column.name];
1622
+ switch (column.type) {
1623
+ case "datetime": {
1624
+ const date = value !== void 0 ? new Date(value) : void 0;
1625
+ if (date && isNaN(date.getTime())) {
1626
+ console.error(`Failed to parse date ${value} for field ${column.name}`);
1627
+ } else if (date) {
1628
+ result[column.name] = date;
1629
+ }
1630
+ break;
1631
+ }
1632
+ case "link": {
1633
+ const linkTable = column.link?.table;
1634
+ if (!linkTable) {
1635
+ console.error(`Failed to parse link for field ${column.name}`);
1636
+ } else if (isObject(value)) {
1637
+ result[column.name] = initObject(db, schema, linkTable, value);
1638
+ }
1639
+ break;
1640
+ }
1476
1641
  }
1477
1642
  }
1478
1643
  result.read = function() {
@@ -1484,7 +1649,10 @@ const initObject = (db, links, table, object) => {
1484
1649
  result.delete = function() {
1485
1650
  return db[table].delete(result["id"]);
1486
1651
  };
1487
- for (const prop of ["read", "update", "delete"]) {
1652
+ result.getMetadata = function() {
1653
+ return xata;
1654
+ };
1655
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1488
1656
  Object.defineProperty(result, prop, { enumerable: false });
1489
1657
  }
1490
1658
  Object.freeze(result);
@@ -1504,7 +1672,7 @@ var __accessCheck$3 = (obj, member, msg) => {
1504
1672
  if (!member.has(obj))
1505
1673
  throw TypeError("Cannot " + msg);
1506
1674
  };
1507
- var __privateGet$2 = (obj, member, getter) => {
1675
+ var __privateGet$3 = (obj, member, getter) => {
1508
1676
  __accessCheck$3(obj, member, "read from private field");
1509
1677
  return getter ? getter.call(obj) : member.get(obj);
1510
1678
  };
@@ -1513,7 +1681,7 @@ var __privateAdd$3 = (obj, member, value) => {
1513
1681
  throw TypeError("Cannot add the same private member more than once");
1514
1682
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1515
1683
  };
1516
- var __privateSet$1 = (obj, member, value, setter) => {
1684
+ var __privateSet$2 = (obj, member, value, setter) => {
1517
1685
  __accessCheck$3(obj, member, "write to private field");
1518
1686
  setter ? setter.call(obj, value) : member.set(obj, value);
1519
1687
  return value;
@@ -1522,30 +1690,30 @@ var _map;
1522
1690
  class SimpleCache {
1523
1691
  constructor(options = {}) {
1524
1692
  __privateAdd$3(this, _map, void 0);
1525
- __privateSet$1(this, _map, /* @__PURE__ */ new Map());
1693
+ __privateSet$2(this, _map, /* @__PURE__ */ new Map());
1526
1694
  this.capacity = options.max ?? 500;
1527
1695
  this.cacheRecords = options.cacheRecords ?? true;
1528
1696
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1529
1697
  }
1530
1698
  async getAll() {
1531
- return Object.fromEntries(__privateGet$2(this, _map));
1699
+ return Object.fromEntries(__privateGet$3(this, _map));
1532
1700
  }
1533
1701
  async get(key) {
1534
- return __privateGet$2(this, _map).get(key) ?? null;
1702
+ return __privateGet$3(this, _map).get(key) ?? null;
1535
1703
  }
1536
1704
  async set(key, value) {
1537
1705
  await this.delete(key);
1538
- __privateGet$2(this, _map).set(key, value);
1539
- if (__privateGet$2(this, _map).size > this.capacity) {
1540
- const leastRecentlyUsed = __privateGet$2(this, _map).keys().next().value;
1706
+ __privateGet$3(this, _map).set(key, value);
1707
+ if (__privateGet$3(this, _map).size > this.capacity) {
1708
+ const leastRecentlyUsed = __privateGet$3(this, _map).keys().next().value;
1541
1709
  await this.delete(leastRecentlyUsed);
1542
1710
  }
1543
1711
  }
1544
1712
  async delete(key) {
1545
- __privateGet$2(this, _map).delete(key);
1713
+ __privateGet$3(this, _map).delete(key);
1546
1714
  }
1547
1715
  async clear() {
1548
- return __privateGet$2(this, _map).clear();
1716
+ return __privateGet$3(this, _map).clear();
1549
1717
  }
1550
1718
  }
1551
1719
  _map = new WeakMap();
@@ -1573,7 +1741,7 @@ var __accessCheck$2 = (obj, member, msg) => {
1573
1741
  if (!member.has(obj))
1574
1742
  throw TypeError("Cannot " + msg);
1575
1743
  };
1576
- var __privateGet$1 = (obj, member, getter) => {
1744
+ var __privateGet$2 = (obj, member, getter) => {
1577
1745
  __accessCheck$2(obj, member, "read from private field");
1578
1746
  return getter ? getter.call(obj) : member.get(obj);
1579
1747
  };
@@ -1584,26 +1752,24 @@ var __privateAdd$2 = (obj, member, value) => {
1584
1752
  };
1585
1753
  var _tables;
1586
1754
  class SchemaPlugin extends XataPlugin {
1587
- constructor(links, tableNames) {
1755
+ constructor(tableNames) {
1588
1756
  super();
1589
- this.links = links;
1590
1757
  this.tableNames = tableNames;
1591
1758
  __privateAdd$2(this, _tables, {});
1592
1759
  }
1593
1760
  build(pluginOptions) {
1594
- const links = this.links;
1595
1761
  const db = new Proxy({}, {
1596
1762
  get: (_target, table) => {
1597
1763
  if (!isString(table))
1598
1764
  throw new Error("Invalid table name");
1599
- if (!__privateGet$1(this, _tables)[table]) {
1600
- __privateGet$1(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, links });
1765
+ if (__privateGet$2(this, _tables)[table] === void 0) {
1766
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table });
1601
1767
  }
1602
- return __privateGet$1(this, _tables)[table];
1768
+ return __privateGet$2(this, _tables)[table];
1603
1769
  }
1604
1770
  });
1605
1771
  for (const table of this.tableNames ?? []) {
1606
- db[table] = new RestRepository({ db, pluginOptions, table, links });
1772
+ db[table] = new RestRepository({ db, pluginOptions, table });
1607
1773
  }
1608
1774
  return db;
1609
1775
  }
@@ -1614,55 +1780,80 @@ var __accessCheck$1 = (obj, member, msg) => {
1614
1780
  if (!member.has(obj))
1615
1781
  throw TypeError("Cannot " + msg);
1616
1782
  };
1783
+ var __privateGet$1 = (obj, member, getter) => {
1784
+ __accessCheck$1(obj, member, "read from private field");
1785
+ return getter ? getter.call(obj) : member.get(obj);
1786
+ };
1617
1787
  var __privateAdd$1 = (obj, member, value) => {
1618
1788
  if (member.has(obj))
1619
1789
  throw TypeError("Cannot add the same private member more than once");
1620
1790
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1621
1791
  };
1792
+ var __privateSet$1 = (obj, member, value, setter) => {
1793
+ __accessCheck$1(obj, member, "write to private field");
1794
+ setter ? setter.call(obj, value) : member.set(obj, value);
1795
+ return value;
1796
+ };
1622
1797
  var __privateMethod$1 = (obj, member, method) => {
1623
1798
  __accessCheck$1(obj, member, "access private method");
1624
1799
  return method;
1625
1800
  };
1626
- var _search, search_fn;
1801
+ var _schema, _search, search_fn, _getSchema, getSchema_fn;
1627
1802
  class SearchPlugin extends XataPlugin {
1628
- constructor(db, links) {
1803
+ constructor(db) {
1629
1804
  super();
1630
1805
  this.db = db;
1631
- this.links = links;
1632
1806
  __privateAdd$1(this, _search);
1807
+ __privateAdd$1(this, _getSchema);
1808
+ __privateAdd$1(this, _schema, void 0);
1633
1809
  }
1634
1810
  build({ getFetchProps }) {
1635
1811
  return {
1636
1812
  all: async (query, options = {}) => {
1637
1813
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1814
+ const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
1638
1815
  return records.map((record) => {
1639
1816
  const { table = "orphan" } = record.xata;
1640
- return { table, record: initObject(this.db, this.links, table, record) };
1817
+ return { table, record: initObject(this.db, schema, table, record) };
1641
1818
  });
1642
1819
  },
1643
1820
  byTable: async (query, options = {}) => {
1644
1821
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1822
+ const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
1645
1823
  return records.reduce((acc, record) => {
1646
1824
  const { table = "orphan" } = record.xata;
1647
1825
  const items = acc[table] ?? [];
1648
- const item = initObject(this.db, this.links, table, record);
1826
+ const item = initObject(this.db, schema, table, record);
1649
1827
  return { ...acc, [table]: [...items, item] };
1650
1828
  }, {});
1651
1829
  }
1652
1830
  };
1653
1831
  }
1654
1832
  }
1833
+ _schema = new WeakMap();
1655
1834
  _search = new WeakSet();
1656
1835
  search_fn = async function(query, options, getFetchProps) {
1657
1836
  const fetchProps = await getFetchProps();
1658
- const { tables, fuzziness } = options ?? {};
1837
+ const { tables, fuzziness, highlight } = options ?? {};
1659
1838
  const { records } = await searchBranch({
1660
1839
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1661
- body: { tables, query, fuzziness },
1840
+ body: { tables, query, fuzziness, highlight },
1662
1841
  ...fetchProps
1663
1842
  });
1664
1843
  return records;
1665
1844
  };
1845
+ _getSchema = new WeakSet();
1846
+ getSchema_fn = async function(getFetchProps) {
1847
+ if (__privateGet$1(this, _schema))
1848
+ return __privateGet$1(this, _schema);
1849
+ const fetchProps = await getFetchProps();
1850
+ const { schema } = await getBranchDetails({
1851
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1852
+ ...fetchProps
1853
+ });
1854
+ __privateSet$1(this, _schema, schema);
1855
+ return schema;
1856
+ };
1666
1857
 
1667
1858
  const isBranchStrategyBuilder = (strategy) => {
1668
1859
  return typeof strategy === "function";
@@ -1674,30 +1865,39 @@ const envBranchNames = [
1674
1865
  "CF_PAGES_BRANCH",
1675
1866
  "BRANCH"
1676
1867
  ];
1677
- const defaultBranch = "main";
1678
1868
  async function getCurrentBranchName(options) {
1679
- const env = await getBranchByEnvVariable();
1680
- if (env)
1681
- return env;
1682
- const branch = await getGitBranch();
1683
- if (!branch)
1684
- return defaultBranch;
1685
- const details = await getDatabaseBranch(branch, options);
1686
- if (details)
1687
- return branch;
1688
- return defaultBranch;
1869
+ const env = getBranchByEnvVariable();
1870
+ if (env) {
1871
+ const details = await getDatabaseBranch(env, options);
1872
+ if (details)
1873
+ return env;
1874
+ console.warn(`Branch ${env} not found in Xata. Ignoring...`);
1875
+ }
1876
+ const gitBranch = await getGitBranch();
1877
+ return resolveXataBranch(gitBranch, options);
1689
1878
  }
1690
1879
  async function getCurrentBranchDetails(options) {
1691
- const env = await getBranchByEnvVariable();
1692
- if (env)
1693
- return getDatabaseBranch(env, options);
1694
- const branch = await getGitBranch();
1695
- if (!branch)
1696
- return getDatabaseBranch(defaultBranch, options);
1697
- const details = await getDatabaseBranch(branch, options);
1698
- if (details)
1699
- return details;
1700
- return getDatabaseBranch(defaultBranch, options);
1880
+ const branch = await getCurrentBranchName(options);
1881
+ return getDatabaseBranch(branch, options);
1882
+ }
1883
+ async function resolveXataBranch(gitBranch, options) {
1884
+ const databaseURL = options?.databaseURL || getDatabaseURL();
1885
+ const apiKey = options?.apiKey || getAPIKey();
1886
+ if (!databaseURL)
1887
+ throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
1888
+ if (!apiKey)
1889
+ throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
1890
+ const [protocol, , host, , dbName] = databaseURL.split("/");
1891
+ const [workspace] = host.split(".");
1892
+ const { branch } = await resolveBranch({
1893
+ apiKey,
1894
+ apiUrl: databaseURL,
1895
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
1896
+ workspacesApiUrl: `${protocol}//${host}`,
1897
+ pathParams: { dbName, workspace },
1898
+ queryParams: { gitBranch, fallbackBranch: getEnvVariable("XATA_FALLBACK_BRANCH") }
1899
+ });
1900
+ return branch;
1701
1901
  }
1702
1902
  async function getDatabaseBranch(branch, options) {
1703
1903
  const databaseURL = options?.databaseURL || getDatabaseURL();
@@ -1715,10 +1915,7 @@ async function getDatabaseBranch(branch, options) {
1715
1915
  apiUrl: databaseURL,
1716
1916
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1717
1917
  workspacesApiUrl: `${protocol}//${host}`,
1718
- pathParams: {
1719
- dbBranchName,
1720
- workspace
1721
- }
1918
+ pathParams: { dbBranchName, workspace }
1722
1919
  });
1723
1920
  } catch (err) {
1724
1921
  if (isObject(err) && err.status === 404)
@@ -1771,7 +1968,7 @@ var __privateMethod = (obj, member, method) => {
1771
1968
  const buildClient = (plugins) => {
1772
1969
  var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1773
1970
  return _a = class {
1774
- constructor(options = {}, links, tables) {
1971
+ constructor(options = {}, tables) {
1775
1972
  __privateAdd(this, _parseOptions);
1776
1973
  __privateAdd(this, _getFetchProps);
1777
1974
  __privateAdd(this, _evaluateBranch);
@@ -1781,12 +1978,12 @@ const buildClient = (plugins) => {
1781
1978
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1782
1979
  cache: safeOptions.cache
1783
1980
  };
1784
- const db = new SchemaPlugin(links, tables).build(pluginOptions);
1785
- const search = new SearchPlugin(db, links ?? {}).build(pluginOptions);
1981
+ const db = new SchemaPlugin(tables).build(pluginOptions);
1982
+ const search = new SearchPlugin(db).build(pluginOptions);
1786
1983
  this.db = db;
1787
1984
  this.search = search;
1788
1985
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
1789
- if (!namespace)
1986
+ if (namespace === void 0)
1790
1987
  continue;
1791
1988
  const result = namespace.build(pluginOptions);
1792
1989
  if (result instanceof Promise) {
@@ -1803,7 +2000,7 @@ const buildClient = (plugins) => {
1803
2000
  const databaseURL = options?.databaseURL || getDatabaseURL();
1804
2001
  const apiKey = options?.apiKey || getAPIKey();
1805
2002
  const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
1806
- const branch = async () => options?.branch ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
2003
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1807
2004
  if (!databaseURL || !apiKey) {
1808
2005
  throw new Error("Options databaseURL and apiKey are required");
1809
2006
  }
@@ -1830,7 +2027,7 @@ const buildClient = (plugins) => {
1830
2027
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1831
2028
  if (__privateGet(this, _branch))
1832
2029
  return __privateGet(this, _branch);
1833
- if (!param)
2030
+ if (param === void 0)
1834
2031
  return void 0;
1835
2032
  const strategies = Array.isArray(param) ? [...param] : [param];
1836
2033
  const evaluateBranch = async (strategy) => {
@@ -1863,6 +2060,7 @@ exports.PAGINATION_MAX_OFFSET = PAGINATION_MAX_OFFSET;
1863
2060
  exports.PAGINATION_MAX_SIZE = PAGINATION_MAX_SIZE;
1864
2061
  exports.Page = Page;
1865
2062
  exports.Query = Query;
2063
+ exports.RecordArray = RecordArray;
1866
2064
  exports.Repository = Repository;
1867
2065
  exports.RestRepository = RestRepository;
1868
2066
  exports.SchemaPlugin = SchemaPlugin;
@@ -1927,6 +2125,7 @@ exports.insertRecord = insertRecord;
1927
2125
  exports.insertRecordWithID = insertRecordWithID;
1928
2126
  exports.inviteWorkspaceMember = inviteWorkspaceMember;
1929
2127
  exports.is = is;
2128
+ exports.isCursorPaginationOptions = isCursorPaginationOptions;
1930
2129
  exports.isIdentifiable = isIdentifiable;
1931
2130
  exports.isNot = isNot;
1932
2131
  exports.isXataRecord = isXataRecord;
@@ -1942,6 +2141,7 @@ exports.removeWorkspaceMember = removeWorkspaceMember;
1942
2141
  exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite;
1943
2142
  exports.resolveBranch = resolveBranch;
1944
2143
  exports.searchBranch = searchBranch;
2144
+ exports.searchTable = searchTable;
1945
2145
  exports.setTableSchema = setTableSchema;
1946
2146
  exports.startsWith = startsWith;
1947
2147
  exports.updateBranchMetadata = updateBranchMetadata;