@xata.io/client 0.0.0-alpha.vebf0406 → 0.0.0-alpha.vec92b09

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,19 @@ function compact(arr) {
7
7
  function isObject(value) {
8
8
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
9
9
  }
10
+ function isDefined(value) {
11
+ return value !== null && value !== void 0;
12
+ }
10
13
  function isString(value) {
11
- return value !== void 0 && value !== null && typeof value === "string";
14
+ return isDefined(value) && typeof value === "string";
15
+ }
16
+ function toBase64(value) {
17
+ try {
18
+ return btoa(value);
19
+ } catch (err) {
20
+ const buf = Buffer;
21
+ return buf.from(value).toString("base64");
22
+ }
12
23
  }
13
24
 
14
25
  function getEnvVariable(name) {
@@ -27,7 +38,10 @@ function getEnvVariable(name) {
27
38
  }
28
39
  async function getGitBranch() {
29
40
  try {
30
- return require("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
41
+ if (typeof require === "function") {
42
+ const req = require;
43
+ return req("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
44
+ }
31
45
  } catch (err) {
32
46
  }
33
47
  try {
@@ -60,16 +74,28 @@ function getFetchImplementation(userFetch) {
60
74
  return fetchImpl;
61
75
  }
62
76
 
63
- class FetcherError extends Error {
64
- constructor(status, data) {
77
+ const VERSION = "0.0.0-alpha.vec92b09";
78
+
79
+ class ErrorWithCause extends Error {
80
+ constructor(message, options) {
81
+ super(message, options);
82
+ }
83
+ }
84
+ class FetcherError extends ErrorWithCause {
85
+ constructor(status, data, requestId) {
65
86
  super(getMessage(data));
66
87
  this.status = status;
67
88
  this.errors = isBulkError(data) ? data.errors : void 0;
89
+ this.requestId = requestId;
68
90
  if (data instanceof Error) {
69
91
  this.stack = data.stack;
70
92
  this.cause = data.cause;
71
93
  }
72
94
  }
95
+ toString() {
96
+ const error = super.toString();
97
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
98
+ }
73
99
  }
74
100
  function isBulkError(error) {
75
101
  return isObject(error) && Array.isArray(error.errors);
@@ -92,7 +118,12 @@ function getMessage(data) {
92
118
  }
93
119
 
94
120
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
95
- const query = new URLSearchParams(queryParams).toString();
121
+ const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
122
+ if (value === void 0 || value === null)
123
+ return acc;
124
+ return { ...acc, [key]: value };
125
+ }, {});
126
+ const query = new URLSearchParams(cleanQueryParams).toString();
96
127
  const queryString = query.length > 0 ? `?${query}` : "";
97
128
  return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
98
129
  };
@@ -132,6 +163,7 @@ async function fetch$1({
132
163
  body: body ? JSON.stringify(body) : void 0,
133
164
  headers: {
134
165
  "Content-Type": "application/json",
166
+ "User-Agent": `Xata client-ts/${VERSION}`,
135
167
  ...headers,
136
168
  ...hostHeader(fullUrl),
137
169
  Authorization: `Bearer ${apiKey}`
@@ -140,14 +172,15 @@ async function fetch$1({
140
172
  if (response.status === 204) {
141
173
  return {};
142
174
  }
175
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
143
176
  try {
144
177
  const jsonResponse = await response.json();
145
178
  if (response.ok) {
146
179
  return jsonResponse;
147
180
  }
148
- throw new FetcherError(response.status, jsonResponse);
181
+ throw new FetcherError(response.status, jsonResponse, requestId);
149
182
  } catch (error) {
150
- throw new FetcherError(response.status, error);
183
+ throw new FetcherError(response.status, error, requestId);
151
184
  }
152
185
  }
153
186
 
@@ -241,6 +274,14 @@ const deleteDatabase = (variables) => fetch$1({
241
274
  method: "delete",
242
275
  ...variables
243
276
  });
277
+ const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
278
+ const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
279
+ const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
280
+ const resolveBranch = (variables) => fetch$1({
281
+ url: "/dbs/{dbName}/resolveBranch",
282
+ method: "get",
283
+ ...variables
284
+ });
244
285
  const getBranchDetails = (variables) => fetch$1({
245
286
  url: "/db/{dbBranchName}",
246
287
  method: "get",
@@ -348,6 +389,11 @@ const queryTable = (variables) => fetch$1({
348
389
  method: "post",
349
390
  ...variables
350
391
  });
392
+ const searchTable = (variables) => fetch$1({
393
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
394
+ method: "post",
395
+ ...variables
396
+ });
351
397
  const searchBranch = (variables) => fetch$1({
352
398
  url: "/db/{dbBranchName}/search",
353
399
  method: "post",
@@ -369,7 +415,15 @@ const operationsByTag = {
369
415
  resendWorkspaceMemberInvite,
370
416
  acceptWorkspaceMemberInvite
371
417
  },
372
- database: { getDatabaseList, createDatabase, deleteDatabase },
418
+ database: {
419
+ getDatabaseList,
420
+ createDatabase,
421
+ deleteDatabase,
422
+ getGitBranchesMapping,
423
+ addGitBranchesEntry,
424
+ removeGitBranchesEntry,
425
+ resolveBranch
426
+ },
373
427
  branch: {
374
428
  getBranchList,
375
429
  getBranchDetails,
@@ -403,6 +457,7 @@ const operationsByTag = {
403
457
  getRecord,
404
458
  bulkInsertTableRecords,
405
459
  queryTable,
460
+ searchTable,
406
461
  searchBranch
407
462
  }
408
463
  };
@@ -432,35 +487,35 @@ function isValidBuilder(builder) {
432
487
  return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
433
488
  }
434
489
 
435
- var __accessCheck$6 = (obj, member, msg) => {
490
+ var __accessCheck$7 = (obj, member, msg) => {
436
491
  if (!member.has(obj))
437
492
  throw TypeError("Cannot " + msg);
438
493
  };
439
- var __privateGet$5 = (obj, member, getter) => {
440
- __accessCheck$6(obj, member, "read from private field");
494
+ var __privateGet$7 = (obj, member, getter) => {
495
+ __accessCheck$7(obj, member, "read from private field");
441
496
  return getter ? getter.call(obj) : member.get(obj);
442
497
  };
443
- var __privateAdd$6 = (obj, member, value) => {
498
+ var __privateAdd$7 = (obj, member, value) => {
444
499
  if (member.has(obj))
445
500
  throw TypeError("Cannot add the same private member more than once");
446
501
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
447
502
  };
448
- var __privateSet$4 = (obj, member, value, setter) => {
449
- __accessCheck$6(obj, member, "write to private field");
503
+ var __privateSet$6 = (obj, member, value, setter) => {
504
+ __accessCheck$7(obj, member, "write to private field");
450
505
  setter ? setter.call(obj, value) : member.set(obj, value);
451
506
  return value;
452
507
  };
453
508
  var _extraProps, _namespaces;
454
509
  class XataApiClient {
455
510
  constructor(options = {}) {
456
- __privateAdd$6(this, _extraProps, void 0);
457
- __privateAdd$6(this, _namespaces, {});
511
+ __privateAdd$7(this, _extraProps, void 0);
512
+ __privateAdd$7(this, _namespaces, {});
458
513
  const provider = options.host ?? "production";
459
514
  const apiKey = options?.apiKey ?? getAPIKey();
460
515
  if (!apiKey) {
461
516
  throw new Error("Could not resolve a valid apiKey");
462
517
  }
463
- __privateSet$4(this, _extraProps, {
518
+ __privateSet$6(this, _extraProps, {
464
519
  apiUrl: getHostUrl(provider, "main"),
465
520
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
466
521
  fetchImpl: getFetchImplementation(options.fetch),
@@ -468,34 +523,34 @@ class XataApiClient {
468
523
  });
469
524
  }
470
525
  get user() {
471
- if (!__privateGet$5(this, _namespaces).user)
472
- __privateGet$5(this, _namespaces).user = new UserApi(__privateGet$5(this, _extraProps));
473
- return __privateGet$5(this, _namespaces).user;
526
+ if (!__privateGet$7(this, _namespaces).user)
527
+ __privateGet$7(this, _namespaces).user = new UserApi(__privateGet$7(this, _extraProps));
528
+ return __privateGet$7(this, _namespaces).user;
474
529
  }
475
530
  get workspaces() {
476
- if (!__privateGet$5(this, _namespaces).workspaces)
477
- __privateGet$5(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$5(this, _extraProps));
478
- return __privateGet$5(this, _namespaces).workspaces;
531
+ if (!__privateGet$7(this, _namespaces).workspaces)
532
+ __privateGet$7(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$7(this, _extraProps));
533
+ return __privateGet$7(this, _namespaces).workspaces;
479
534
  }
480
535
  get databases() {
481
- if (!__privateGet$5(this, _namespaces).databases)
482
- __privateGet$5(this, _namespaces).databases = new DatabaseApi(__privateGet$5(this, _extraProps));
483
- return __privateGet$5(this, _namespaces).databases;
536
+ if (!__privateGet$7(this, _namespaces).databases)
537
+ __privateGet$7(this, _namespaces).databases = new DatabaseApi(__privateGet$7(this, _extraProps));
538
+ return __privateGet$7(this, _namespaces).databases;
484
539
  }
485
540
  get branches() {
486
- if (!__privateGet$5(this, _namespaces).branches)
487
- __privateGet$5(this, _namespaces).branches = new BranchApi(__privateGet$5(this, _extraProps));
488
- return __privateGet$5(this, _namespaces).branches;
541
+ if (!__privateGet$7(this, _namespaces).branches)
542
+ __privateGet$7(this, _namespaces).branches = new BranchApi(__privateGet$7(this, _extraProps));
543
+ return __privateGet$7(this, _namespaces).branches;
489
544
  }
490
545
  get tables() {
491
- if (!__privateGet$5(this, _namespaces).tables)
492
- __privateGet$5(this, _namespaces).tables = new TableApi(__privateGet$5(this, _extraProps));
493
- return __privateGet$5(this, _namespaces).tables;
546
+ if (!__privateGet$7(this, _namespaces).tables)
547
+ __privateGet$7(this, _namespaces).tables = new TableApi(__privateGet$7(this, _extraProps));
548
+ return __privateGet$7(this, _namespaces).tables;
494
549
  }
495
550
  get records() {
496
- if (!__privateGet$5(this, _namespaces).records)
497
- __privateGet$5(this, _namespaces).records = new RecordsApi(__privateGet$5(this, _extraProps));
498
- return __privateGet$5(this, _namespaces).records;
551
+ if (!__privateGet$7(this, _namespaces).records)
552
+ __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
553
+ return __privateGet$7(this, _namespaces).records;
499
554
  }
500
555
  }
501
556
  _extraProps = new WeakMap();
@@ -629,6 +684,33 @@ class DatabaseApi {
629
684
  ...this.extraProps
630
685
  });
631
686
  }
687
+ getGitBranchesMapping(workspace, dbName) {
688
+ return operationsByTag.database.getGitBranchesMapping({
689
+ pathParams: { workspace, dbName },
690
+ ...this.extraProps
691
+ });
692
+ }
693
+ addGitBranchesEntry(workspace, dbName, body) {
694
+ return operationsByTag.database.addGitBranchesEntry({
695
+ pathParams: { workspace, dbName },
696
+ body,
697
+ ...this.extraProps
698
+ });
699
+ }
700
+ removeGitBranchesEntry(workspace, dbName, gitBranch) {
701
+ return operationsByTag.database.removeGitBranchesEntry({
702
+ pathParams: { workspace, dbName },
703
+ queryParams: { gitBranch },
704
+ ...this.extraProps
705
+ });
706
+ }
707
+ resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
708
+ return operationsByTag.database.resolveBranch({
709
+ pathParams: { workspace, dbName },
710
+ queryParams: { gitBranch, fallbackBranch },
711
+ ...this.extraProps
712
+ });
713
+ }
632
714
  }
633
715
  class BranchApi {
634
716
  constructor(extraProps) {
@@ -646,10 +728,10 @@ class BranchApi {
646
728
  ...this.extraProps
647
729
  });
648
730
  }
649
- createBranch(workspace, database, branch, from = "", options = {}) {
731
+ createBranch(workspace, database, branch, from, options = {}) {
650
732
  return operationsByTag.branch.createBranch({
651
733
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
652
- queryParams: { from },
734
+ queryParams: isString(from) ? { from } : void 0,
653
735
  body: options,
654
736
  ...this.extraProps
655
737
  });
@@ -831,6 +913,13 @@ class RecordsApi {
831
913
  ...this.extraProps
832
914
  });
833
915
  }
916
+ searchTable(workspace, database, branch, tableName, query) {
917
+ return operationsByTag.records.searchTable({
918
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
919
+ body: query,
920
+ ...this.extraProps
921
+ });
922
+ }
834
923
  searchBranch(workspace, database, branch, query) {
835
924
  return operationsByTag.records.searchBranch({
836
925
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -850,43 +939,43 @@ class XataApiPlugin {
850
939
  class XataPlugin {
851
940
  }
852
941
 
853
- var __accessCheck$5 = (obj, member, msg) => {
942
+ var __accessCheck$6 = (obj, member, msg) => {
854
943
  if (!member.has(obj))
855
944
  throw TypeError("Cannot " + msg);
856
945
  };
857
- var __privateGet$4 = (obj, member, getter) => {
858
- __accessCheck$5(obj, member, "read from private field");
946
+ var __privateGet$6 = (obj, member, getter) => {
947
+ __accessCheck$6(obj, member, "read from private field");
859
948
  return getter ? getter.call(obj) : member.get(obj);
860
949
  };
861
- var __privateAdd$5 = (obj, member, value) => {
950
+ var __privateAdd$6 = (obj, member, value) => {
862
951
  if (member.has(obj))
863
952
  throw TypeError("Cannot add the same private member more than once");
864
953
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
865
954
  };
866
- var __privateSet$3 = (obj, member, value, setter) => {
867
- __accessCheck$5(obj, member, "write to private field");
955
+ var __privateSet$5 = (obj, member, value, setter) => {
956
+ __accessCheck$6(obj, member, "write to private field");
868
957
  setter ? setter.call(obj, value) : member.set(obj, value);
869
958
  return value;
870
959
  };
871
- var _query;
960
+ var _query, _page;
872
961
  class Page {
873
962
  constructor(query, meta, records = []) {
874
- __privateAdd$5(this, _query, void 0);
875
- __privateSet$3(this, _query, query);
963
+ __privateAdd$6(this, _query, void 0);
964
+ __privateSet$5(this, _query, query);
876
965
  this.meta = meta;
877
- this.records = records;
966
+ this.records = new RecordArray(this, records);
878
967
  }
879
968
  async nextPage(size, offset) {
880
- return __privateGet$4(this, _query).getPaginated({ page: { size, offset, after: this.meta.page.cursor } });
969
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
881
970
  }
882
971
  async previousPage(size, offset) {
883
- return __privateGet$4(this, _query).getPaginated({ page: { size, offset, before: this.meta.page.cursor } });
972
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
884
973
  }
885
974
  async firstPage(size, offset) {
886
- return __privateGet$4(this, _query).getPaginated({ page: { size, offset, first: this.meta.page.cursor } });
975
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
887
976
  }
888
977
  async lastPage(size, offset) {
889
- return __privateGet$4(this, _query).getPaginated({ page: { size, offset, last: this.meta.page.cursor } });
978
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
890
979
  }
891
980
  hasNextPage() {
892
981
  return this.meta.page.more;
@@ -894,50 +983,93 @@ class Page {
894
983
  }
895
984
  _query = new WeakMap();
896
985
  const PAGINATION_MAX_SIZE = 200;
897
- const PAGINATION_DEFAULT_SIZE = 200;
986
+ const PAGINATION_DEFAULT_SIZE = 20;
898
987
  const PAGINATION_MAX_OFFSET = 800;
899
988
  const PAGINATION_DEFAULT_OFFSET = 0;
989
+ function isCursorPaginationOptions(options) {
990
+ return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
991
+ }
992
+ const _RecordArray = class extends Array {
993
+ constructor(page, overrideRecords) {
994
+ super(..._RecordArray.parseConstructorParams(page, overrideRecords));
995
+ __privateAdd$6(this, _page, void 0);
996
+ __privateSet$5(this, _page, page);
997
+ }
998
+ static parseConstructorParams(...args) {
999
+ if (args.length === 1 && typeof args[0] === "number") {
1000
+ return new Array(args[0]);
1001
+ }
1002
+ if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
1003
+ const result = args[1] ?? args[0].records ?? [];
1004
+ return new Array(...result);
1005
+ }
1006
+ return new Array(...args);
1007
+ }
1008
+ async nextPage(size, offset) {
1009
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1010
+ return new _RecordArray(newPage);
1011
+ }
1012
+ async previousPage(size, offset) {
1013
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1014
+ return new _RecordArray(newPage);
1015
+ }
1016
+ async firstPage(size, offset) {
1017
+ const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1018
+ return new _RecordArray(newPage);
1019
+ }
1020
+ async lastPage(size, offset) {
1021
+ const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1022
+ return new _RecordArray(newPage);
1023
+ }
1024
+ hasNextPage() {
1025
+ return __privateGet$6(this, _page).meta.page.more;
1026
+ }
1027
+ };
1028
+ let RecordArray = _RecordArray;
1029
+ _page = new WeakMap();
900
1030
 
901
- var __accessCheck$4 = (obj, member, msg) => {
1031
+ var __accessCheck$5 = (obj, member, msg) => {
902
1032
  if (!member.has(obj))
903
1033
  throw TypeError("Cannot " + msg);
904
1034
  };
905
- var __privateGet$3 = (obj, member, getter) => {
906
- __accessCheck$4(obj, member, "read from private field");
1035
+ var __privateGet$5 = (obj, member, getter) => {
1036
+ __accessCheck$5(obj, member, "read from private field");
907
1037
  return getter ? getter.call(obj) : member.get(obj);
908
1038
  };
909
- var __privateAdd$4 = (obj, member, value) => {
1039
+ var __privateAdd$5 = (obj, member, value) => {
910
1040
  if (member.has(obj))
911
1041
  throw TypeError("Cannot add the same private member more than once");
912
1042
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
913
1043
  };
914
- var __privateSet$2 = (obj, member, value, setter) => {
915
- __accessCheck$4(obj, member, "write to private field");
1044
+ var __privateSet$4 = (obj, member, value, setter) => {
1045
+ __accessCheck$5(obj, member, "write to private field");
916
1046
  setter ? setter.call(obj, value) : member.set(obj, value);
917
1047
  return value;
918
1048
  };
919
1049
  var _table$1, _repository, _data;
920
1050
  const _Query = class {
921
- constructor(repository, table, data, parent) {
922
- __privateAdd$4(this, _table$1, void 0);
923
- __privateAdd$4(this, _repository, void 0);
924
- __privateAdd$4(this, _data, { filter: {} });
1051
+ constructor(repository, table, data, rawParent) {
1052
+ __privateAdd$5(this, _table$1, void 0);
1053
+ __privateAdd$5(this, _repository, void 0);
1054
+ __privateAdd$5(this, _data, { filter: {} });
925
1055
  this.meta = { page: { cursor: "start", more: true } };
926
- this.records = [];
927
- __privateSet$2(this, _table$1, table);
1056
+ this.records = new RecordArray(this, []);
1057
+ __privateSet$4(this, _table$1, table);
928
1058
  if (repository) {
929
- __privateSet$2(this, _repository, repository);
1059
+ __privateSet$4(this, _repository, repository);
930
1060
  } else {
931
- __privateSet$2(this, _repository, this);
1061
+ __privateSet$4(this, _repository, this);
932
1062
  }
933
- __privateGet$3(this, _data).filter = data.filter ?? parent?.filter ?? {};
934
- __privateGet$3(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
935
- __privateGet$3(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
936
- __privateGet$3(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
937
- __privateGet$3(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
938
- __privateGet$3(this, _data).sort = data.sort ?? parent?.sort;
939
- __privateGet$3(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
940
- __privateGet$3(this, _data).page = data.page ?? parent?.page;
1063
+ const parent = cleanParent(data, rawParent);
1064
+ __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
1065
+ __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
1066
+ __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
1067
+ __privateGet$5(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
1068
+ __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1069
+ __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1070
+ __privateGet$5(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
1071
+ __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1072
+ __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
941
1073
  this.any = this.any.bind(this);
942
1074
  this.all = this.all.bind(this);
943
1075
  this.not = this.not.bind(this);
@@ -948,75 +1080,88 @@ const _Query = class {
948
1080
  Object.defineProperty(this, "repository", { enumerable: false });
949
1081
  }
950
1082
  getQueryOptions() {
951
- return __privateGet$3(this, _data);
1083
+ return __privateGet$5(this, _data);
1084
+ }
1085
+ key() {
1086
+ const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$5(this, _data);
1087
+ const key = JSON.stringify({ columns, filter, sort, pagination });
1088
+ return toBase64(key);
952
1089
  }
953
1090
  any(...queries) {
954
1091
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
955
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $any } }, __privateGet$3(this, _data));
1092
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
956
1093
  }
957
1094
  all(...queries) {
958
1095
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
959
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $all } }, __privateGet$3(this, _data));
1096
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
960
1097
  }
961
1098
  not(...queries) {
962
1099
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
963
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $not } }, __privateGet$3(this, _data));
1100
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
964
1101
  }
965
1102
  none(...queries) {
966
1103
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
967
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $none } }, __privateGet$3(this, _data));
1104
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
968
1105
  }
969
1106
  filter(a, b) {
970
1107
  if (arguments.length === 1) {
971
1108
  const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
972
- const $all = compact([__privateGet$3(this, _data).filter?.$all].flat().concat(constraints));
973
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $all } }, __privateGet$3(this, _data));
1109
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1110
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
974
1111
  } else {
975
- const $all = compact([__privateGet$3(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
976
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $all } }, __privateGet$3(this, _data));
1112
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
1113
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
977
1114
  }
978
1115
  }
979
1116
  sort(column, direction) {
980
- const originalSort = [__privateGet$3(this, _data).sort ?? []].flat();
1117
+ const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
981
1118
  const sort = [...originalSort, { column, direction }];
982
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { sort }, __privateGet$3(this, _data));
1119
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
983
1120
  }
984
1121
  select(columns) {
985
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { columns }, __privateGet$3(this, _data));
1122
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { columns }, __privateGet$5(this, _data));
986
1123
  }
987
1124
  getPaginated(options = {}) {
988
- const query = new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), options, __privateGet$3(this, _data));
989
- return __privateGet$3(this, _repository).query(query);
1125
+ const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
1126
+ return __privateGet$5(this, _repository).query(query);
990
1127
  }
991
1128
  async *[Symbol.asyncIterator]() {
992
- for await (const [record] of this.getIterator(1)) {
1129
+ for await (const [record] of this.getIterator({ batchSize: 1 })) {
993
1130
  yield record;
994
1131
  }
995
1132
  }
996
- async *getIterator(chunk, options = {}) {
997
- let offset = 0;
998
- let end = false;
999
- while (!end) {
1000
- const { records, meta } = await this.getPaginated({ ...options, page: { size: chunk, offset } });
1001
- yield records;
1002
- offset += chunk;
1003
- end = !meta.page.more;
1133
+ async *getIterator(options = {}) {
1134
+ const { batchSize = 1 } = options;
1135
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
1136
+ let more = page.hasNextPage();
1137
+ yield page.records;
1138
+ while (more) {
1139
+ page = await page.nextPage();
1140
+ more = page.hasNextPage();
1141
+ yield page.records;
1004
1142
  }
1005
1143
  }
1006
1144
  async getMany(options = {}) {
1007
- const { records } = await this.getPaginated(options);
1008
- return records;
1145
+ const page = await this.getPaginated(options);
1146
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1147
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1148
+ }
1149
+ return page.records;
1009
1150
  }
1010
- async getAll(chunk = PAGINATION_MAX_SIZE, options = {}) {
1151
+ async getAll(options = {}) {
1152
+ const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
1011
1153
  const results = [];
1012
- for await (const page of this.getIterator(chunk, options)) {
1154
+ for await (const page of this.getIterator({ ...rest, batchSize })) {
1013
1155
  results.push(...page);
1014
1156
  }
1015
1157
  return results;
1016
1158
  }
1017
- async getOne(options = {}) {
1018
- const records = await this.getMany({ ...options, page: { size: 1 } });
1019
- return records[0] || null;
1159
+ async getFirst(options = {}) {
1160
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1161
+ return records[0] ?? null;
1162
+ }
1163
+ cache(ttl) {
1164
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1020
1165
  }
1021
1166
  nextPage(size, offset) {
1022
1167
  return this.firstPage(size, offset);
@@ -1025,10 +1170,10 @@ const _Query = class {
1025
1170
  return this.firstPage(size, offset);
1026
1171
  }
1027
1172
  firstPage(size, offset) {
1028
- return this.getPaginated({ page: { size, offset } });
1173
+ return this.getPaginated({ pagination: { size, offset } });
1029
1174
  }
1030
1175
  lastPage(size, offset) {
1031
- return this.getPaginated({ page: { size, offset, before: "end" } });
1176
+ return this.getPaginated({ pagination: { size, offset, before: "end" } });
1032
1177
  }
1033
1178
  hasNextPage() {
1034
1179
  return this.meta.page.more;
@@ -1038,12 +1183,20 @@ let Query = _Query;
1038
1183
  _table$1 = new WeakMap();
1039
1184
  _repository = new WeakMap();
1040
1185
  _data = new WeakMap();
1186
+ function cleanParent(data, parent) {
1187
+ if (isCursorPaginationOptions(data.pagination)) {
1188
+ return { ...parent, sorting: void 0, filter: void 0 };
1189
+ }
1190
+ return parent;
1191
+ }
1041
1192
 
1042
1193
  function isIdentifiable(x) {
1043
1194
  return isObject(x) && isString(x?.id);
1044
1195
  }
1045
1196
  function isXataRecord(x) {
1046
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1197
+ const record = x;
1198
+ const metadata = record?.getMetadata();
1199
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1047
1200
  }
1048
1201
 
1049
1202
  function isSortFilterString(value) {
@@ -1069,169 +1222,253 @@ function buildSortFilter(filter) {
1069
1222
  }
1070
1223
  }
1071
1224
 
1072
- var __accessCheck$3 = (obj, member, msg) => {
1225
+ var __accessCheck$4 = (obj, member, msg) => {
1073
1226
  if (!member.has(obj))
1074
1227
  throw TypeError("Cannot " + msg);
1075
1228
  };
1076
- var __privateGet$2 = (obj, member, getter) => {
1077
- __accessCheck$3(obj, member, "read from private field");
1229
+ var __privateGet$4 = (obj, member, getter) => {
1230
+ __accessCheck$4(obj, member, "read from private field");
1078
1231
  return getter ? getter.call(obj) : member.get(obj);
1079
1232
  };
1080
- var __privateAdd$3 = (obj, member, value) => {
1233
+ var __privateAdd$4 = (obj, member, value) => {
1081
1234
  if (member.has(obj))
1082
1235
  throw TypeError("Cannot add the same private member more than once");
1083
1236
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1084
1237
  };
1085
- var __privateSet$1 = (obj, member, value, setter) => {
1086
- __accessCheck$3(obj, member, "write to private field");
1238
+ var __privateSet$3 = (obj, member, value, setter) => {
1239
+ __accessCheck$4(obj, member, "write to private field");
1087
1240
  setter ? setter.call(obj, value) : member.set(obj, value);
1088
1241
  return value;
1089
1242
  };
1090
1243
  var __privateMethod$2 = (obj, member, method) => {
1091
- __accessCheck$3(obj, member, "access private method");
1244
+ __accessCheck$4(obj, member, "access private method");
1092
1245
  return method;
1093
1246
  };
1094
- var _table, _links, _getFetchProps, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn;
1247
+ 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;
1095
1248
  class Repository extends Query {
1096
1249
  }
1097
1250
  class RestRepository extends Query {
1098
1251
  constructor(options) {
1099
1252
  super(null, options.table, {});
1100
- __privateAdd$3(this, _insertRecordWithoutId);
1101
- __privateAdd$3(this, _insertRecordWithId);
1102
- __privateAdd$3(this, _bulkInsertTableRecords);
1103
- __privateAdd$3(this, _updateRecordWithID);
1104
- __privateAdd$3(this, _upsertRecordWithID);
1105
- __privateAdd$3(this, _deleteRecord);
1106
- __privateAdd$3(this, _table, void 0);
1107
- __privateAdd$3(this, _links, void 0);
1108
- __privateAdd$3(this, _getFetchProps, void 0);
1109
- __privateSet$1(this, _table, options.table);
1110
- __privateSet$1(this, _links, options.links ?? {});
1111
- __privateSet$1(this, _getFetchProps, options.getFetchProps);
1253
+ __privateAdd$4(this, _insertRecordWithoutId);
1254
+ __privateAdd$4(this, _insertRecordWithId);
1255
+ __privateAdd$4(this, _bulkInsertTableRecords);
1256
+ __privateAdd$4(this, _updateRecordWithID);
1257
+ __privateAdd$4(this, _upsertRecordWithID);
1258
+ __privateAdd$4(this, _deleteRecord);
1259
+ __privateAdd$4(this, _invalidateCache);
1260
+ __privateAdd$4(this, _setCacheRecord);
1261
+ __privateAdd$4(this, _getCacheRecord);
1262
+ __privateAdd$4(this, _setCacheQuery);
1263
+ __privateAdd$4(this, _getCacheQuery);
1264
+ __privateAdd$4(this, _getSchema$1);
1265
+ __privateAdd$4(this, _table, void 0);
1266
+ __privateAdd$4(this, _getFetchProps, void 0);
1267
+ __privateAdd$4(this, _cache, void 0);
1268
+ __privateAdd$4(this, _schema$1, void 0);
1269
+ __privateSet$3(this, _table, options.table);
1270
+ __privateSet$3(this, _getFetchProps, options.pluginOptions.getFetchProps);
1112
1271
  this.db = options.db;
1272
+ __privateSet$3(this, _cache, options.pluginOptions.cache);
1113
1273
  }
1114
1274
  async create(a, b) {
1115
1275
  if (Array.isArray(a)) {
1116
- return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1276
+ if (a.length === 0)
1277
+ return [];
1278
+ const [itemsWithoutIds, itemsWithIds, order] = a.reduce(([accWithoutIds, accWithIds, accOrder], item) => {
1279
+ const condition = isString(item.id);
1280
+ accOrder.push(condition);
1281
+ if (condition) {
1282
+ accWithIds.push(item);
1283
+ } else {
1284
+ accWithoutIds.push(item);
1285
+ }
1286
+ return [accWithoutIds, accWithIds, accOrder];
1287
+ }, [[], [], []]);
1288
+ const recordsWithoutId = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, itemsWithoutIds);
1289
+ await Promise.all(recordsWithoutId.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1290
+ if (itemsWithIds.length > 100) {
1291
+ console.warn("Bulk create operation with id is not optimized in the Xata API yet, this request might be slow");
1292
+ }
1293
+ const recordsWithId = await Promise.all(itemsWithIds.map((object) => this.create(object)));
1294
+ return order.map((condition) => {
1295
+ if (condition) {
1296
+ return recordsWithId.shift();
1297
+ } else {
1298
+ return recordsWithoutId.shift();
1299
+ }
1300
+ }).filter((record) => !!record);
1117
1301
  }
1118
1302
  if (isString(a) && isObject(b)) {
1119
1303
  if (a === "")
1120
1304
  throw new Error("The id can't be empty");
1121
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1305
+ const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1306
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1307
+ return record;
1122
1308
  }
1123
1309
  if (isObject(a) && isString(a.id)) {
1124
1310
  if (a.id === "")
1125
1311
  throw new Error("The id can't be empty");
1126
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1312
+ const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1313
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1314
+ return record;
1127
1315
  }
1128
1316
  if (isObject(a)) {
1129
- return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1317
+ const record = await __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1318
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1319
+ return record;
1130
1320
  }
1131
1321
  throw new Error("Invalid arguments for create method");
1132
1322
  }
1133
- async read(recordId) {
1134
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1135
- try {
1136
- const response = await getRecord({
1137
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table), recordId },
1138
- ...fetchProps
1139
- });
1140
- return initObject(this.db, __privateGet$2(this, _links), __privateGet$2(this, _table), response);
1141
- } catch (e) {
1142
- if (isObject(e) && e.status === 404) {
1143
- return null;
1323
+ async read(a) {
1324
+ if (Array.isArray(a)) {
1325
+ if (a.length === 0)
1326
+ return [];
1327
+ const ids = a.map((item) => isString(item) ? item : item.id).filter((id2) => isString(id2));
1328
+ return this.getAll({ filter: { id: { $any: ids } } });
1329
+ }
1330
+ const id = isString(a) ? a : a.id;
1331
+ if (isString(id)) {
1332
+ const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, id);
1333
+ if (cacheRecord)
1334
+ return cacheRecord;
1335
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1336
+ try {
1337
+ const response = await getRecord({
1338
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: id },
1339
+ ...fetchProps
1340
+ });
1341
+ const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1342
+ return initObject(this.db, schema, __privateGet$4(this, _table), response);
1343
+ } catch (e) {
1344
+ if (isObject(e) && e.status === 404) {
1345
+ return null;
1346
+ }
1347
+ throw e;
1144
1348
  }
1145
- throw e;
1146
1349
  }
1147
1350
  }
1148
1351
  async update(a, b) {
1149
1352
  if (Array.isArray(a)) {
1353
+ if (a.length === 0)
1354
+ return [];
1150
1355
  if (a.length > 100) {
1151
1356
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1152
1357
  }
1153
1358
  return Promise.all(a.map((object) => this.update(object)));
1154
1359
  }
1155
1360
  if (isString(a) && isObject(b)) {
1156
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1361
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1362
+ const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1363
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1364
+ return record;
1157
1365
  }
1158
1366
  if (isObject(a) && isString(a.id)) {
1159
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1367
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1368
+ const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1369
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1370
+ return record;
1160
1371
  }
1161
1372
  throw new Error("Invalid arguments for update method");
1162
1373
  }
1163
1374
  async createOrUpdate(a, b) {
1164
1375
  if (Array.isArray(a)) {
1376
+ if (a.length === 0)
1377
+ return [];
1165
1378
  if (a.length > 100) {
1166
1379
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1167
1380
  }
1168
1381
  return Promise.all(a.map((object) => this.createOrUpdate(object)));
1169
1382
  }
1170
1383
  if (isString(a) && isObject(b)) {
1171
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1384
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1385
+ const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1386
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1387
+ return record;
1172
1388
  }
1173
1389
  if (isObject(a) && isString(a.id)) {
1174
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1390
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1391
+ const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1392
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1393
+ return record;
1175
1394
  }
1176
1395
  throw new Error("Invalid arguments for createOrUpdate method");
1177
1396
  }
1178
- async delete(recordId) {
1179
- if (Array.isArray(recordId)) {
1180
- if (recordId.length > 100) {
1397
+ async delete(a) {
1398
+ if (Array.isArray(a)) {
1399
+ if (a.length === 0)
1400
+ return;
1401
+ if (a.length > 100) {
1181
1402
  console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1182
1403
  }
1183
- await Promise.all(recordId.map((id) => this.delete(id)));
1404
+ await Promise.all(a.map((id) => this.delete(id)));
1184
1405
  return;
1185
1406
  }
1186
- if (isString(recordId)) {
1187
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, recordId);
1407
+ if (isString(a)) {
1408
+ await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1409
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1188
1410
  return;
1189
1411
  }
1190
- if (isObject(recordId) && isString(recordId.id)) {
1191
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, recordId.id);
1412
+ if (isObject(a) && isString(a.id)) {
1413
+ await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1414
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1192
1415
  return;
1193
1416
  }
1194
1417
  throw new Error("Invalid arguments for delete method");
1195
1418
  }
1196
1419
  async search(query, options = {}) {
1197
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1198
- const { records } = await searchBranch({
1199
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1200
- body: { tables: [__privateGet$2(this, _table)], query, fuzziness: options.fuzziness },
1420
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1421
+ const { records } = await searchTable({
1422
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1423
+ body: {
1424
+ query,
1425
+ fuzziness: options.fuzziness,
1426
+ prefix: options.prefix,
1427
+ highlight: options.highlight,
1428
+ filter: options.filter,
1429
+ boosters: options.boosters
1430
+ },
1201
1431
  ...fetchProps
1202
1432
  });
1203
- return records.map((item) => initObject(this.db, __privateGet$2(this, _links), __privateGet$2(this, _table), item));
1433
+ const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1434
+ return records.map((item) => initObject(this.db, schema, __privateGet$4(this, _table), item));
1204
1435
  }
1205
1436
  async query(query) {
1437
+ const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1438
+ if (cacheQuery)
1439
+ return new Page(query, cacheQuery.meta, cacheQuery.records);
1206
1440
  const data = query.getQueryOptions();
1207
1441
  const body = {
1208
1442
  filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1209
- sort: data.sort ? buildSortFilter(data.sort) : void 0,
1210
- page: data.page,
1443
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1444
+ page: data.pagination,
1211
1445
  columns: data.columns
1212
1446
  };
1213
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1447
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1214
1448
  const { meta, records: objects } = await queryTable({
1215
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table) },
1449
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1216
1450
  body,
1217
1451
  ...fetchProps
1218
1452
  });
1219
- const records = objects.map((record) => initObject(this.db, __privateGet$2(this, _links), __privateGet$2(this, _table), record));
1453
+ const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1454
+ const records = objects.map((record) => initObject(this.db, schema, __privateGet$4(this, _table), record));
1455
+ await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1220
1456
  return new Page(query, meta, records);
1221
1457
  }
1222
1458
  }
1223
1459
  _table = new WeakMap();
1224
- _links = new WeakMap();
1225
1460
  _getFetchProps = new WeakMap();
1461
+ _cache = new WeakMap();
1462
+ _schema$1 = new WeakMap();
1226
1463
  _insertRecordWithoutId = new WeakSet();
1227
1464
  insertRecordWithoutId_fn = async function(object) {
1228
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1465
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1229
1466
  const record = transformObjectLinks(object);
1230
1467
  const response = await insertRecord({
1231
1468
  pathParams: {
1232
1469
  workspace: "{workspaceId}",
1233
1470
  dbBranchName: "{dbBranch}",
1234
- tableName: __privateGet$2(this, _table)
1471
+ tableName: __privateGet$4(this, _table)
1235
1472
  },
1236
1473
  body: record,
1237
1474
  ...fetchProps
@@ -1244,13 +1481,13 @@ insertRecordWithoutId_fn = async function(object) {
1244
1481
  };
1245
1482
  _insertRecordWithId = new WeakSet();
1246
1483
  insertRecordWithId_fn = async function(recordId, object) {
1247
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1484
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1248
1485
  const record = transformObjectLinks(object);
1249
1486
  const response = await insertRecordWithID({
1250
1487
  pathParams: {
1251
1488
  workspace: "{workspaceId}",
1252
1489
  dbBranchName: "{dbBranch}",
1253
- tableName: __privateGet$2(this, _table),
1490
+ tableName: __privateGet$4(this, _table),
1254
1491
  recordId
1255
1492
  },
1256
1493
  body: record,
@@ -1265,14 +1502,14 @@ insertRecordWithId_fn = async function(recordId, object) {
1265
1502
  };
1266
1503
  _bulkInsertTableRecords = new WeakSet();
1267
1504
  bulkInsertTableRecords_fn = async function(objects) {
1268
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1505
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1269
1506
  const records = objects.map((object) => transformObjectLinks(object));
1270
1507
  const response = await bulkInsertTableRecords({
1271
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table) },
1508
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1272
1509
  body: { records },
1273
1510
  ...fetchProps
1274
1511
  });
1275
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1512
+ const finalObjects = await this.read(response.recordIDs);
1276
1513
  if (finalObjects.length !== objects.length) {
1277
1514
  throw new Error("The server failed to save some records");
1278
1515
  }
@@ -1280,10 +1517,10 @@ bulkInsertTableRecords_fn = async function(objects) {
1280
1517
  };
1281
1518
  _updateRecordWithID = new WeakSet();
1282
1519
  updateRecordWithID_fn = async function(recordId, object) {
1283
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1520
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1284
1521
  const record = transformObjectLinks(object);
1285
1522
  const response = await updateRecordWithID({
1286
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table), recordId },
1523
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1287
1524
  body: record,
1288
1525
  ...fetchProps
1289
1526
  });
@@ -1294,9 +1531,9 @@ updateRecordWithID_fn = async function(recordId, object) {
1294
1531
  };
1295
1532
  _upsertRecordWithID = new WeakSet();
1296
1533
  upsertRecordWithID_fn = async function(recordId, object) {
1297
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1534
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1298
1535
  const response = await upsertRecordWithID({
1299
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table), recordId },
1536
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1300
1537
  body: object,
1301
1538
  ...fetchProps
1302
1539
  });
@@ -1307,11 +1544,62 @@ upsertRecordWithID_fn = async function(recordId, object) {
1307
1544
  };
1308
1545
  _deleteRecord = new WeakSet();
1309
1546
  deleteRecord_fn = async function(recordId) {
1310
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1547
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1311
1548
  await deleteRecord({
1312
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table), recordId },
1549
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1550
+ ...fetchProps
1551
+ });
1552
+ };
1553
+ _invalidateCache = new WeakSet();
1554
+ invalidateCache_fn = async function(recordId) {
1555
+ await __privateGet$4(this, _cache).delete(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1556
+ const cacheItems = await __privateGet$4(this, _cache).getAll();
1557
+ const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1558
+ for (const [key, value] of queries) {
1559
+ const ids = getIds(value);
1560
+ if (ids.includes(recordId))
1561
+ await __privateGet$4(this, _cache).delete(key);
1562
+ }
1563
+ };
1564
+ _setCacheRecord = new WeakSet();
1565
+ setCacheRecord_fn = async function(record) {
1566
+ if (!__privateGet$4(this, _cache).cacheRecords)
1567
+ return;
1568
+ await __privateGet$4(this, _cache).set(`rec_${__privateGet$4(this, _table)}:${record.id}`, record);
1569
+ };
1570
+ _getCacheRecord = new WeakSet();
1571
+ getCacheRecord_fn = async function(recordId) {
1572
+ if (!__privateGet$4(this, _cache).cacheRecords)
1573
+ return null;
1574
+ return __privateGet$4(this, _cache).get(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1575
+ };
1576
+ _setCacheQuery = new WeakSet();
1577
+ setCacheQuery_fn = async function(query, meta, records) {
1578
+ await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1579
+ };
1580
+ _getCacheQuery = new WeakSet();
1581
+ getCacheQuery_fn = async function(query) {
1582
+ const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
1583
+ const result = await __privateGet$4(this, _cache).get(key);
1584
+ if (!result)
1585
+ return null;
1586
+ const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1587
+ if (ttl < 0)
1588
+ return null;
1589
+ const hasExpired = result.date.getTime() + ttl < Date.now();
1590
+ return hasExpired ? null : result;
1591
+ };
1592
+ _getSchema$1 = new WeakSet();
1593
+ getSchema_fn$1 = async function() {
1594
+ if (__privateGet$4(this, _schema$1))
1595
+ return __privateGet$4(this, _schema$1);
1596
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1597
+ const { schema } = await getBranchDetails({
1598
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1313
1599
  ...fetchProps
1314
1600
  });
1601
+ __privateSet$3(this, _schema$1, schema);
1602
+ return schema;
1315
1603
  };
1316
1604
  const transformObjectLinks = (object) => {
1317
1605
  return Object.entries(object).reduce((acc, [key, value]) => {
@@ -1320,15 +1608,34 @@ const transformObjectLinks = (object) => {
1320
1608
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1321
1609
  }, {});
1322
1610
  };
1323
- const initObject = (db, links, table, object) => {
1611
+ const initObject = (db, schema, table, object) => {
1324
1612
  const result = {};
1325
- Object.assign(result, object);
1326
- const tableLinks = links[table] || [];
1327
- for (const link of tableLinks) {
1328
- const [field, linkTable] = link;
1329
- const value = result[field];
1330
- if (value && isObject(value)) {
1331
- result[field] = initObject(db, links, linkTable, value);
1613
+ const { xata, ...rest } = object ?? {};
1614
+ Object.assign(result, rest);
1615
+ const { columns } = schema.tables.find(({ name }) => name === table) ?? {};
1616
+ if (!columns)
1617
+ console.error(`Table ${table} not found in schema`);
1618
+ for (const column of columns ?? []) {
1619
+ const value = result[column.name];
1620
+ switch (column.type) {
1621
+ case "datetime": {
1622
+ const date = value !== void 0 ? new Date(value) : void 0;
1623
+ if (date && isNaN(date.getTime())) {
1624
+ console.error(`Failed to parse date ${value} for field ${column.name}`);
1625
+ } else if (date) {
1626
+ result[column.name] = date;
1627
+ }
1628
+ break;
1629
+ }
1630
+ case "link": {
1631
+ const linkTable = column.link?.table;
1632
+ if (!linkTable) {
1633
+ console.error(`Failed to parse link for field ${column.name}`);
1634
+ } else if (isObject(value)) {
1635
+ result[column.name] = initObject(db, schema, linkTable, value);
1636
+ }
1637
+ break;
1638
+ }
1332
1639
  }
1333
1640
  }
1334
1641
  result.read = function() {
@@ -1340,12 +1647,74 @@ const initObject = (db, links, table, object) => {
1340
1647
  result.delete = function() {
1341
1648
  return db[table].delete(result["id"]);
1342
1649
  };
1343
- for (const prop of ["read", "update", "delete"]) {
1650
+ result.getMetadata = function() {
1651
+ return xata;
1652
+ };
1653
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1344
1654
  Object.defineProperty(result, prop, { enumerable: false });
1345
1655
  }
1346
1656
  Object.freeze(result);
1347
1657
  return result;
1348
1658
  };
1659
+ function getIds(value) {
1660
+ if (Array.isArray(value)) {
1661
+ return value.map((item) => getIds(item)).flat();
1662
+ }
1663
+ if (!isObject(value))
1664
+ return [];
1665
+ const nestedIds = Object.values(value).map((item) => getIds(item)).flat();
1666
+ return isString(value.id) ? [value.id, ...nestedIds] : nestedIds;
1667
+ }
1668
+
1669
+ var __accessCheck$3 = (obj, member, msg) => {
1670
+ if (!member.has(obj))
1671
+ throw TypeError("Cannot " + msg);
1672
+ };
1673
+ var __privateGet$3 = (obj, member, getter) => {
1674
+ __accessCheck$3(obj, member, "read from private field");
1675
+ return getter ? getter.call(obj) : member.get(obj);
1676
+ };
1677
+ var __privateAdd$3 = (obj, member, value) => {
1678
+ if (member.has(obj))
1679
+ throw TypeError("Cannot add the same private member more than once");
1680
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1681
+ };
1682
+ var __privateSet$2 = (obj, member, value, setter) => {
1683
+ __accessCheck$3(obj, member, "write to private field");
1684
+ setter ? setter.call(obj, value) : member.set(obj, value);
1685
+ return value;
1686
+ };
1687
+ var _map;
1688
+ class SimpleCache {
1689
+ constructor(options = {}) {
1690
+ __privateAdd$3(this, _map, void 0);
1691
+ __privateSet$2(this, _map, /* @__PURE__ */ new Map());
1692
+ this.capacity = options.max ?? 500;
1693
+ this.cacheRecords = options.cacheRecords ?? true;
1694
+ this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1695
+ }
1696
+ async getAll() {
1697
+ return Object.fromEntries(__privateGet$3(this, _map));
1698
+ }
1699
+ async get(key) {
1700
+ return __privateGet$3(this, _map).get(key) ?? null;
1701
+ }
1702
+ async set(key, value) {
1703
+ await this.delete(key);
1704
+ __privateGet$3(this, _map).set(key, value);
1705
+ if (__privateGet$3(this, _map).size > this.capacity) {
1706
+ const leastRecentlyUsed = __privateGet$3(this, _map).keys().next().value;
1707
+ await this.delete(leastRecentlyUsed);
1708
+ }
1709
+ }
1710
+ async delete(key) {
1711
+ __privateGet$3(this, _map).delete(key);
1712
+ }
1713
+ async clear() {
1714
+ return __privateGet$3(this, _map).clear();
1715
+ }
1716
+ }
1717
+ _map = new WeakMap();
1349
1718
 
1350
1719
  const gt = (value) => ({ $gt: value });
1351
1720
  const ge = (value) => ({ $ge: value });
@@ -1370,7 +1739,7 @@ var __accessCheck$2 = (obj, member, msg) => {
1370
1739
  if (!member.has(obj))
1371
1740
  throw TypeError("Cannot " + msg);
1372
1741
  };
1373
- var __privateGet$1 = (obj, member, getter) => {
1742
+ var __privateGet$2 = (obj, member, getter) => {
1374
1743
  __accessCheck$2(obj, member, "read from private field");
1375
1744
  return getter ? getter.call(obj) : member.get(obj);
1376
1745
  };
@@ -1381,26 +1750,24 @@ var __privateAdd$2 = (obj, member, value) => {
1381
1750
  };
1382
1751
  var _tables;
1383
1752
  class SchemaPlugin extends XataPlugin {
1384
- constructor(links, tableNames) {
1753
+ constructor(tableNames) {
1385
1754
  super();
1386
- this.links = links;
1387
1755
  this.tableNames = tableNames;
1388
1756
  __privateAdd$2(this, _tables, {});
1389
1757
  }
1390
- build(options) {
1391
- const { getFetchProps } = options;
1392
- const links = this.links;
1758
+ build(pluginOptions) {
1393
1759
  const db = new Proxy({}, {
1394
1760
  get: (_target, table) => {
1395
1761
  if (!isString(table))
1396
1762
  throw new Error("Invalid table name");
1397
- if (!__privateGet$1(this, _tables)[table])
1398
- __privateGet$1(this, _tables)[table] = new RestRepository({ db, getFetchProps, table, links });
1399
- return __privateGet$1(this, _tables)[table];
1763
+ if (__privateGet$2(this, _tables)[table] === void 0) {
1764
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table });
1765
+ }
1766
+ return __privateGet$2(this, _tables)[table];
1400
1767
  }
1401
1768
  });
1402
1769
  for (const table of this.tableNames ?? []) {
1403
- db[table] = new RestRepository({ db, getFetchProps, table, links });
1770
+ db[table] = new RestRepository({ db, pluginOptions, table });
1404
1771
  }
1405
1772
  return db;
1406
1773
  }
@@ -1411,55 +1778,80 @@ var __accessCheck$1 = (obj, member, msg) => {
1411
1778
  if (!member.has(obj))
1412
1779
  throw TypeError("Cannot " + msg);
1413
1780
  };
1781
+ var __privateGet$1 = (obj, member, getter) => {
1782
+ __accessCheck$1(obj, member, "read from private field");
1783
+ return getter ? getter.call(obj) : member.get(obj);
1784
+ };
1414
1785
  var __privateAdd$1 = (obj, member, value) => {
1415
1786
  if (member.has(obj))
1416
1787
  throw TypeError("Cannot add the same private member more than once");
1417
1788
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1418
1789
  };
1790
+ var __privateSet$1 = (obj, member, value, setter) => {
1791
+ __accessCheck$1(obj, member, "write to private field");
1792
+ setter ? setter.call(obj, value) : member.set(obj, value);
1793
+ return value;
1794
+ };
1419
1795
  var __privateMethod$1 = (obj, member, method) => {
1420
1796
  __accessCheck$1(obj, member, "access private method");
1421
1797
  return method;
1422
1798
  };
1423
- var _search, search_fn;
1799
+ var _schema, _search, search_fn, _getSchema, getSchema_fn;
1424
1800
  class SearchPlugin extends XataPlugin {
1425
- constructor(db, links) {
1801
+ constructor(db) {
1426
1802
  super();
1427
1803
  this.db = db;
1428
- this.links = links;
1429
1804
  __privateAdd$1(this, _search);
1805
+ __privateAdd$1(this, _getSchema);
1806
+ __privateAdd$1(this, _schema, void 0);
1430
1807
  }
1431
1808
  build({ getFetchProps }) {
1432
1809
  return {
1433
1810
  all: async (query, options = {}) => {
1434
1811
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1812
+ const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
1435
1813
  return records.map((record) => {
1436
1814
  const { table = "orphan" } = record.xata;
1437
- return { table, record: initObject(this.db, this.links, table, record) };
1815
+ return { table, record: initObject(this.db, schema, table, record) };
1438
1816
  });
1439
1817
  },
1440
1818
  byTable: async (query, options = {}) => {
1441
1819
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1820
+ const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
1442
1821
  return records.reduce((acc, record) => {
1443
1822
  const { table = "orphan" } = record.xata;
1444
1823
  const items = acc[table] ?? [];
1445
- const item = initObject(this.db, this.links, table, record);
1824
+ const item = initObject(this.db, schema, table, record);
1446
1825
  return { ...acc, [table]: [...items, item] };
1447
1826
  }, {});
1448
1827
  }
1449
1828
  };
1450
1829
  }
1451
1830
  }
1831
+ _schema = new WeakMap();
1452
1832
  _search = new WeakSet();
1453
1833
  search_fn = async function(query, options, getFetchProps) {
1454
1834
  const fetchProps = await getFetchProps();
1455
- const { tables, fuzziness } = options ?? {};
1835
+ const { tables, fuzziness, highlight, prefix } = options ?? {};
1456
1836
  const { records } = await searchBranch({
1457
1837
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1458
- body: { tables, query, fuzziness },
1838
+ body: { tables, query, fuzziness, prefix, highlight },
1459
1839
  ...fetchProps
1460
1840
  });
1461
1841
  return records;
1462
1842
  };
1843
+ _getSchema = new WeakSet();
1844
+ getSchema_fn = async function(getFetchProps) {
1845
+ if (__privateGet$1(this, _schema))
1846
+ return __privateGet$1(this, _schema);
1847
+ const fetchProps = await getFetchProps();
1848
+ const { schema } = await getBranchDetails({
1849
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1850
+ ...fetchProps
1851
+ });
1852
+ __privateSet$1(this, _schema, schema);
1853
+ return schema;
1854
+ };
1463
1855
 
1464
1856
  const isBranchStrategyBuilder = (strategy) => {
1465
1857
  return typeof strategy === "function";
@@ -1471,30 +1863,39 @@ const envBranchNames = [
1471
1863
  "CF_PAGES_BRANCH",
1472
1864
  "BRANCH"
1473
1865
  ];
1474
- const defaultBranch = "main";
1475
1866
  async function getCurrentBranchName(options) {
1476
- const env = await getBranchByEnvVariable();
1477
- if (env)
1478
- return env;
1479
- const branch = await getGitBranch();
1480
- if (!branch)
1481
- return defaultBranch;
1482
- const details = await getDatabaseBranch(branch, options);
1483
- if (details)
1484
- return branch;
1485
- return defaultBranch;
1867
+ const env = getBranchByEnvVariable();
1868
+ if (env) {
1869
+ const details = await getDatabaseBranch(env, options);
1870
+ if (details)
1871
+ return env;
1872
+ console.warn(`Branch ${env} not found in Xata. Ignoring...`);
1873
+ }
1874
+ const gitBranch = await getGitBranch();
1875
+ return resolveXataBranch(gitBranch, options);
1486
1876
  }
1487
1877
  async function getCurrentBranchDetails(options) {
1488
- const env = await getBranchByEnvVariable();
1489
- if (env)
1490
- return getDatabaseBranch(env, options);
1491
- const branch = await getGitBranch();
1492
- if (!branch)
1493
- return getDatabaseBranch(defaultBranch, options);
1494
- const details = await getDatabaseBranch(branch, options);
1495
- if (details)
1496
- return details;
1497
- return getDatabaseBranch(defaultBranch, options);
1878
+ const branch = await getCurrentBranchName(options);
1879
+ return getDatabaseBranch(branch, options);
1880
+ }
1881
+ async function resolveXataBranch(gitBranch, options) {
1882
+ const databaseURL = options?.databaseURL || getDatabaseURL();
1883
+ const apiKey = options?.apiKey || getAPIKey();
1884
+ if (!databaseURL)
1885
+ throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
1886
+ if (!apiKey)
1887
+ throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
1888
+ const [protocol, , host, , dbName] = databaseURL.split("/");
1889
+ const [workspace] = host.split(".");
1890
+ const { branch } = await resolveBranch({
1891
+ apiKey,
1892
+ apiUrl: databaseURL,
1893
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
1894
+ workspacesApiUrl: `${protocol}//${host}`,
1895
+ pathParams: { dbName, workspace },
1896
+ queryParams: { gitBranch, fallbackBranch: getEnvVariable("XATA_FALLBACK_BRANCH") }
1897
+ });
1898
+ return branch;
1498
1899
  }
1499
1900
  async function getDatabaseBranch(branch, options) {
1500
1901
  const databaseURL = options?.databaseURL || getDatabaseURL();
@@ -1512,10 +1913,7 @@ async function getDatabaseBranch(branch, options) {
1512
1913
  apiUrl: databaseURL,
1513
1914
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1514
1915
  workspacesApiUrl: `${protocol}//${host}`,
1515
- pathParams: {
1516
- dbBranchName,
1517
- workspace
1518
- }
1916
+ pathParams: { dbBranchName, workspace }
1519
1917
  });
1520
1918
  } catch (err) {
1521
1919
  if (isObject(err) && err.status === 404)
@@ -1568,22 +1966,24 @@ var __privateMethod = (obj, member, method) => {
1568
1966
  const buildClient = (plugins) => {
1569
1967
  var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1570
1968
  return _a = class {
1571
- constructor(options = {}, links, tables) {
1969
+ constructor(options = {}, tables) {
1572
1970
  __privateAdd(this, _parseOptions);
1573
1971
  __privateAdd(this, _getFetchProps);
1574
1972
  __privateAdd(this, _evaluateBranch);
1575
1973
  __privateAdd(this, _branch, void 0);
1576
1974
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
1577
- const db = new SchemaPlugin(links, tables).build({ getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions) });
1578
- const search = new SearchPlugin(db, links ?? {}).build({
1579
- getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions)
1580
- });
1975
+ const pluginOptions = {
1976
+ getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1977
+ cache: safeOptions.cache
1978
+ };
1979
+ const db = new SchemaPlugin(tables).build(pluginOptions);
1980
+ const search = new SearchPlugin(db).build(pluginOptions);
1581
1981
  this.db = db;
1582
1982
  this.search = search;
1583
1983
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
1584
- if (!namespace)
1984
+ if (namespace === void 0)
1585
1985
  continue;
1586
- const result = namespace.build({ getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions) });
1986
+ const result = namespace.build(pluginOptions);
1587
1987
  if (result instanceof Promise) {
1588
1988
  void result.then((namespace2) => {
1589
1989
  this[key] = namespace2;
@@ -1597,11 +1997,12 @@ const buildClient = (plugins) => {
1597
1997
  const fetch = getFetchImplementation(options?.fetch);
1598
1998
  const databaseURL = options?.databaseURL || getDatabaseURL();
1599
1999
  const apiKey = options?.apiKey || getAPIKey();
1600
- const branch = async () => options?.branch ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
2000
+ const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
2001
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1601
2002
  if (!databaseURL || !apiKey) {
1602
2003
  throw new Error("Options databaseURL and apiKey are required");
1603
2004
  }
1604
- return { fetch, databaseURL, apiKey, branch };
2005
+ return { fetch, databaseURL, apiKey, branch, cache };
1605
2006
  }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
1606
2007
  fetch,
1607
2008
  apiKey,
@@ -1624,7 +2025,7 @@ const buildClient = (plugins) => {
1624
2025
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1625
2026
  if (__privateGet(this, _branch))
1626
2027
  return __privateGet(this, _branch);
1627
- if (!param)
2028
+ if (param === void 0)
1628
2029
  return void 0;
1629
2030
  const strategies = Array.isArray(param) ? [...param] : [param];
1630
2031
  const evaluateBranch = async (strategy) => {
@@ -1649,5 +2050,5 @@ class XataError extends Error {
1649
2050
  }
1650
2051
  }
1651
2052
 
1652
- export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, Repository, RestRepository, SchemaPlugin, SearchPlugin, 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 };
2053
+ 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 };
1653
2054
  //# sourceMappingURL=index.mjs.map