@xata.io/client 0.0.0-alpha.vf2696e7 → 0.0.0-alpha.vf344dbc

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -7,8 +7,11 @@ function compact(arr) {
7
7
  function isObject(value) {
8
8
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
9
9
  }
10
+ function isDefined(value) {
11
+ return value !== null && value !== void 0;
12
+ }
10
13
  function isString(value) {
11
- return value !== void 0 && value !== null && typeof value === "string";
14
+ return isDefined(value) && typeof value === "string";
12
15
  }
13
16
  function toBase64(value) {
14
17
  try {
@@ -34,7 +37,10 @@ function getEnvVariable(name) {
34
37
  }
35
38
  async function getGitBranch() {
36
39
  try {
37
- return require("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
40
+ if (typeof require === "function") {
41
+ const req = require;
42
+ return req("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
43
+ }
38
44
  } catch (err) {
39
45
  }
40
46
  try {
@@ -67,7 +73,12 @@ function getFetchImplementation(userFetch) {
67
73
  return fetchImpl;
68
74
  }
69
75
 
70
- class FetcherError extends Error {
76
+ class ErrorWithCause extends Error {
77
+ constructor(message, options) {
78
+ super(message, options);
79
+ }
80
+ }
81
+ class FetcherError extends ErrorWithCause {
71
82
  constructor(status, data) {
72
83
  super(getMessage(data));
73
84
  this.status = status;
@@ -248,6 +259,14 @@ const deleteDatabase = (variables) => fetch$1({
248
259
  method: "delete",
249
260
  ...variables
250
261
  });
262
+ const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
263
+ const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
264
+ const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
265
+ const resolveBranch = (variables) => fetch$1({
266
+ url: "/dbs/{dbName}/resolveBranch",
267
+ method: "get",
268
+ ...variables
269
+ });
251
270
  const getBranchDetails = (variables) => fetch$1({
252
271
  url: "/db/{dbBranchName}",
253
272
  method: "get",
@@ -355,6 +374,11 @@ const queryTable = (variables) => fetch$1({
355
374
  method: "post",
356
375
  ...variables
357
376
  });
377
+ const searchTable = (variables) => fetch$1({
378
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
379
+ method: "post",
380
+ ...variables
381
+ });
358
382
  const searchBranch = (variables) => fetch$1({
359
383
  url: "/db/{dbBranchName}/search",
360
384
  method: "post",
@@ -376,7 +400,15 @@ const operationsByTag = {
376
400
  resendWorkspaceMemberInvite,
377
401
  acceptWorkspaceMemberInvite
378
402
  },
379
- database: { getDatabaseList, createDatabase, deleteDatabase },
403
+ database: {
404
+ getDatabaseList,
405
+ createDatabase,
406
+ deleteDatabase,
407
+ getGitBranchesMapping,
408
+ addGitBranchesEntry,
409
+ removeGitBranchesEntry,
410
+ resolveBranch
411
+ },
380
412
  branch: {
381
413
  getBranchList,
382
414
  getBranchDetails,
@@ -410,6 +442,7 @@ const operationsByTag = {
410
442
  getRecord,
411
443
  bulkInsertTableRecords,
412
444
  queryTable,
445
+ searchTable,
413
446
  searchBranch
414
447
  }
415
448
  };
@@ -443,7 +476,7 @@ var __accessCheck$7 = (obj, member, msg) => {
443
476
  if (!member.has(obj))
444
477
  throw TypeError("Cannot " + msg);
445
478
  };
446
- var __privateGet$6 = (obj, member, getter) => {
479
+ var __privateGet$7 = (obj, member, getter) => {
447
480
  __accessCheck$7(obj, member, "read from private field");
448
481
  return getter ? getter.call(obj) : member.get(obj);
449
482
  };
@@ -452,7 +485,7 @@ var __privateAdd$7 = (obj, member, value) => {
452
485
  throw TypeError("Cannot add the same private member more than once");
453
486
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
454
487
  };
455
- var __privateSet$5 = (obj, member, value, setter) => {
488
+ var __privateSet$6 = (obj, member, value, setter) => {
456
489
  __accessCheck$7(obj, member, "write to private field");
457
490
  setter ? setter.call(obj, value) : member.set(obj, value);
458
491
  return value;
@@ -467,7 +500,7 @@ class XataApiClient {
467
500
  if (!apiKey) {
468
501
  throw new Error("Could not resolve a valid apiKey");
469
502
  }
470
- __privateSet$5(this, _extraProps, {
503
+ __privateSet$6(this, _extraProps, {
471
504
  apiUrl: getHostUrl(provider, "main"),
472
505
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
473
506
  fetchImpl: getFetchImplementation(options.fetch),
@@ -475,34 +508,34 @@ class XataApiClient {
475
508
  });
476
509
  }
477
510
  get user() {
478
- if (!__privateGet$6(this, _namespaces).user)
479
- __privateGet$6(this, _namespaces).user = new UserApi(__privateGet$6(this, _extraProps));
480
- return __privateGet$6(this, _namespaces).user;
511
+ if (!__privateGet$7(this, _namespaces).user)
512
+ __privateGet$7(this, _namespaces).user = new UserApi(__privateGet$7(this, _extraProps));
513
+ return __privateGet$7(this, _namespaces).user;
481
514
  }
482
515
  get workspaces() {
483
- if (!__privateGet$6(this, _namespaces).workspaces)
484
- __privateGet$6(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$6(this, _extraProps));
485
- return __privateGet$6(this, _namespaces).workspaces;
516
+ if (!__privateGet$7(this, _namespaces).workspaces)
517
+ __privateGet$7(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$7(this, _extraProps));
518
+ return __privateGet$7(this, _namespaces).workspaces;
486
519
  }
487
520
  get databases() {
488
- if (!__privateGet$6(this, _namespaces).databases)
489
- __privateGet$6(this, _namespaces).databases = new DatabaseApi(__privateGet$6(this, _extraProps));
490
- return __privateGet$6(this, _namespaces).databases;
521
+ if (!__privateGet$7(this, _namespaces).databases)
522
+ __privateGet$7(this, _namespaces).databases = new DatabaseApi(__privateGet$7(this, _extraProps));
523
+ return __privateGet$7(this, _namespaces).databases;
491
524
  }
492
525
  get branches() {
493
- if (!__privateGet$6(this, _namespaces).branches)
494
- __privateGet$6(this, _namespaces).branches = new BranchApi(__privateGet$6(this, _extraProps));
495
- return __privateGet$6(this, _namespaces).branches;
526
+ if (!__privateGet$7(this, _namespaces).branches)
527
+ __privateGet$7(this, _namespaces).branches = new BranchApi(__privateGet$7(this, _extraProps));
528
+ return __privateGet$7(this, _namespaces).branches;
496
529
  }
497
530
  get tables() {
498
- if (!__privateGet$6(this, _namespaces).tables)
499
- __privateGet$6(this, _namespaces).tables = new TableApi(__privateGet$6(this, _extraProps));
500
- return __privateGet$6(this, _namespaces).tables;
531
+ if (!__privateGet$7(this, _namespaces).tables)
532
+ __privateGet$7(this, _namespaces).tables = new TableApi(__privateGet$7(this, _extraProps));
533
+ return __privateGet$7(this, _namespaces).tables;
501
534
  }
502
535
  get records() {
503
- if (!__privateGet$6(this, _namespaces).records)
504
- __privateGet$6(this, _namespaces).records = new RecordsApi(__privateGet$6(this, _extraProps));
505
- return __privateGet$6(this, _namespaces).records;
536
+ if (!__privateGet$7(this, _namespaces).records)
537
+ __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
538
+ return __privateGet$7(this, _namespaces).records;
506
539
  }
507
540
  }
508
541
  _extraProps = new WeakMap();
@@ -636,6 +669,33 @@ class DatabaseApi {
636
669
  ...this.extraProps
637
670
  });
638
671
  }
672
+ getGitBranchesMapping(workspace, dbName) {
673
+ return operationsByTag.database.getGitBranchesMapping({
674
+ pathParams: { workspace, dbName },
675
+ ...this.extraProps
676
+ });
677
+ }
678
+ addGitBranchesEntry(workspace, dbName, body) {
679
+ return operationsByTag.database.addGitBranchesEntry({
680
+ pathParams: { workspace, dbName },
681
+ body,
682
+ ...this.extraProps
683
+ });
684
+ }
685
+ removeGitBranchesEntry(workspace, dbName, gitBranch) {
686
+ return operationsByTag.database.removeGitBranchesEntry({
687
+ pathParams: { workspace, dbName },
688
+ queryParams: { gitBranch },
689
+ ...this.extraProps
690
+ });
691
+ }
692
+ resolveBranch(workspace, dbName, gitBranch) {
693
+ return operationsByTag.database.resolveBranch({
694
+ pathParams: { workspace, dbName },
695
+ queryParams: { gitBranch },
696
+ ...this.extraProps
697
+ });
698
+ }
639
699
  }
640
700
  class BranchApi {
641
701
  constructor(extraProps) {
@@ -653,10 +713,10 @@ class BranchApi {
653
713
  ...this.extraProps
654
714
  });
655
715
  }
656
- createBranch(workspace, database, branch, from = "", options = {}) {
716
+ createBranch(workspace, database, branch, from, options = {}) {
657
717
  return operationsByTag.branch.createBranch({
658
718
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
659
- queryParams: { from },
719
+ queryParams: isString(from) ? { from } : void 0,
660
720
  body: options,
661
721
  ...this.extraProps
662
722
  });
@@ -838,6 +898,13 @@ class RecordsApi {
838
898
  ...this.extraProps
839
899
  });
840
900
  }
901
+ searchTable(workspace, database, branch, tableName, query) {
902
+ return operationsByTag.records.searchTable({
903
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
904
+ body: query,
905
+ ...this.extraProps
906
+ });
907
+ }
841
908
  searchBranch(workspace, database, branch, query) {
842
909
  return operationsByTag.records.searchBranch({
843
910
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -861,7 +928,7 @@ var __accessCheck$6 = (obj, member, msg) => {
861
928
  if (!member.has(obj))
862
929
  throw TypeError("Cannot " + msg);
863
930
  };
864
- var __privateGet$5 = (obj, member, getter) => {
931
+ var __privateGet$6 = (obj, member, getter) => {
865
932
  __accessCheck$6(obj, member, "read from private field");
866
933
  return getter ? getter.call(obj) : member.get(obj);
867
934
  };
@@ -870,30 +937,30 @@ var __privateAdd$6 = (obj, member, value) => {
870
937
  throw TypeError("Cannot add the same private member more than once");
871
938
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
872
939
  };
873
- var __privateSet$4 = (obj, member, value, setter) => {
940
+ var __privateSet$5 = (obj, member, value, setter) => {
874
941
  __accessCheck$6(obj, member, "write to private field");
875
942
  setter ? setter.call(obj, value) : member.set(obj, value);
876
943
  return value;
877
944
  };
878
- var _query;
945
+ var _query, _page;
879
946
  class Page {
880
947
  constructor(query, meta, records = []) {
881
948
  __privateAdd$6(this, _query, void 0);
882
- __privateSet$4(this, _query, query);
949
+ __privateSet$5(this, _query, query);
883
950
  this.meta = meta;
884
- this.records = records;
951
+ this.records = new RecordArray(this, records);
885
952
  }
886
953
  async nextPage(size, offset) {
887
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, after: this.meta.page.cursor } });
954
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
888
955
  }
889
956
  async previousPage(size, offset) {
890
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, before: this.meta.page.cursor } });
957
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
891
958
  }
892
959
  async firstPage(size, offset) {
893
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, first: this.meta.page.cursor } });
960
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
894
961
  }
895
962
  async lastPage(size, offset) {
896
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, last: this.meta.page.cursor } });
963
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
897
964
  }
898
965
  hasNextPage() {
899
966
  return this.meta.page.more;
@@ -901,15 +968,46 @@ class Page {
901
968
  }
902
969
  _query = new WeakMap();
903
970
  const PAGINATION_MAX_SIZE = 200;
904
- const PAGINATION_DEFAULT_SIZE = 200;
971
+ const PAGINATION_DEFAULT_SIZE = 20;
905
972
  const PAGINATION_MAX_OFFSET = 800;
906
973
  const PAGINATION_DEFAULT_OFFSET = 0;
974
+ function isCursorPaginationOptions(options) {
975
+ return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
976
+ }
977
+ const _RecordArray = class extends Array {
978
+ constructor(page, overrideRecords) {
979
+ super(...overrideRecords ?? page.records);
980
+ __privateAdd$6(this, _page, void 0);
981
+ __privateSet$5(this, _page, page);
982
+ }
983
+ async nextPage(size, offset) {
984
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
985
+ return new _RecordArray(newPage);
986
+ }
987
+ async previousPage(size, offset) {
988
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
989
+ return new _RecordArray(newPage);
990
+ }
991
+ async firstPage(size, offset) {
992
+ const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
993
+ return new _RecordArray(newPage);
994
+ }
995
+ async lastPage(size, offset) {
996
+ const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
997
+ return new _RecordArray(newPage);
998
+ }
999
+ hasNextPage() {
1000
+ return __privateGet$6(this, _page).meta.page.more;
1001
+ }
1002
+ };
1003
+ let RecordArray = _RecordArray;
1004
+ _page = new WeakMap();
907
1005
 
908
1006
  var __accessCheck$5 = (obj, member, msg) => {
909
1007
  if (!member.has(obj))
910
1008
  throw TypeError("Cannot " + msg);
911
1009
  };
912
- var __privateGet$4 = (obj, member, getter) => {
1010
+ var __privateGet$5 = (obj, member, getter) => {
913
1011
  __accessCheck$5(obj, member, "read from private field");
914
1012
  return getter ? getter.call(obj) : member.get(obj);
915
1013
  };
@@ -918,34 +1016,35 @@ var __privateAdd$5 = (obj, member, value) => {
918
1016
  throw TypeError("Cannot add the same private member more than once");
919
1017
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
920
1018
  };
921
- var __privateSet$3 = (obj, member, value, setter) => {
1019
+ var __privateSet$4 = (obj, member, value, setter) => {
922
1020
  __accessCheck$5(obj, member, "write to private field");
923
1021
  setter ? setter.call(obj, value) : member.set(obj, value);
924
1022
  return value;
925
1023
  };
926
1024
  var _table$1, _repository, _data;
927
1025
  const _Query = class {
928
- constructor(repository, table, data, parent) {
1026
+ constructor(repository, table, data, rawParent) {
929
1027
  __privateAdd$5(this, _table$1, void 0);
930
1028
  __privateAdd$5(this, _repository, void 0);
931
1029
  __privateAdd$5(this, _data, { filter: {} });
932
1030
  this.meta = { page: { cursor: "start", more: true } };
933
- this.records = [];
934
- __privateSet$3(this, _table$1, table);
1031
+ this.records = new RecordArray(this, []);
1032
+ __privateSet$4(this, _table$1, table);
935
1033
  if (repository) {
936
- __privateSet$3(this, _repository, repository);
1034
+ __privateSet$4(this, _repository, repository);
937
1035
  } else {
938
- __privateSet$3(this, _repository, this);
1036
+ __privateSet$4(this, _repository, this);
939
1037
  }
940
- __privateGet$4(this, _data).filter = data.filter ?? parent?.filter ?? {};
941
- __privateGet$4(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
942
- __privateGet$4(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
943
- __privateGet$4(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
944
- __privateGet$4(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
945
- __privateGet$4(this, _data).sort = data.sort ?? parent?.sort;
946
- __privateGet$4(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
947
- __privateGet$4(this, _data).page = data.page ?? parent?.page;
948
- __privateGet$4(this, _data).cache = data.cache ?? parent?.cache;
1038
+ const parent = cleanParent(data, rawParent);
1039
+ __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
1040
+ __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
1041
+ __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
1042
+ __privateGet$5(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
1043
+ __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1044
+ __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1045
+ __privateGet$5(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
1046
+ __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1047
+ __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
949
1048
  this.any = this.any.bind(this);
950
1049
  this.all = this.all.bind(this);
951
1050
  this.not = this.not.bind(this);
@@ -956,83 +1055,88 @@ const _Query = class {
956
1055
  Object.defineProperty(this, "repository", { enumerable: false });
957
1056
  }
958
1057
  getQueryOptions() {
959
- return __privateGet$4(this, _data);
1058
+ return __privateGet$5(this, _data);
960
1059
  }
961
1060
  key() {
962
- const { columns = [], filter = {}, sort = [], page = {} } = __privateGet$4(this, _data);
963
- const key = JSON.stringify({ columns, filter, sort, page });
1061
+ const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$5(this, _data);
1062
+ const key = JSON.stringify({ columns, filter, sort, pagination });
964
1063
  return toBase64(key);
965
1064
  }
966
1065
  any(...queries) {
967
1066
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
968
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $any } }, __privateGet$4(this, _data));
1067
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
969
1068
  }
970
1069
  all(...queries) {
971
1070
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
972
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1071
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
973
1072
  }
974
1073
  not(...queries) {
975
1074
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
976
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $not } }, __privateGet$4(this, _data));
1075
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
977
1076
  }
978
1077
  none(...queries) {
979
1078
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
980
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $none } }, __privateGet$4(this, _data));
1079
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
981
1080
  }
982
1081
  filter(a, b) {
983
1082
  if (arguments.length === 1) {
984
1083
  const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
985
- const $all = compact([__privateGet$4(this, _data).filter?.$all].flat().concat(constraints));
986
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1084
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1085
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
987
1086
  } else {
988
- const $all = compact([__privateGet$4(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
989
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1087
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
1088
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
990
1089
  }
991
1090
  }
992
1091
  sort(column, direction) {
993
- const originalSort = [__privateGet$4(this, _data).sort ?? []].flat();
1092
+ const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
994
1093
  const sort = [...originalSort, { column, direction }];
995
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { sort }, __privateGet$4(this, _data));
1094
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
996
1095
  }
997
1096
  select(columns) {
998
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { columns }, __privateGet$4(this, _data));
1097
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { columns }, __privateGet$5(this, _data));
999
1098
  }
1000
1099
  getPaginated(options = {}) {
1001
- const query = new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), options, __privateGet$4(this, _data));
1002
- return __privateGet$4(this, _repository).query(query);
1100
+ const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
1101
+ return __privateGet$5(this, _repository).query(query);
1003
1102
  }
1004
1103
  async *[Symbol.asyncIterator]() {
1005
- for await (const [record] of this.getIterator(1)) {
1104
+ for await (const [record] of this.getIterator({ batchSize: 1 })) {
1006
1105
  yield record;
1007
1106
  }
1008
1107
  }
1009
- async *getIterator(chunk, options = {}) {
1010
- let offset = 0;
1011
- let end = false;
1012
- while (!end) {
1013
- const { records, meta } = await this.getPaginated({ ...options, page: { size: chunk, offset } });
1014
- yield records;
1015
- offset += chunk;
1016
- end = !meta.page.more;
1108
+ async *getIterator(options = {}) {
1109
+ const { batchSize = 1 } = options;
1110
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
1111
+ let more = page.hasNextPage();
1112
+ yield page.records;
1113
+ while (more) {
1114
+ page = await page.nextPage();
1115
+ more = page.hasNextPage();
1116
+ yield page.records;
1017
1117
  }
1018
1118
  }
1019
1119
  async getMany(options = {}) {
1020
- const { records } = await this.getPaginated(options);
1021
- return records;
1120
+ const page = await this.getPaginated(options);
1121
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1122
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1123
+ }
1124
+ return page.records;
1022
1125
  }
1023
- async getAll(chunk = PAGINATION_MAX_SIZE, options = {}) {
1126
+ async getAll(options = {}) {
1127
+ const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
1024
1128
  const results = [];
1025
- for await (const page of this.getIterator(chunk, options)) {
1129
+ for await (const page of this.getIterator({ ...rest, batchSize })) {
1026
1130
  results.push(...page);
1027
1131
  }
1028
1132
  return results;
1029
1133
  }
1030
1134
  async getFirst(options = {}) {
1031
- const records = await this.getMany({ ...options, page: { size: 1 } });
1032
- return records[0] || null;
1135
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1136
+ return records[0] ?? null;
1033
1137
  }
1034
1138
  cache(ttl) {
1035
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { cache: ttl }, __privateGet$4(this, _data));
1139
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1036
1140
  }
1037
1141
  nextPage(size, offset) {
1038
1142
  return this.firstPage(size, offset);
@@ -1041,10 +1145,10 @@ const _Query = class {
1041
1145
  return this.firstPage(size, offset);
1042
1146
  }
1043
1147
  firstPage(size, offset) {
1044
- return this.getPaginated({ page: { size, offset } });
1148
+ return this.getPaginated({ pagination: { size, offset } });
1045
1149
  }
1046
1150
  lastPage(size, offset) {
1047
- return this.getPaginated({ page: { size, offset, before: "end" } });
1151
+ return this.getPaginated({ pagination: { size, offset, before: "end" } });
1048
1152
  }
1049
1153
  hasNextPage() {
1050
1154
  return this.meta.page.more;
@@ -1054,12 +1158,20 @@ let Query = _Query;
1054
1158
  _table$1 = new WeakMap();
1055
1159
  _repository = new WeakMap();
1056
1160
  _data = new WeakMap();
1161
+ function cleanParent(data, parent) {
1162
+ if (isCursorPaginationOptions(data.pagination)) {
1163
+ return { ...parent, sorting: void 0, filter: void 0 };
1164
+ }
1165
+ return parent;
1166
+ }
1057
1167
 
1058
1168
  function isIdentifiable(x) {
1059
1169
  return isObject(x) && isString(x?.id);
1060
1170
  }
1061
1171
  function isXataRecord(x) {
1062
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1172
+ const record = x;
1173
+ const metadata = record?.getMetadata();
1174
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1063
1175
  }
1064
1176
 
1065
1177
  function isSortFilterString(value) {
@@ -1089,7 +1201,7 @@ var __accessCheck$4 = (obj, member, msg) => {
1089
1201
  if (!member.has(obj))
1090
1202
  throw TypeError("Cannot " + msg);
1091
1203
  };
1092
- var __privateGet$3 = (obj, member, getter) => {
1204
+ var __privateGet$4 = (obj, member, getter) => {
1093
1205
  __accessCheck$4(obj, member, "read from private field");
1094
1206
  return getter ? getter.call(obj) : member.get(obj);
1095
1207
  };
@@ -1098,7 +1210,7 @@ var __privateAdd$4 = (obj, member, value) => {
1098
1210
  throw TypeError("Cannot add the same private member more than once");
1099
1211
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1100
1212
  };
1101
- var __privateSet$2 = (obj, member, value, setter) => {
1213
+ var __privateSet$3 = (obj, member, value, setter) => {
1102
1214
  __accessCheck$4(obj, member, "write to private field");
1103
1215
  setter ? setter.call(obj, value) : member.set(obj, value);
1104
1216
  return value;
@@ -1107,7 +1219,7 @@ var __privateMethod$2 = (obj, member, method) => {
1107
1219
  __accessCheck$4(obj, member, "access private method");
1108
1220
  return method;
1109
1221
  };
1110
- 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;
1222
+ 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;
1111
1223
  class Repository extends Query {
1112
1224
  }
1113
1225
  class RestRepository extends Query {
@@ -1124,18 +1236,20 @@ class RestRepository extends Query {
1124
1236
  __privateAdd$4(this, _getCacheRecord);
1125
1237
  __privateAdd$4(this, _setCacheQuery);
1126
1238
  __privateAdd$4(this, _getCacheQuery);
1239
+ __privateAdd$4(this, _getSchema$1);
1127
1240
  __privateAdd$4(this, _table, void 0);
1128
- __privateAdd$4(this, _links, void 0);
1129
1241
  __privateAdd$4(this, _getFetchProps, void 0);
1130
1242
  __privateAdd$4(this, _cache, void 0);
1131
- __privateSet$2(this, _table, options.table);
1132
- __privateSet$2(this, _links, options.links ?? {});
1133
- __privateSet$2(this, _getFetchProps, options.pluginOptions.getFetchProps);
1243
+ __privateAdd$4(this, _schema$1, void 0);
1244
+ __privateSet$3(this, _table, options.table);
1245
+ __privateSet$3(this, _getFetchProps, options.pluginOptions.getFetchProps);
1134
1246
  this.db = options.db;
1135
- __privateSet$2(this, _cache, options.pluginOptions.cache);
1247
+ __privateSet$3(this, _cache, options.pluginOptions.cache);
1136
1248
  }
1137
1249
  async create(a, b) {
1138
1250
  if (Array.isArray(a)) {
1251
+ if (a.length === 0)
1252
+ return [];
1139
1253
  const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1140
1254
  await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1141
1255
  return records;
@@ -1161,26 +1275,36 @@ class RestRepository extends Query {
1161
1275
  }
1162
1276
  throw new Error("Invalid arguments for create method");
1163
1277
  }
1164
- async read(recordId) {
1165
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, recordId);
1166
- if (cacheRecord)
1167
- return cacheRecord;
1168
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1169
- try {
1170
- const response = await getRecord({
1171
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1172
- ...fetchProps
1173
- });
1174
- return initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), response);
1175
- } catch (e) {
1176
- if (isObject(e) && e.status === 404) {
1177
- return null;
1278
+ async read(a) {
1279
+ if (Array.isArray(a)) {
1280
+ if (a.length === 0)
1281
+ return [];
1282
+ return this.getAll({ filter: { id: { $any: a } } });
1283
+ }
1284
+ if (isString(a)) {
1285
+ const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, a);
1286
+ if (cacheRecord)
1287
+ return cacheRecord;
1288
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1289
+ try {
1290
+ const response = await getRecord({
1291
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: a },
1292
+ ...fetchProps
1293
+ });
1294
+ const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1295
+ return initObject(this.db, schema, __privateGet$4(this, _table), response);
1296
+ } catch (e) {
1297
+ if (isObject(e) && e.status === 404) {
1298
+ return null;
1299
+ }
1300
+ throw e;
1178
1301
  }
1179
- throw e;
1180
1302
  }
1181
1303
  }
1182
1304
  async update(a, b) {
1183
1305
  if (Array.isArray(a)) {
1306
+ if (a.length === 0)
1307
+ return [];
1184
1308
  if (a.length > 100) {
1185
1309
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1186
1310
  }
@@ -1202,6 +1326,8 @@ class RestRepository extends Query {
1202
1326
  }
1203
1327
  async createOrUpdate(a, b) {
1204
1328
  if (Array.isArray(a)) {
1329
+ if (a.length === 0)
1330
+ return [];
1205
1331
  if (a.length > 100) {
1206
1332
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1207
1333
  }
@@ -1223,6 +1349,8 @@ class RestRepository extends Query {
1223
1349
  }
1224
1350
  async delete(a) {
1225
1351
  if (Array.isArray(a)) {
1352
+ if (a.length === 0)
1353
+ return;
1226
1354
  if (a.length > 100) {
1227
1355
  console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1228
1356
  }
@@ -1242,13 +1370,19 @@ class RestRepository extends Query {
1242
1370
  throw new Error("Invalid arguments for delete method");
1243
1371
  }
1244
1372
  async search(query, options = {}) {
1245
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1246
- const { records } = await searchBranch({
1247
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1248
- body: { tables: [__privateGet$3(this, _table)], query, fuzziness: options.fuzziness },
1373
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1374
+ const { records } = await searchTable({
1375
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1376
+ body: {
1377
+ query,
1378
+ fuzziness: options.fuzziness,
1379
+ highlight: options.highlight,
1380
+ filter: options.filter
1381
+ },
1249
1382
  ...fetchProps
1250
1383
  });
1251
- return records.map((item) => initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), item));
1384
+ const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1385
+ return records.map((item) => initObject(this.db, schema, __privateGet$4(this, _table), item));
1252
1386
  }
1253
1387
  async query(query) {
1254
1388
  const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
@@ -1257,34 +1391,35 @@ class RestRepository extends Query {
1257
1391
  const data = query.getQueryOptions();
1258
1392
  const body = {
1259
1393
  filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1260
- sort: data.sort ? buildSortFilter(data.sort) : void 0,
1261
- page: data.page,
1394
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1395
+ page: data.pagination,
1262
1396
  columns: data.columns
1263
1397
  };
1264
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1398
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1265
1399
  const { meta, records: objects } = await queryTable({
1266
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table) },
1400
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1267
1401
  body,
1268
1402
  ...fetchProps
1269
1403
  });
1270
- const records = objects.map((record) => initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), record));
1404
+ const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1405
+ const records = objects.map((record) => initObject(this.db, schema, __privateGet$4(this, _table), record));
1271
1406
  await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1272
1407
  return new Page(query, meta, records);
1273
1408
  }
1274
1409
  }
1275
1410
  _table = new WeakMap();
1276
- _links = new WeakMap();
1277
1411
  _getFetchProps = new WeakMap();
1278
1412
  _cache = new WeakMap();
1413
+ _schema$1 = new WeakMap();
1279
1414
  _insertRecordWithoutId = new WeakSet();
1280
1415
  insertRecordWithoutId_fn = async function(object) {
1281
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1416
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1282
1417
  const record = transformObjectLinks(object);
1283
1418
  const response = await insertRecord({
1284
1419
  pathParams: {
1285
1420
  workspace: "{workspaceId}",
1286
1421
  dbBranchName: "{dbBranch}",
1287
- tableName: __privateGet$3(this, _table)
1422
+ tableName: __privateGet$4(this, _table)
1288
1423
  },
1289
1424
  body: record,
1290
1425
  ...fetchProps
@@ -1297,13 +1432,13 @@ insertRecordWithoutId_fn = async function(object) {
1297
1432
  };
1298
1433
  _insertRecordWithId = new WeakSet();
1299
1434
  insertRecordWithId_fn = async function(recordId, object) {
1300
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1435
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1301
1436
  const record = transformObjectLinks(object);
1302
1437
  const response = await insertRecordWithID({
1303
1438
  pathParams: {
1304
1439
  workspace: "{workspaceId}",
1305
1440
  dbBranchName: "{dbBranch}",
1306
- tableName: __privateGet$3(this, _table),
1441
+ tableName: __privateGet$4(this, _table),
1307
1442
  recordId
1308
1443
  },
1309
1444
  body: record,
@@ -1318,10 +1453,10 @@ insertRecordWithId_fn = async function(recordId, object) {
1318
1453
  };
1319
1454
  _bulkInsertTableRecords = new WeakSet();
1320
1455
  bulkInsertTableRecords_fn = async function(objects) {
1321
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1456
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1322
1457
  const records = objects.map((object) => transformObjectLinks(object));
1323
1458
  const response = await bulkInsertTableRecords({
1324
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table) },
1459
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1325
1460
  body: { records },
1326
1461
  ...fetchProps
1327
1462
  });
@@ -1333,10 +1468,10 @@ bulkInsertTableRecords_fn = async function(objects) {
1333
1468
  };
1334
1469
  _updateRecordWithID = new WeakSet();
1335
1470
  updateRecordWithID_fn = async function(recordId, object) {
1336
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1471
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1337
1472
  const record = transformObjectLinks(object);
1338
1473
  const response = await updateRecordWithID({
1339
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1474
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1340
1475
  body: record,
1341
1476
  ...fetchProps
1342
1477
  });
@@ -1347,9 +1482,9 @@ updateRecordWithID_fn = async function(recordId, object) {
1347
1482
  };
1348
1483
  _upsertRecordWithID = new WeakSet();
1349
1484
  upsertRecordWithID_fn = async function(recordId, object) {
1350
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1485
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1351
1486
  const response = await upsertRecordWithID({
1352
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1487
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1353
1488
  body: object,
1354
1489
  ...fetchProps
1355
1490
  });
@@ -1360,51 +1495,63 @@ upsertRecordWithID_fn = async function(recordId, object) {
1360
1495
  };
1361
1496
  _deleteRecord = new WeakSet();
1362
1497
  deleteRecord_fn = async function(recordId) {
1363
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1498
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1364
1499
  await deleteRecord({
1365
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1500
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1366
1501
  ...fetchProps
1367
1502
  });
1368
1503
  };
1369
1504
  _invalidateCache = new WeakSet();
1370
1505
  invalidateCache_fn = async function(recordId) {
1371
- await __privateGet$3(this, _cache).delete(`rec_${__privateGet$3(this, _table)}:${recordId}`);
1372
- const cacheItems = await __privateGet$3(this, _cache).getAll();
1506
+ await __privateGet$4(this, _cache).delete(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1507
+ const cacheItems = await __privateGet$4(this, _cache).getAll();
1373
1508
  const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1374
1509
  for (const [key, value] of queries) {
1375
1510
  const ids = getIds(value);
1376
1511
  if (ids.includes(recordId))
1377
- await __privateGet$3(this, _cache).delete(key);
1512
+ await __privateGet$4(this, _cache).delete(key);
1378
1513
  }
1379
1514
  };
1380
1515
  _setCacheRecord = new WeakSet();
1381
1516
  setCacheRecord_fn = async function(record) {
1382
- if (!__privateGet$3(this, _cache).cacheRecords)
1517
+ if (!__privateGet$4(this, _cache).cacheRecords)
1383
1518
  return;
1384
- await __privateGet$3(this, _cache).set(`rec_${__privateGet$3(this, _table)}:${record.id}`, record);
1519
+ await __privateGet$4(this, _cache).set(`rec_${__privateGet$4(this, _table)}:${record.id}`, record);
1385
1520
  };
1386
1521
  _getCacheRecord = new WeakSet();
1387
1522
  getCacheRecord_fn = async function(recordId) {
1388
- if (!__privateGet$3(this, _cache).cacheRecords)
1523
+ if (!__privateGet$4(this, _cache).cacheRecords)
1389
1524
  return null;
1390
- return __privateGet$3(this, _cache).get(`rec_${__privateGet$3(this, _table)}:${recordId}`);
1525
+ return __privateGet$4(this, _cache).get(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1391
1526
  };
1392
1527
  _setCacheQuery = new WeakSet();
1393
1528
  setCacheQuery_fn = async function(query, meta, records) {
1394
- await __privateGet$3(this, _cache).set(`query_${__privateGet$3(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1529
+ await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1395
1530
  };
1396
1531
  _getCacheQuery = new WeakSet();
1397
1532
  getCacheQuery_fn = async function(query) {
1398
- const key = `query_${__privateGet$3(this, _table)}:${query.key()}`;
1399
- const result = await __privateGet$3(this, _cache).get(key);
1533
+ const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
1534
+ const result = await __privateGet$4(this, _cache).get(key);
1400
1535
  if (!result)
1401
1536
  return null;
1402
- const { cache: ttl = __privateGet$3(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1403
- if (!ttl || ttl < 0)
1404
- return result;
1537
+ const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1538
+ if (ttl < 0)
1539
+ return null;
1405
1540
  const hasExpired = result.date.getTime() + ttl < Date.now();
1406
1541
  return hasExpired ? null : result;
1407
1542
  };
1543
+ _getSchema$1 = new WeakSet();
1544
+ getSchema_fn$1 = async function() {
1545
+ if (__privateGet$4(this, _schema$1))
1546
+ return __privateGet$4(this, _schema$1);
1547
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1548
+ const { schema } = await getBranchDetails({
1549
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1550
+ ...fetchProps
1551
+ });
1552
+ __privateSet$3(this, _schema$1, schema);
1553
+ return schema;
1554
+ };
1408
1555
  const transformObjectLinks = (object) => {
1409
1556
  return Object.entries(object).reduce((acc, [key, value]) => {
1410
1557
  if (key === "xata")
@@ -1412,15 +1559,34 @@ const transformObjectLinks = (object) => {
1412
1559
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1413
1560
  }, {});
1414
1561
  };
1415
- const initObject = (db, links, table, object) => {
1562
+ const initObject = (db, schema, table, object) => {
1416
1563
  const result = {};
1417
- Object.assign(result, object);
1418
- const tableLinks = links[table] || [];
1419
- for (const link of tableLinks) {
1420
- const [field, linkTable] = link;
1421
- const value = result[field];
1422
- if (value && isObject(value)) {
1423
- result[field] = initObject(db, links, linkTable, value);
1564
+ const { xata, ...rest } = object ?? {};
1565
+ Object.assign(result, rest);
1566
+ const { columns } = schema.tables.find(({ name }) => name === table) ?? {};
1567
+ if (!columns)
1568
+ console.error(`Table ${table} not found in schema`);
1569
+ for (const column of columns ?? []) {
1570
+ const value = result[column.name];
1571
+ switch (column.type) {
1572
+ case "datetime": {
1573
+ const date = value !== void 0 ? new Date(value) : void 0;
1574
+ if (date && isNaN(date.getTime())) {
1575
+ console.error(`Failed to parse date ${value} for field ${column.name}`);
1576
+ } else if (date) {
1577
+ result[column.name] = date;
1578
+ }
1579
+ break;
1580
+ }
1581
+ case "link": {
1582
+ const linkTable = column.link?.table;
1583
+ if (!linkTable) {
1584
+ console.error(`Failed to parse link for field ${column.name}`);
1585
+ } else if (isObject(value)) {
1586
+ result[column.name] = initObject(db, schema, linkTable, value);
1587
+ }
1588
+ break;
1589
+ }
1424
1590
  }
1425
1591
  }
1426
1592
  result.read = function() {
@@ -1432,7 +1598,10 @@ const initObject = (db, links, table, object) => {
1432
1598
  result.delete = function() {
1433
1599
  return db[table].delete(result["id"]);
1434
1600
  };
1435
- for (const prop of ["read", "update", "delete"]) {
1601
+ result.getMetadata = function() {
1602
+ return xata;
1603
+ };
1604
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1436
1605
  Object.defineProperty(result, prop, { enumerable: false });
1437
1606
  }
1438
1607
  Object.freeze(result);
@@ -1452,7 +1621,7 @@ var __accessCheck$3 = (obj, member, msg) => {
1452
1621
  if (!member.has(obj))
1453
1622
  throw TypeError("Cannot " + msg);
1454
1623
  };
1455
- var __privateGet$2 = (obj, member, getter) => {
1624
+ var __privateGet$3 = (obj, member, getter) => {
1456
1625
  __accessCheck$3(obj, member, "read from private field");
1457
1626
  return getter ? getter.call(obj) : member.get(obj);
1458
1627
  };
@@ -1461,7 +1630,7 @@ var __privateAdd$3 = (obj, member, value) => {
1461
1630
  throw TypeError("Cannot add the same private member more than once");
1462
1631
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1463
1632
  };
1464
- var __privateSet$1 = (obj, member, value, setter) => {
1633
+ var __privateSet$2 = (obj, member, value, setter) => {
1465
1634
  __accessCheck$3(obj, member, "write to private field");
1466
1635
  setter ? setter.call(obj, value) : member.set(obj, value);
1467
1636
  return value;
@@ -1470,30 +1639,30 @@ var _map;
1470
1639
  class SimpleCache {
1471
1640
  constructor(options = {}) {
1472
1641
  __privateAdd$3(this, _map, void 0);
1473
- __privateSet$1(this, _map, /* @__PURE__ */ new Map());
1642
+ __privateSet$2(this, _map, /* @__PURE__ */ new Map());
1474
1643
  this.capacity = options.max ?? 500;
1475
1644
  this.cacheRecords = options.cacheRecords ?? true;
1476
1645
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1477
1646
  }
1478
1647
  async getAll() {
1479
- return Object.fromEntries(__privateGet$2(this, _map));
1648
+ return Object.fromEntries(__privateGet$3(this, _map));
1480
1649
  }
1481
1650
  async get(key) {
1482
- return __privateGet$2(this, _map).get(key) ?? null;
1651
+ return __privateGet$3(this, _map).get(key) ?? null;
1483
1652
  }
1484
1653
  async set(key, value) {
1485
1654
  await this.delete(key);
1486
- __privateGet$2(this, _map).set(key, value);
1487
- if (__privateGet$2(this, _map).size > this.capacity) {
1488
- const leastRecentlyUsed = __privateGet$2(this, _map).keys().next().value;
1655
+ __privateGet$3(this, _map).set(key, value);
1656
+ if (__privateGet$3(this, _map).size > this.capacity) {
1657
+ const leastRecentlyUsed = __privateGet$3(this, _map).keys().next().value;
1489
1658
  await this.delete(leastRecentlyUsed);
1490
1659
  }
1491
1660
  }
1492
1661
  async delete(key) {
1493
- __privateGet$2(this, _map).delete(key);
1662
+ __privateGet$3(this, _map).delete(key);
1494
1663
  }
1495
1664
  async clear() {
1496
- return __privateGet$2(this, _map).clear();
1665
+ return __privateGet$3(this, _map).clear();
1497
1666
  }
1498
1667
  }
1499
1668
  _map = new WeakMap();
@@ -1521,7 +1690,7 @@ var __accessCheck$2 = (obj, member, msg) => {
1521
1690
  if (!member.has(obj))
1522
1691
  throw TypeError("Cannot " + msg);
1523
1692
  };
1524
- var __privateGet$1 = (obj, member, getter) => {
1693
+ var __privateGet$2 = (obj, member, getter) => {
1525
1694
  __accessCheck$2(obj, member, "read from private field");
1526
1695
  return getter ? getter.call(obj) : member.get(obj);
1527
1696
  };
@@ -1532,26 +1701,24 @@ var __privateAdd$2 = (obj, member, value) => {
1532
1701
  };
1533
1702
  var _tables;
1534
1703
  class SchemaPlugin extends XataPlugin {
1535
- constructor(links, tableNames) {
1704
+ constructor(tableNames) {
1536
1705
  super();
1537
- this.links = links;
1538
1706
  this.tableNames = tableNames;
1539
1707
  __privateAdd$2(this, _tables, {});
1540
1708
  }
1541
1709
  build(pluginOptions) {
1542
- const links = this.links;
1543
1710
  const db = new Proxy({}, {
1544
1711
  get: (_target, table) => {
1545
1712
  if (!isString(table))
1546
1713
  throw new Error("Invalid table name");
1547
- if (!__privateGet$1(this, _tables)[table]) {
1548
- __privateGet$1(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, links });
1714
+ if (__privateGet$2(this, _tables)[table] === void 0) {
1715
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table });
1549
1716
  }
1550
- return __privateGet$1(this, _tables)[table];
1717
+ return __privateGet$2(this, _tables)[table];
1551
1718
  }
1552
1719
  });
1553
1720
  for (const table of this.tableNames ?? []) {
1554
- db[table] = new RestRepository({ db, pluginOptions, table, links });
1721
+ db[table] = new RestRepository({ db, pluginOptions, table });
1555
1722
  }
1556
1723
  return db;
1557
1724
  }
@@ -1562,55 +1729,80 @@ var __accessCheck$1 = (obj, member, msg) => {
1562
1729
  if (!member.has(obj))
1563
1730
  throw TypeError("Cannot " + msg);
1564
1731
  };
1732
+ var __privateGet$1 = (obj, member, getter) => {
1733
+ __accessCheck$1(obj, member, "read from private field");
1734
+ return getter ? getter.call(obj) : member.get(obj);
1735
+ };
1565
1736
  var __privateAdd$1 = (obj, member, value) => {
1566
1737
  if (member.has(obj))
1567
1738
  throw TypeError("Cannot add the same private member more than once");
1568
1739
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1569
1740
  };
1741
+ var __privateSet$1 = (obj, member, value, setter) => {
1742
+ __accessCheck$1(obj, member, "write to private field");
1743
+ setter ? setter.call(obj, value) : member.set(obj, value);
1744
+ return value;
1745
+ };
1570
1746
  var __privateMethod$1 = (obj, member, method) => {
1571
1747
  __accessCheck$1(obj, member, "access private method");
1572
1748
  return method;
1573
1749
  };
1574
- var _search, search_fn;
1750
+ var _schema, _search, search_fn, _getSchema, getSchema_fn;
1575
1751
  class SearchPlugin extends XataPlugin {
1576
- constructor(db, links) {
1752
+ constructor(db) {
1577
1753
  super();
1578
1754
  this.db = db;
1579
- this.links = links;
1580
1755
  __privateAdd$1(this, _search);
1756
+ __privateAdd$1(this, _getSchema);
1757
+ __privateAdd$1(this, _schema, void 0);
1581
1758
  }
1582
1759
  build({ getFetchProps }) {
1583
1760
  return {
1584
1761
  all: async (query, options = {}) => {
1585
1762
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1763
+ const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
1586
1764
  return records.map((record) => {
1587
1765
  const { table = "orphan" } = record.xata;
1588
- return { table, record: initObject(this.db, this.links, table, record) };
1766
+ return { table, record: initObject(this.db, schema, table, record) };
1589
1767
  });
1590
1768
  },
1591
1769
  byTable: async (query, options = {}) => {
1592
1770
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1771
+ const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
1593
1772
  return records.reduce((acc, record) => {
1594
1773
  const { table = "orphan" } = record.xata;
1595
1774
  const items = acc[table] ?? [];
1596
- const item = initObject(this.db, this.links, table, record);
1775
+ const item = initObject(this.db, schema, table, record);
1597
1776
  return { ...acc, [table]: [...items, item] };
1598
1777
  }, {});
1599
1778
  }
1600
1779
  };
1601
1780
  }
1602
1781
  }
1782
+ _schema = new WeakMap();
1603
1783
  _search = new WeakSet();
1604
1784
  search_fn = async function(query, options, getFetchProps) {
1605
1785
  const fetchProps = await getFetchProps();
1606
- const { tables, fuzziness } = options ?? {};
1786
+ const { tables, fuzziness, highlight } = options ?? {};
1607
1787
  const { records } = await searchBranch({
1608
1788
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1609
- body: { tables, query, fuzziness },
1789
+ body: { tables, query, fuzziness, highlight },
1610
1790
  ...fetchProps
1611
1791
  });
1612
1792
  return records;
1613
1793
  };
1794
+ _getSchema = new WeakSet();
1795
+ getSchema_fn = async function(getFetchProps) {
1796
+ if (__privateGet$1(this, _schema))
1797
+ return __privateGet$1(this, _schema);
1798
+ const fetchProps = await getFetchProps();
1799
+ const { schema } = await getBranchDetails({
1800
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1801
+ ...fetchProps
1802
+ });
1803
+ __privateSet$1(this, _schema, schema);
1804
+ return schema;
1805
+ };
1614
1806
 
1615
1807
  const isBranchStrategyBuilder = (strategy) => {
1616
1808
  return typeof strategy === "function";
@@ -1622,30 +1814,39 @@ const envBranchNames = [
1622
1814
  "CF_PAGES_BRANCH",
1623
1815
  "BRANCH"
1624
1816
  ];
1625
- const defaultBranch = "main";
1626
1817
  async function getCurrentBranchName(options) {
1627
- const env = await getBranchByEnvVariable();
1628
- if (env)
1629
- return env;
1630
- const branch = await getGitBranch();
1631
- if (!branch)
1632
- return defaultBranch;
1633
- const details = await getDatabaseBranch(branch, options);
1634
- if (details)
1635
- return branch;
1636
- return defaultBranch;
1818
+ const env = getBranchByEnvVariable();
1819
+ if (env) {
1820
+ const details = await getDatabaseBranch(env, options);
1821
+ if (details)
1822
+ return env;
1823
+ console.warn(`Branch ${env} not found in Xata. Ignoring...`);
1824
+ }
1825
+ const gitBranch = await getGitBranch();
1826
+ return resolveXataBranch(gitBranch, options);
1637
1827
  }
1638
1828
  async function getCurrentBranchDetails(options) {
1639
- const env = await getBranchByEnvVariable();
1640
- if (env)
1641
- return getDatabaseBranch(env, options);
1642
- const branch = await getGitBranch();
1643
- if (!branch)
1644
- return getDatabaseBranch(defaultBranch, options);
1645
- const details = await getDatabaseBranch(branch, options);
1646
- if (details)
1647
- return details;
1648
- return getDatabaseBranch(defaultBranch, options);
1829
+ const branch = await getCurrentBranchName(options);
1830
+ return getDatabaseBranch(branch, options);
1831
+ }
1832
+ async function resolveXataBranch(gitBranch, options) {
1833
+ const databaseURL = options?.databaseURL || getDatabaseURL();
1834
+ const apiKey = options?.apiKey || getAPIKey();
1835
+ if (!databaseURL)
1836
+ throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
1837
+ if (!apiKey)
1838
+ throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
1839
+ const [protocol, , host, , dbName] = databaseURL.split("/");
1840
+ const [workspace] = host.split(".");
1841
+ const { branch } = await resolveBranch({
1842
+ apiKey,
1843
+ apiUrl: databaseURL,
1844
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
1845
+ workspacesApiUrl: `${protocol}//${host}`,
1846
+ pathParams: { dbName, workspace },
1847
+ queryParams: { gitBranch, fallbackBranch: getEnvVariable("XATA_FALLBACK_BRANCH") }
1848
+ });
1849
+ return branch;
1649
1850
  }
1650
1851
  async function getDatabaseBranch(branch, options) {
1651
1852
  const databaseURL = options?.databaseURL || getDatabaseURL();
@@ -1719,7 +1920,7 @@ var __privateMethod = (obj, member, method) => {
1719
1920
  const buildClient = (plugins) => {
1720
1921
  var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1721
1922
  return _a = class {
1722
- constructor(options = {}, links, tables) {
1923
+ constructor(options = {}, tables) {
1723
1924
  __privateAdd(this, _parseOptions);
1724
1925
  __privateAdd(this, _getFetchProps);
1725
1926
  __privateAdd(this, _evaluateBranch);
@@ -1729,12 +1930,12 @@ const buildClient = (plugins) => {
1729
1930
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1730
1931
  cache: safeOptions.cache
1731
1932
  };
1732
- const db = new SchemaPlugin(links, tables).build(pluginOptions);
1733
- const search = new SearchPlugin(db, links ?? {}).build(pluginOptions);
1933
+ const db = new SchemaPlugin(tables).build(pluginOptions);
1934
+ const search = new SearchPlugin(db).build(pluginOptions);
1734
1935
  this.db = db;
1735
1936
  this.search = search;
1736
1937
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
1737
- if (!namespace)
1938
+ if (namespace === void 0)
1738
1939
  continue;
1739
1940
  const result = namespace.build(pluginOptions);
1740
1941
  if (result instanceof Promise) {
@@ -1751,7 +1952,7 @@ const buildClient = (plugins) => {
1751
1952
  const databaseURL = options?.databaseURL || getDatabaseURL();
1752
1953
  const apiKey = options?.apiKey || getAPIKey();
1753
1954
  const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
1754
- const branch = async () => options?.branch ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1955
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1755
1956
  if (!databaseURL || !apiKey) {
1756
1957
  throw new Error("Options databaseURL and apiKey are required");
1757
1958
  }
@@ -1778,7 +1979,7 @@ const buildClient = (plugins) => {
1778
1979
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1779
1980
  if (__privateGet(this, _branch))
1780
1981
  return __privateGet(this, _branch);
1781
- if (!param)
1982
+ if (param === void 0)
1782
1983
  return void 0;
1783
1984
  const strategies = Array.isArray(param) ? [...param] : [param];
1784
1985
  const evaluateBranch = async (strategy) => {
@@ -1803,5 +2004,5 @@ class XataError extends Error {
1803
2004
  }
1804
2005
  }
1805
2006
 
1806
- export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, Repository, RestRepository, SchemaPlugin, SearchPlugin, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addTableColumn, buildClient, bulkInsertTableRecords, cancelWorkspaceMemberInvite, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, endsWith, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseURL, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isIdentifiable, isNot, isXataRecord, le, lt, lte, notExists, operationsByTag, pattern, queryTable, removeWorkspaceMember, resendWorkspaceMemberInvite, searchBranch, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberRole, upsertRecordWithID };
2007
+ export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, buildClient, bulkInsertTableRecords, cancelWorkspaceMemberInvite, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, endsWith, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseURL, getGitBranchesMapping, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isIdentifiable, isNot, isXataRecord, le, lt, lte, notExists, operationsByTag, pattern, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberRole, upsertRecordWithID };
1807
2008
  //# sourceMappingURL=index.mjs.map