@xata.io/client 0.0.0-alpha.vfd071d9 → 0.0.0-alpha.vfe4ae98

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.vfe4ae98";
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$7 = (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$7(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$6 = (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$6(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(...args) {
998
+ super(..._RecordArray.parseConstructorParams(...args));
999
+ __privateAdd$6(this, _page, void 0);
1000
+ __privateSet$6(this, _page, args[0]);
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$5 = (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$5(this, _table$1, table);
985
1062
  if (repository) {
986
- __privateSet$3(this, _repository, repository);
1063
+ __privateSet$5(this, _repository, repository);
987
1064
  } else {
988
- __privateSet$3(this, _repository, this);
1065
+ __privateSet$5(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,83 +1084,88 @@ 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
- for await (const [record] of this.getIterator(1)) {
1133
+ for await (const [record] of this.getIterator({ batchSize: 1 })) {
1056
1134
  yield record;
1057
1135
  }
1058
1136
  }
1059
- async *getIterator(chunk, options = {}) {
1060
- let offset = 0;
1061
- let end = false;
1062
- while (!end) {
1063
- const { records, meta } = await this.getPaginated({ ...options, page: { size: chunk, offset } });
1064
- yield records;
1065
- offset += chunk;
1066
- end = !meta.page.more;
1137
+ async *getIterator(options = {}) {
1138
+ const { batchSize = 1 } = options;
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;
1067
1146
  }
1068
1147
  }
1069
1148
  async getMany(options = {}) {
1070
- const { records } = await this.getPaginated(options);
1071
- 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;
1072
1154
  }
1073
- async getAll(chunk = PAGINATION_MAX_SIZE, options = {}) {
1155
+ async getAll(options = {}) {
1156
+ const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
1074
1157
  const results = [];
1075
- for await (const page of this.getIterator(chunk, options)) {
1158
+ for await (const page of this.getIterator({ ...rest, batchSize })) {
1076
1159
  results.push(...page);
1077
1160
  }
1078
1161
  return results;
1079
1162
  }
1080
1163
  async getFirst(options = {}) {
1081
- const records = await this.getMany({ ...options, page: { size: 1 } });
1082
- return records[0] || null;
1164
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1165
+ return records[0] ?? null;
1083
1166
  }
1084
1167
  cache(ttl) {
1085
- 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));
1086
1169
  }
1087
1170
  nextPage(size, offset) {
1088
1171
  return this.firstPage(size, offset);
@@ -1091,10 +1174,10 @@ const _Query = class {
1091
1174
  return this.firstPage(size, offset);
1092
1175
  }
1093
1176
  firstPage(size, offset) {
1094
- return this.getPaginated({ page: { size, offset } });
1177
+ return this.getPaginated({ pagination: { size, offset } });
1095
1178
  }
1096
1179
  lastPage(size, offset) {
1097
- return this.getPaginated({ page: { size, offset, before: "end" } });
1180
+ return this.getPaginated({ pagination: { size, offset, before: "end" } });
1098
1181
  }
1099
1182
  hasNextPage() {
1100
1183
  return this.meta.page.more;
@@ -1104,12 +1187,20 @@ let Query = _Query;
1104
1187
  _table$1 = new WeakMap();
1105
1188
  _repository = new WeakMap();
1106
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
+ }
1107
1196
 
1108
1197
  function isIdentifiable(x) {
1109
1198
  return isObject(x) && isString(x?.id);
1110
1199
  }
1111
1200
  function isXataRecord(x) {
1112
- 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";
1113
1204
  }
1114
1205
 
1115
1206
  function isSortFilterString(value) {
@@ -1139,7 +1230,7 @@ var __accessCheck$4 = (obj, member, msg) => {
1139
1230
  if (!member.has(obj))
1140
1231
  throw TypeError("Cannot " + msg);
1141
1232
  };
1142
- var __privateGet$3 = (obj, member, getter) => {
1233
+ var __privateGet$4 = (obj, member, getter) => {
1143
1234
  __accessCheck$4(obj, member, "read from private field");
1144
1235
  return getter ? getter.call(obj) : member.get(obj);
1145
1236
  };
@@ -1148,7 +1239,7 @@ var __privateAdd$4 = (obj, member, value) => {
1148
1239
  throw TypeError("Cannot add the same private member more than once");
1149
1240
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1150
1241
  };
1151
- var __privateSet$2 = (obj, member, value, setter) => {
1242
+ var __privateSet$4 = (obj, member, value, setter) => {
1152
1243
  __accessCheck$4(obj, member, "write to private field");
1153
1244
  setter ? setter.call(obj, value) : member.set(obj, value);
1154
1245
  return value;
@@ -1157,7 +1248,7 @@ var __privateMethod$2 = (obj, member, method) => {
1157
1248
  __accessCheck$4(obj, member, "access private method");
1158
1249
  return method;
1159
1250
  };
1160
- 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, _schemaTables$2, _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, _getSchemaTables$1, getSchemaTables_fn$1;
1161
1252
  class Repository extends Query {
1162
1253
  }
1163
1254
  class RestRepository extends Query {
@@ -1174,18 +1265,21 @@ class RestRepository extends Query {
1174
1265
  __privateAdd$4(this, _getCacheRecord);
1175
1266
  __privateAdd$4(this, _setCacheQuery);
1176
1267
  __privateAdd$4(this, _getCacheQuery);
1268
+ __privateAdd$4(this, _getSchemaTables$1);
1177
1269
  __privateAdd$4(this, _table, void 0);
1178
- __privateAdd$4(this, _links, void 0);
1179
1270
  __privateAdd$4(this, _getFetchProps, void 0);
1180
1271
  __privateAdd$4(this, _cache, void 0);
1181
- __privateSet$2(this, _table, options.table);
1182
- __privateSet$2(this, _links, options.links ?? {});
1183
- __privateSet$2(this, _getFetchProps, options.pluginOptions.getFetchProps);
1272
+ __privateAdd$4(this, _schemaTables$2, void 0);
1273
+ __privateSet$4(this, _table, options.table);
1274
+ __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1184
1275
  this.db = options.db;
1185
- __privateSet$2(this, _cache, options.pluginOptions.cache);
1276
+ __privateSet$4(this, _cache, options.pluginOptions.cache);
1277
+ __privateSet$4(this, _schemaTables$2, options.schemaTables);
1186
1278
  }
1187
1279
  async create(a, b) {
1188
1280
  if (Array.isArray(a)) {
1281
+ if (a.length === 0)
1282
+ return [];
1189
1283
  const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1190
1284
  await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1191
1285
  return records;
@@ -1211,26 +1305,38 @@ class RestRepository extends Query {
1211
1305
  }
1212
1306
  throw new Error("Invalid arguments for create method");
1213
1307
  }
1214
- async read(recordId) {
1215
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, recordId);
1216
- if (cacheRecord)
1217
- return cacheRecord;
1218
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1219
- try {
1220
- const response = await getRecord({
1221
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1222
- ...fetchProps
1223
- });
1224
- return initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), response);
1225
- } catch (e) {
1226
- if (isObject(e) && e.status === 404) {
1227
- return null;
1308
+ async read(a) {
1309
+ if (Array.isArray(a)) {
1310
+ if (a.length === 0)
1311
+ return [];
1312
+ const ids = a.map((item) => isString(item) ? item : item.id).filter((id2) => isString(id2));
1313
+ return this.getAll({ filter: { id: { $any: ids } } });
1314
+ }
1315
+ const id = isString(a) ? a : a.id;
1316
+ if (isString(id)) {
1317
+ const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, id);
1318
+ if (cacheRecord)
1319
+ return cacheRecord;
1320
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1321
+ try {
1322
+ const response = await getRecord({
1323
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: id },
1324
+ ...fetchProps
1325
+ });
1326
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1327
+ return initObject(this.db, schemaTables, __privateGet$4(this, _table), response);
1328
+ } catch (e) {
1329
+ if (isObject(e) && e.status === 404) {
1330
+ return null;
1331
+ }
1332
+ throw e;
1228
1333
  }
1229
- throw e;
1230
1334
  }
1231
1335
  }
1232
1336
  async update(a, b) {
1233
1337
  if (Array.isArray(a)) {
1338
+ if (a.length === 0)
1339
+ return [];
1234
1340
  if (a.length > 100) {
1235
1341
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1236
1342
  }
@@ -1252,6 +1358,8 @@ class RestRepository extends Query {
1252
1358
  }
1253
1359
  async createOrUpdate(a, b) {
1254
1360
  if (Array.isArray(a)) {
1361
+ if (a.length === 0)
1362
+ return [];
1255
1363
  if (a.length > 100) {
1256
1364
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1257
1365
  }
@@ -1273,6 +1381,8 @@ class RestRepository extends Query {
1273
1381
  }
1274
1382
  async delete(a) {
1275
1383
  if (Array.isArray(a)) {
1384
+ if (a.length === 0)
1385
+ return;
1276
1386
  if (a.length > 100) {
1277
1387
  console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1278
1388
  }
@@ -1292,13 +1402,19 @@ class RestRepository extends Query {
1292
1402
  throw new Error("Invalid arguments for delete method");
1293
1403
  }
1294
1404
  async search(query, options = {}) {
1295
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1296
- const { records } = await searchBranch({
1297
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1298
- body: { tables: [__privateGet$3(this, _table)], query, fuzziness: options.fuzziness },
1405
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1406
+ const { records } = await searchTable({
1407
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1408
+ body: {
1409
+ query,
1410
+ fuzziness: options.fuzziness,
1411
+ highlight: options.highlight,
1412
+ filter: options.filter
1413
+ },
1299
1414
  ...fetchProps
1300
1415
  });
1301
- return records.map((item) => initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), item));
1416
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1417
+ return records.map((item) => initObject(this.db, schemaTables, __privateGet$4(this, _table), item));
1302
1418
  }
1303
1419
  async query(query) {
1304
1420
  const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
@@ -1307,34 +1423,35 @@ class RestRepository extends Query {
1307
1423
  const data = query.getQueryOptions();
1308
1424
  const body = {
1309
1425
  filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1310
- sort: data.sort ? buildSortFilter(data.sort) : void 0,
1311
- page: data.page,
1426
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1427
+ page: data.pagination,
1312
1428
  columns: data.columns
1313
1429
  };
1314
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1430
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1315
1431
  const { meta, records: objects } = await queryTable({
1316
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table) },
1432
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1317
1433
  body,
1318
1434
  ...fetchProps
1319
1435
  });
1320
- const records = objects.map((record) => initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), record));
1436
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1437
+ const records = objects.map((record) => initObject(this.db, schemaTables, __privateGet$4(this, _table), record));
1321
1438
  await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1322
1439
  return new Page(query, meta, records);
1323
1440
  }
1324
1441
  }
1325
1442
  _table = new WeakMap();
1326
- _links = new WeakMap();
1327
1443
  _getFetchProps = new WeakMap();
1328
1444
  _cache = new WeakMap();
1445
+ _schemaTables$2 = new WeakMap();
1329
1446
  _insertRecordWithoutId = new WeakSet();
1330
1447
  insertRecordWithoutId_fn = async function(object) {
1331
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1448
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1332
1449
  const record = transformObjectLinks(object);
1333
1450
  const response = await insertRecord({
1334
1451
  pathParams: {
1335
1452
  workspace: "{workspaceId}",
1336
1453
  dbBranchName: "{dbBranch}",
1337
- tableName: __privateGet$3(this, _table)
1454
+ tableName: __privateGet$4(this, _table)
1338
1455
  },
1339
1456
  body: record,
1340
1457
  ...fetchProps
@@ -1347,13 +1464,13 @@ insertRecordWithoutId_fn = async function(object) {
1347
1464
  };
1348
1465
  _insertRecordWithId = new WeakSet();
1349
1466
  insertRecordWithId_fn = async function(recordId, object) {
1350
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1467
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1351
1468
  const record = transformObjectLinks(object);
1352
1469
  const response = await insertRecordWithID({
1353
1470
  pathParams: {
1354
1471
  workspace: "{workspaceId}",
1355
1472
  dbBranchName: "{dbBranch}",
1356
- tableName: __privateGet$3(this, _table),
1473
+ tableName: __privateGet$4(this, _table),
1357
1474
  recordId
1358
1475
  },
1359
1476
  body: record,
@@ -1368,25 +1485,29 @@ insertRecordWithId_fn = async function(recordId, object) {
1368
1485
  };
1369
1486
  _bulkInsertTableRecords = new WeakSet();
1370
1487
  bulkInsertTableRecords_fn = async function(objects) {
1371
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1488
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1372
1489
  const records = objects.map((object) => transformObjectLinks(object));
1373
- const response = await bulkInsertTableRecords({
1374
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table) },
1490
+ const { recordIDs } = await bulkInsertTableRecords({
1491
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1375
1492
  body: { records },
1376
1493
  ...fetchProps
1377
1494
  });
1378
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1495
+ const finalObjects = await this.read(recordIDs);
1379
1496
  if (finalObjects.length !== objects.length) {
1380
1497
  throw new Error("The server failed to save some records");
1381
1498
  }
1382
- return finalObjects;
1499
+ const dictionary = finalObjects.reduce((acc, object) => {
1500
+ acc[object.id] = object;
1501
+ return acc;
1502
+ }, {});
1503
+ return recordIDs.map((id) => dictionary[id]);
1383
1504
  };
1384
1505
  _updateRecordWithID = new WeakSet();
1385
1506
  updateRecordWithID_fn = async function(recordId, object) {
1386
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1507
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1387
1508
  const record = transformObjectLinks(object);
1388
1509
  const response = await updateRecordWithID({
1389
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1510
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1390
1511
  body: record,
1391
1512
  ...fetchProps
1392
1513
  });
@@ -1397,9 +1518,9 @@ updateRecordWithID_fn = async function(recordId, object) {
1397
1518
  };
1398
1519
  _upsertRecordWithID = new WeakSet();
1399
1520
  upsertRecordWithID_fn = async function(recordId, object) {
1400
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1521
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1401
1522
  const response = await upsertRecordWithID({
1402
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1523
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1403
1524
  body: object,
1404
1525
  ...fetchProps
1405
1526
  });
@@ -1410,51 +1531,63 @@ upsertRecordWithID_fn = async function(recordId, object) {
1410
1531
  };
1411
1532
  _deleteRecord = new WeakSet();
1412
1533
  deleteRecord_fn = async function(recordId) {
1413
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1534
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1414
1535
  await deleteRecord({
1415
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1536
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1416
1537
  ...fetchProps
1417
1538
  });
1418
1539
  };
1419
1540
  _invalidateCache = new WeakSet();
1420
1541
  invalidateCache_fn = async function(recordId) {
1421
- await __privateGet$3(this, _cache).delete(`rec_${__privateGet$3(this, _table)}:${recordId}`);
1422
- const cacheItems = await __privateGet$3(this, _cache).getAll();
1542
+ await __privateGet$4(this, _cache).delete(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1543
+ const cacheItems = await __privateGet$4(this, _cache).getAll();
1423
1544
  const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1424
1545
  for (const [key, value] of queries) {
1425
1546
  const ids = getIds(value);
1426
1547
  if (ids.includes(recordId))
1427
- await __privateGet$3(this, _cache).delete(key);
1548
+ await __privateGet$4(this, _cache).delete(key);
1428
1549
  }
1429
1550
  };
1430
1551
  _setCacheRecord = new WeakSet();
1431
1552
  setCacheRecord_fn = async function(record) {
1432
- if (!__privateGet$3(this, _cache).cacheRecords)
1553
+ if (!__privateGet$4(this, _cache).cacheRecords)
1433
1554
  return;
1434
- await __privateGet$3(this, _cache).set(`rec_${__privateGet$3(this, _table)}:${record.id}`, record);
1555
+ await __privateGet$4(this, _cache).set(`rec_${__privateGet$4(this, _table)}:${record.id}`, record);
1435
1556
  };
1436
1557
  _getCacheRecord = new WeakSet();
1437
1558
  getCacheRecord_fn = async function(recordId) {
1438
- if (!__privateGet$3(this, _cache).cacheRecords)
1559
+ if (!__privateGet$4(this, _cache).cacheRecords)
1439
1560
  return null;
1440
- return __privateGet$3(this, _cache).get(`rec_${__privateGet$3(this, _table)}:${recordId}`);
1561
+ return __privateGet$4(this, _cache).get(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1441
1562
  };
1442
1563
  _setCacheQuery = new WeakSet();
1443
1564
  setCacheQuery_fn = async function(query, meta, records) {
1444
- await __privateGet$3(this, _cache).set(`query_${__privateGet$3(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1565
+ await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1445
1566
  };
1446
1567
  _getCacheQuery = new WeakSet();
1447
1568
  getCacheQuery_fn = async function(query) {
1448
- const key = `query_${__privateGet$3(this, _table)}:${query.key()}`;
1449
- const result = await __privateGet$3(this, _cache).get(key);
1569
+ const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
1570
+ const result = await __privateGet$4(this, _cache).get(key);
1450
1571
  if (!result)
1451
1572
  return null;
1452
- const { cache: ttl = __privateGet$3(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1453
- if (!ttl || ttl < 0)
1454
- return result;
1573
+ const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1574
+ if (ttl < 0)
1575
+ return null;
1455
1576
  const hasExpired = result.date.getTime() + ttl < Date.now();
1456
1577
  return hasExpired ? null : result;
1457
1578
  };
1579
+ _getSchemaTables$1 = new WeakSet();
1580
+ getSchemaTables_fn$1 = async function() {
1581
+ if (__privateGet$4(this, _schemaTables$2))
1582
+ return __privateGet$4(this, _schemaTables$2);
1583
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1584
+ const { schema } = await getBranchDetails({
1585
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1586
+ ...fetchProps
1587
+ });
1588
+ __privateSet$4(this, _schemaTables$2, schema.tables);
1589
+ return schema.tables;
1590
+ };
1458
1591
  const transformObjectLinks = (object) => {
1459
1592
  return Object.entries(object).reduce((acc, [key, value]) => {
1460
1593
  if (key === "xata")
@@ -1462,15 +1595,34 @@ const transformObjectLinks = (object) => {
1462
1595
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1463
1596
  }, {});
1464
1597
  };
1465
- const initObject = (db, links, table, object) => {
1598
+ const initObject = (db, schemaTables, table, object) => {
1466
1599
  const result = {};
1467
- Object.assign(result, object);
1468
- const tableLinks = links[table] || [];
1469
- for (const link of tableLinks) {
1470
- const [field, linkTable] = link;
1471
- const value = result[field];
1472
- if (value && isObject(value)) {
1473
- result[field] = initObject(db, links, linkTable, value);
1600
+ const { xata, ...rest } = object ?? {};
1601
+ Object.assign(result, rest);
1602
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
1603
+ if (!columns)
1604
+ console.error(`Table ${table} not found in schema`);
1605
+ for (const column of columns ?? []) {
1606
+ const value = result[column.name];
1607
+ switch (column.type) {
1608
+ case "datetime": {
1609
+ const date = value !== void 0 ? new Date(value) : void 0;
1610
+ if (date && isNaN(date.getTime())) {
1611
+ console.error(`Failed to parse date ${value} for field ${column.name}`);
1612
+ } else if (date) {
1613
+ result[column.name] = date;
1614
+ }
1615
+ break;
1616
+ }
1617
+ case "link": {
1618
+ const linkTable = column.link?.table;
1619
+ if (!linkTable) {
1620
+ console.error(`Failed to parse link for field ${column.name}`);
1621
+ } else if (isObject(value)) {
1622
+ result[column.name] = initObject(db, schemaTables, linkTable, value);
1623
+ }
1624
+ break;
1625
+ }
1474
1626
  }
1475
1627
  }
1476
1628
  result.read = function() {
@@ -1482,7 +1634,10 @@ const initObject = (db, links, table, object) => {
1482
1634
  result.delete = function() {
1483
1635
  return db[table].delete(result["id"]);
1484
1636
  };
1485
- for (const prop of ["read", "update", "delete"]) {
1637
+ result.getMetadata = function() {
1638
+ return xata;
1639
+ };
1640
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1486
1641
  Object.defineProperty(result, prop, { enumerable: false });
1487
1642
  }
1488
1643
  Object.freeze(result);
@@ -1502,7 +1657,7 @@ var __accessCheck$3 = (obj, member, msg) => {
1502
1657
  if (!member.has(obj))
1503
1658
  throw TypeError("Cannot " + msg);
1504
1659
  };
1505
- var __privateGet$2 = (obj, member, getter) => {
1660
+ var __privateGet$3 = (obj, member, getter) => {
1506
1661
  __accessCheck$3(obj, member, "read from private field");
1507
1662
  return getter ? getter.call(obj) : member.get(obj);
1508
1663
  };
@@ -1511,7 +1666,7 @@ var __privateAdd$3 = (obj, member, value) => {
1511
1666
  throw TypeError("Cannot add the same private member more than once");
1512
1667
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1513
1668
  };
1514
- var __privateSet$1 = (obj, member, value, setter) => {
1669
+ var __privateSet$3 = (obj, member, value, setter) => {
1515
1670
  __accessCheck$3(obj, member, "write to private field");
1516
1671
  setter ? setter.call(obj, value) : member.set(obj, value);
1517
1672
  return value;
@@ -1520,30 +1675,30 @@ var _map;
1520
1675
  class SimpleCache {
1521
1676
  constructor(options = {}) {
1522
1677
  __privateAdd$3(this, _map, void 0);
1523
- __privateSet$1(this, _map, /* @__PURE__ */ new Map());
1678
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1524
1679
  this.capacity = options.max ?? 500;
1525
1680
  this.cacheRecords = options.cacheRecords ?? true;
1526
1681
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1527
1682
  }
1528
1683
  async getAll() {
1529
- return Object.fromEntries(__privateGet$2(this, _map));
1684
+ return Object.fromEntries(__privateGet$3(this, _map));
1530
1685
  }
1531
1686
  async get(key) {
1532
- return __privateGet$2(this, _map).get(key) ?? null;
1687
+ return __privateGet$3(this, _map).get(key) ?? null;
1533
1688
  }
1534
1689
  async set(key, value) {
1535
1690
  await this.delete(key);
1536
- __privateGet$2(this, _map).set(key, value);
1537
- if (__privateGet$2(this, _map).size > this.capacity) {
1538
- const leastRecentlyUsed = __privateGet$2(this, _map).keys().next().value;
1691
+ __privateGet$3(this, _map).set(key, value);
1692
+ if (__privateGet$3(this, _map).size > this.capacity) {
1693
+ const leastRecentlyUsed = __privateGet$3(this, _map).keys().next().value;
1539
1694
  await this.delete(leastRecentlyUsed);
1540
1695
  }
1541
1696
  }
1542
1697
  async delete(key) {
1543
- __privateGet$2(this, _map).delete(key);
1698
+ __privateGet$3(this, _map).delete(key);
1544
1699
  }
1545
1700
  async clear() {
1546
- return __privateGet$2(this, _map).clear();
1701
+ return __privateGet$3(this, _map).clear();
1547
1702
  }
1548
1703
  }
1549
1704
  _map = new WeakMap();
@@ -1571,7 +1726,7 @@ var __accessCheck$2 = (obj, member, msg) => {
1571
1726
  if (!member.has(obj))
1572
1727
  throw TypeError("Cannot " + msg);
1573
1728
  };
1574
- var __privateGet$1 = (obj, member, getter) => {
1729
+ var __privateGet$2 = (obj, member, getter) => {
1575
1730
  __accessCheck$2(obj, member, "read from private field");
1576
1731
  return getter ? getter.call(obj) : member.get(obj);
1577
1732
  };
@@ -1580,87 +1735,119 @@ var __privateAdd$2 = (obj, member, value) => {
1580
1735
  throw TypeError("Cannot add the same private member more than once");
1581
1736
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1582
1737
  };
1583
- var _tables;
1738
+ var __privateSet$2 = (obj, member, value, setter) => {
1739
+ __accessCheck$2(obj, member, "write to private field");
1740
+ setter ? setter.call(obj, value) : member.set(obj, value);
1741
+ return value;
1742
+ };
1743
+ var _tables, _schemaTables$1;
1584
1744
  class SchemaPlugin extends XataPlugin {
1585
- constructor(links, tableNames) {
1745
+ constructor(schemaTables) {
1586
1746
  super();
1587
- this.links = links;
1588
- this.tableNames = tableNames;
1589
1747
  __privateAdd$2(this, _tables, {});
1748
+ __privateAdd$2(this, _schemaTables$1, void 0);
1749
+ __privateSet$2(this, _schemaTables$1, schemaTables);
1590
1750
  }
1591
1751
  build(pluginOptions) {
1592
- const links = this.links;
1593
1752
  const db = new Proxy({}, {
1594
1753
  get: (_target, table) => {
1595
1754
  if (!isString(table))
1596
1755
  throw new Error("Invalid table name");
1597
- if (!__privateGet$1(this, _tables)[table]) {
1598
- __privateGet$1(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, links });
1756
+ if (__privateGet$2(this, _tables)[table] === void 0) {
1757
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table });
1599
1758
  }
1600
- return __privateGet$1(this, _tables)[table];
1759
+ return __privateGet$2(this, _tables)[table];
1601
1760
  }
1602
1761
  });
1603
- for (const table of this.tableNames ?? []) {
1604
- db[table] = new RestRepository({ db, pluginOptions, table, links });
1762
+ const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
1763
+ for (const table of tableNames) {
1764
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1605
1765
  }
1606
1766
  return db;
1607
1767
  }
1608
1768
  }
1609
1769
  _tables = new WeakMap();
1770
+ _schemaTables$1 = new WeakMap();
1610
1771
 
1611
1772
  var __accessCheck$1 = (obj, member, msg) => {
1612
1773
  if (!member.has(obj))
1613
1774
  throw TypeError("Cannot " + msg);
1614
1775
  };
1776
+ var __privateGet$1 = (obj, member, getter) => {
1777
+ __accessCheck$1(obj, member, "read from private field");
1778
+ return getter ? getter.call(obj) : member.get(obj);
1779
+ };
1615
1780
  var __privateAdd$1 = (obj, member, value) => {
1616
1781
  if (member.has(obj))
1617
1782
  throw TypeError("Cannot add the same private member more than once");
1618
1783
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1619
1784
  };
1785
+ var __privateSet$1 = (obj, member, value, setter) => {
1786
+ __accessCheck$1(obj, member, "write to private field");
1787
+ setter ? setter.call(obj, value) : member.set(obj, value);
1788
+ return value;
1789
+ };
1620
1790
  var __privateMethod$1 = (obj, member, method) => {
1621
1791
  __accessCheck$1(obj, member, "access private method");
1622
1792
  return method;
1623
1793
  };
1624
- var _search, search_fn;
1794
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1625
1795
  class SearchPlugin extends XataPlugin {
1626
- constructor(db, links) {
1796
+ constructor(db, schemaTables) {
1627
1797
  super();
1628
1798
  this.db = db;
1629
- this.links = links;
1630
1799
  __privateAdd$1(this, _search);
1800
+ __privateAdd$1(this, _getSchemaTables);
1801
+ __privateAdd$1(this, _schemaTables, void 0);
1802
+ __privateSet$1(this, _schemaTables, schemaTables);
1631
1803
  }
1632
1804
  build({ getFetchProps }) {
1633
1805
  return {
1634
1806
  all: async (query, options = {}) => {
1635
1807
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1808
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1636
1809
  return records.map((record) => {
1637
1810
  const { table = "orphan" } = record.xata;
1638
- return { table, record: initObject(this.db, this.links, table, record) };
1811
+ return { table, record: initObject(this.db, schemaTables, table, record) };
1639
1812
  });
1640
1813
  },
1641
1814
  byTable: async (query, options = {}) => {
1642
1815
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1816
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1643
1817
  return records.reduce((acc, record) => {
1644
1818
  const { table = "orphan" } = record.xata;
1645
1819
  const items = acc[table] ?? [];
1646
- const item = initObject(this.db, this.links, table, record);
1820
+ const item = initObject(this.db, schemaTables, table, record);
1647
1821
  return { ...acc, [table]: [...items, item] };
1648
1822
  }, {});
1649
1823
  }
1650
1824
  };
1651
1825
  }
1652
1826
  }
1827
+ _schemaTables = new WeakMap();
1653
1828
  _search = new WeakSet();
1654
1829
  search_fn = async function(query, options, getFetchProps) {
1655
1830
  const fetchProps = await getFetchProps();
1656
- const { tables, fuzziness } = options ?? {};
1831
+ const { tables, fuzziness, highlight } = options ?? {};
1657
1832
  const { records } = await searchBranch({
1658
1833
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1659
- body: { tables, query, fuzziness },
1834
+ body: { tables, query, fuzziness, highlight },
1660
1835
  ...fetchProps
1661
1836
  });
1662
1837
  return records;
1663
1838
  };
1839
+ _getSchemaTables = new WeakSet();
1840
+ getSchemaTables_fn = async function(getFetchProps) {
1841
+ if (__privateGet$1(this, _schemaTables))
1842
+ return __privateGet$1(this, _schemaTables);
1843
+ const fetchProps = await getFetchProps();
1844
+ const { schema } = await getBranchDetails({
1845
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1846
+ ...fetchProps
1847
+ });
1848
+ __privateSet$1(this, _schemaTables, schema.tables);
1849
+ return schema.tables;
1850
+ };
1664
1851
 
1665
1852
  const isBranchStrategyBuilder = (strategy) => {
1666
1853
  return typeof strategy === "function";
@@ -1672,30 +1859,39 @@ const envBranchNames = [
1672
1859
  "CF_PAGES_BRANCH",
1673
1860
  "BRANCH"
1674
1861
  ];
1675
- const defaultBranch = "main";
1676
1862
  async function getCurrentBranchName(options) {
1677
- const env = await getBranchByEnvVariable();
1678
- if (env)
1679
- return env;
1680
- const branch = await getGitBranch();
1681
- if (!branch)
1682
- return defaultBranch;
1683
- const details = await getDatabaseBranch(branch, options);
1684
- if (details)
1685
- return branch;
1686
- return defaultBranch;
1863
+ const env = getBranchByEnvVariable();
1864
+ if (env) {
1865
+ const details = await getDatabaseBranch(env, options);
1866
+ if (details)
1867
+ return env;
1868
+ console.warn(`Branch ${env} not found in Xata. Ignoring...`);
1869
+ }
1870
+ const gitBranch = await getGitBranch();
1871
+ return resolveXataBranch(gitBranch, options);
1687
1872
  }
1688
1873
  async function getCurrentBranchDetails(options) {
1689
- const env = await getBranchByEnvVariable();
1690
- if (env)
1691
- return getDatabaseBranch(env, options);
1692
- const branch = await getGitBranch();
1693
- if (!branch)
1694
- return getDatabaseBranch(defaultBranch, options);
1695
- const details = await getDatabaseBranch(branch, options);
1696
- if (details)
1697
- return details;
1698
- return getDatabaseBranch(defaultBranch, options);
1874
+ const branch = await getCurrentBranchName(options);
1875
+ return getDatabaseBranch(branch, options);
1876
+ }
1877
+ async function resolveXataBranch(gitBranch, options) {
1878
+ const databaseURL = options?.databaseURL || getDatabaseURL();
1879
+ const apiKey = options?.apiKey || getAPIKey();
1880
+ if (!databaseURL)
1881
+ throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
1882
+ if (!apiKey)
1883
+ throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
1884
+ const [protocol, , host, , dbName] = databaseURL.split("/");
1885
+ const [workspace] = host.split(".");
1886
+ const { branch } = await resolveBranch({
1887
+ apiKey,
1888
+ apiUrl: databaseURL,
1889
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
1890
+ workspacesApiUrl: `${protocol}//${host}`,
1891
+ pathParams: { dbName, workspace },
1892
+ queryParams: { gitBranch, fallbackBranch: getEnvVariable("XATA_FALLBACK_BRANCH") }
1893
+ });
1894
+ return branch;
1699
1895
  }
1700
1896
  async function getDatabaseBranch(branch, options) {
1701
1897
  const databaseURL = options?.databaseURL || getDatabaseURL();
@@ -1713,10 +1909,7 @@ async function getDatabaseBranch(branch, options) {
1713
1909
  apiUrl: databaseURL,
1714
1910
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1715
1911
  workspacesApiUrl: `${protocol}//${host}`,
1716
- pathParams: {
1717
- dbBranchName,
1718
- workspace
1719
- }
1912
+ pathParams: { dbBranchName, workspace }
1720
1913
  });
1721
1914
  } catch (err) {
1722
1915
  if (isObject(err) && err.status === 404)
@@ -1769,7 +1962,7 @@ var __privateMethod = (obj, member, method) => {
1769
1962
  const buildClient = (plugins) => {
1770
1963
  var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1771
1964
  return _a = class {
1772
- constructor(options = {}, links, tables) {
1965
+ constructor(options = {}, schemaTables) {
1773
1966
  __privateAdd(this, _parseOptions);
1774
1967
  __privateAdd(this, _getFetchProps);
1775
1968
  __privateAdd(this, _evaluateBranch);
@@ -1779,12 +1972,12 @@ const buildClient = (plugins) => {
1779
1972
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1780
1973
  cache: safeOptions.cache
1781
1974
  };
1782
- const db = new SchemaPlugin(links, tables).build(pluginOptions);
1783
- const search = new SearchPlugin(db, links ?? {}).build(pluginOptions);
1975
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
1976
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1784
1977
  this.db = db;
1785
1978
  this.search = search;
1786
1979
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
1787
- if (!namespace)
1980
+ if (namespace === void 0)
1788
1981
  continue;
1789
1982
  const result = namespace.build(pluginOptions);
1790
1983
  if (result instanceof Promise) {
@@ -1801,7 +1994,7 @@ const buildClient = (plugins) => {
1801
1994
  const databaseURL = options?.databaseURL || getDatabaseURL();
1802
1995
  const apiKey = options?.apiKey || getAPIKey();
1803
1996
  const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
1804
- const branch = async () => options?.branch ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1997
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1805
1998
  if (!databaseURL || !apiKey) {
1806
1999
  throw new Error("Options databaseURL and apiKey are required");
1807
2000
  }
@@ -1828,7 +2021,7 @@ const buildClient = (plugins) => {
1828
2021
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1829
2022
  if (__privateGet(this, _branch))
1830
2023
  return __privateGet(this, _branch);
1831
- if (!param)
2024
+ if (param === void 0)
1832
2025
  return void 0;
1833
2026
  const strategies = Array.isArray(param) ? [...param] : [param];
1834
2027
  const evaluateBranch = async (strategy) => {
@@ -1861,6 +2054,7 @@ exports.PAGINATION_MAX_OFFSET = PAGINATION_MAX_OFFSET;
1861
2054
  exports.PAGINATION_MAX_SIZE = PAGINATION_MAX_SIZE;
1862
2055
  exports.Page = Page;
1863
2056
  exports.Query = Query;
2057
+ exports.RecordArray = RecordArray;
1864
2058
  exports.Repository = Repository;
1865
2059
  exports.RestRepository = RestRepository;
1866
2060
  exports.SchemaPlugin = SchemaPlugin;
@@ -1925,6 +2119,7 @@ exports.insertRecord = insertRecord;
1925
2119
  exports.insertRecordWithID = insertRecordWithID;
1926
2120
  exports.inviteWorkspaceMember = inviteWorkspaceMember;
1927
2121
  exports.is = is;
2122
+ exports.isCursorPaginationOptions = isCursorPaginationOptions;
1928
2123
  exports.isIdentifiable = isIdentifiable;
1929
2124
  exports.isNot = isNot;
1930
2125
  exports.isXataRecord = isXataRecord;
@@ -1940,6 +2135,7 @@ exports.removeWorkspaceMember = removeWorkspaceMember;
1940
2135
  exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite;
1941
2136
  exports.resolveBranch = resolveBranch;
1942
2137
  exports.searchBranch = searchBranch;
2138
+ exports.searchTable = searchTable;
1943
2139
  exports.setTableSchema = setTableSchema;
1944
2140
  exports.startsWith = startsWith;
1945
2141
  exports.updateBranchMetadata = updateBranchMetadata;