@xata.io/client 0.0.0-alpha.vf38f30b → 0.0.0-alpha.vf481c73

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,27 +7,88 @@ 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
- function getEnvVariable(name) {
25
+ function getEnvironment() {
15
26
  try {
16
- if (isObject(process) && isString(process?.env?.[name])) {
17
- return process.env[name];
27
+ if (isObject(process) && isObject(process.env)) {
28
+ return {
29
+ apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
30
+ databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
31
+ branch: process.env.XATA_BRANCH,
32
+ envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
33
+ fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
34
+ };
18
35
  }
19
36
  } catch (err) {
20
37
  }
21
38
  try {
22
- if (isObject(Deno) && isString(Deno?.env?.get(name))) {
23
- return Deno.env.get(name);
39
+ if (isObject(Deno) && isObject(Deno.env)) {
40
+ return {
41
+ apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
42
+ databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
43
+ branch: Deno.env.get("XATA_BRANCH"),
44
+ envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
45
+ fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
46
+ };
24
47
  }
25
48
  } catch (err) {
26
49
  }
50
+ return {
51
+ apiKey: getGlobalApiKey(),
52
+ databaseURL: getGlobalDatabaseURL(),
53
+ branch: getGlobalBranch(),
54
+ envBranch: void 0,
55
+ fallbackBranch: getGlobalFallbackBranch()
56
+ };
57
+ }
58
+ function getGlobalApiKey() {
59
+ try {
60
+ return XATA_API_KEY;
61
+ } catch (err) {
62
+ return void 0;
63
+ }
64
+ }
65
+ function getGlobalDatabaseURL() {
66
+ try {
67
+ return XATA_DATABASE_URL;
68
+ } catch (err) {
69
+ return void 0;
70
+ }
71
+ }
72
+ function getGlobalBranch() {
73
+ try {
74
+ return XATA_BRANCH;
75
+ } catch (err) {
76
+ return void 0;
77
+ }
78
+ }
79
+ function getGlobalFallbackBranch() {
80
+ try {
81
+ return XATA_FALLBACK_BRANCH;
82
+ } catch (err) {
83
+ return void 0;
84
+ }
27
85
  }
28
86
  async function getGitBranch() {
29
87
  try {
30
- return require("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
88
+ if (typeof require === "function") {
89
+ const req = require;
90
+ return req("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
91
+ }
31
92
  } catch (err) {
32
93
  }
33
94
  try {
@@ -45,7 +106,8 @@ async function getGitBranch() {
45
106
 
46
107
  function getAPIKey() {
47
108
  try {
48
- return getEnvVariable("XATA_API_KEY") ?? XATA_API_KEY;
109
+ const { apiKey } = getEnvironment();
110
+ return apiKey;
49
111
  } catch (err) {
50
112
  return void 0;
51
113
  }
@@ -60,16 +122,28 @@ function getFetchImplementation(userFetch) {
60
122
  return fetchImpl;
61
123
  }
62
124
 
63
- class FetcherError extends Error {
64
- constructor(status, data) {
125
+ const VERSION = "0.0.0-alpha.vf481c73";
126
+
127
+ class ErrorWithCause extends Error {
128
+ constructor(message, options) {
129
+ super(message, options);
130
+ }
131
+ }
132
+ class FetcherError extends ErrorWithCause {
133
+ constructor(status, data, requestId) {
65
134
  super(getMessage(data));
66
135
  this.status = status;
67
136
  this.errors = isBulkError(data) ? data.errors : void 0;
137
+ this.requestId = requestId;
68
138
  if (data instanceof Error) {
69
139
  this.stack = data.stack;
70
140
  this.cause = data.cause;
71
141
  }
72
142
  }
143
+ toString() {
144
+ const error = super.toString();
145
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
146
+ }
73
147
  }
74
148
  function isBulkError(error) {
75
149
  return isObject(error) && Array.isArray(error.errors);
@@ -92,7 +166,12 @@ function getMessage(data) {
92
166
  }
93
167
 
94
168
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
95
- const query = new URLSearchParams(queryParams).toString();
169
+ const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
170
+ if (value === void 0 || value === null)
171
+ return acc;
172
+ return { ...acc, [key]: value };
173
+ }, {});
174
+ const query = new URLSearchParams(cleanQueryParams).toString();
96
175
  const queryString = query.length > 0 ? `?${query}` : "";
97
176
  return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
98
177
  };
@@ -132,6 +211,7 @@ async function fetch$1({
132
211
  body: body ? JSON.stringify(body) : void 0,
133
212
  headers: {
134
213
  "Content-Type": "application/json",
214
+ "User-Agent": `Xata client-ts/${VERSION}`,
135
215
  ...headers,
136
216
  ...hostHeader(fullUrl),
137
217
  Authorization: `Bearer ${apiKey}`
@@ -140,14 +220,15 @@ async function fetch$1({
140
220
  if (response.status === 204) {
141
221
  return {};
142
222
  }
223
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
143
224
  try {
144
225
  const jsonResponse = await response.json();
145
226
  if (response.ok) {
146
227
  return jsonResponse;
147
228
  }
148
- throw new FetcherError(response.status, jsonResponse);
229
+ throw new FetcherError(response.status, jsonResponse, requestId);
149
230
  } catch (error) {
150
- throw new FetcherError(response.status, error);
231
+ throw new FetcherError(response.status, error, requestId);
151
232
  }
152
233
  }
153
234
 
@@ -241,6 +322,14 @@ const deleteDatabase = (variables) => fetch$1({
241
322
  method: "delete",
242
323
  ...variables
243
324
  });
325
+ const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
326
+ const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
327
+ const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
328
+ const resolveBranch = (variables) => fetch$1({
329
+ url: "/dbs/{dbName}/resolveBranch",
330
+ method: "get",
331
+ ...variables
332
+ });
244
333
  const getBranchDetails = (variables) => fetch$1({
245
334
  url: "/db/{dbBranchName}",
246
335
  method: "get",
@@ -348,6 +437,11 @@ const queryTable = (variables) => fetch$1({
348
437
  method: "post",
349
438
  ...variables
350
439
  });
440
+ const searchTable = (variables) => fetch$1({
441
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
442
+ method: "post",
443
+ ...variables
444
+ });
351
445
  const searchBranch = (variables) => fetch$1({
352
446
  url: "/db/{dbBranchName}/search",
353
447
  method: "post",
@@ -369,7 +463,15 @@ const operationsByTag = {
369
463
  resendWorkspaceMemberInvite,
370
464
  acceptWorkspaceMemberInvite
371
465
  },
372
- database: { getDatabaseList, createDatabase, deleteDatabase },
466
+ database: {
467
+ getDatabaseList,
468
+ createDatabase,
469
+ deleteDatabase,
470
+ getGitBranchesMapping,
471
+ addGitBranchesEntry,
472
+ removeGitBranchesEntry,
473
+ resolveBranch
474
+ },
373
475
  branch: {
374
476
  getBranchList,
375
477
  getBranchDetails,
@@ -403,6 +505,7 @@ const operationsByTag = {
403
505
  getRecord,
404
506
  bulkInsertTableRecords,
405
507
  queryTable,
508
+ searchTable,
406
509
  searchBranch
407
510
  }
408
511
  };
@@ -432,35 +535,35 @@ function isValidBuilder(builder) {
432
535
  return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
433
536
  }
434
537
 
435
- var __accessCheck$6 = (obj, member, msg) => {
538
+ var __accessCheck$7 = (obj, member, msg) => {
436
539
  if (!member.has(obj))
437
540
  throw TypeError("Cannot " + msg);
438
541
  };
439
- var __privateGet$5 = (obj, member, getter) => {
440
- __accessCheck$6(obj, member, "read from private field");
542
+ var __privateGet$7 = (obj, member, getter) => {
543
+ __accessCheck$7(obj, member, "read from private field");
441
544
  return getter ? getter.call(obj) : member.get(obj);
442
545
  };
443
- var __privateAdd$6 = (obj, member, value) => {
546
+ var __privateAdd$7 = (obj, member, value) => {
444
547
  if (member.has(obj))
445
548
  throw TypeError("Cannot add the same private member more than once");
446
549
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
447
550
  };
448
- var __privateSet$4 = (obj, member, value, setter) => {
449
- __accessCheck$6(obj, member, "write to private field");
551
+ var __privateSet$7 = (obj, member, value, setter) => {
552
+ __accessCheck$7(obj, member, "write to private field");
450
553
  setter ? setter.call(obj, value) : member.set(obj, value);
451
554
  return value;
452
555
  };
453
556
  var _extraProps, _namespaces;
454
557
  class XataApiClient {
455
558
  constructor(options = {}) {
456
- __privateAdd$6(this, _extraProps, void 0);
457
- __privateAdd$6(this, _namespaces, {});
559
+ __privateAdd$7(this, _extraProps, void 0);
560
+ __privateAdd$7(this, _namespaces, {});
458
561
  const provider = options.host ?? "production";
459
562
  const apiKey = options?.apiKey ?? getAPIKey();
460
563
  if (!apiKey) {
461
564
  throw new Error("Could not resolve a valid apiKey");
462
565
  }
463
- __privateSet$4(this, _extraProps, {
566
+ __privateSet$7(this, _extraProps, {
464
567
  apiUrl: getHostUrl(provider, "main"),
465
568
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
466
569
  fetchImpl: getFetchImplementation(options.fetch),
@@ -468,34 +571,34 @@ class XataApiClient {
468
571
  });
469
572
  }
470
573
  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;
574
+ if (!__privateGet$7(this, _namespaces).user)
575
+ __privateGet$7(this, _namespaces).user = new UserApi(__privateGet$7(this, _extraProps));
576
+ return __privateGet$7(this, _namespaces).user;
474
577
  }
475
578
  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;
579
+ if (!__privateGet$7(this, _namespaces).workspaces)
580
+ __privateGet$7(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$7(this, _extraProps));
581
+ return __privateGet$7(this, _namespaces).workspaces;
479
582
  }
480
583
  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;
584
+ if (!__privateGet$7(this, _namespaces).databases)
585
+ __privateGet$7(this, _namespaces).databases = new DatabaseApi(__privateGet$7(this, _extraProps));
586
+ return __privateGet$7(this, _namespaces).databases;
484
587
  }
485
588
  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;
589
+ if (!__privateGet$7(this, _namespaces).branches)
590
+ __privateGet$7(this, _namespaces).branches = new BranchApi(__privateGet$7(this, _extraProps));
591
+ return __privateGet$7(this, _namespaces).branches;
489
592
  }
490
593
  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;
594
+ if (!__privateGet$7(this, _namespaces).tables)
595
+ __privateGet$7(this, _namespaces).tables = new TableApi(__privateGet$7(this, _extraProps));
596
+ return __privateGet$7(this, _namespaces).tables;
494
597
  }
495
598
  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;
599
+ if (!__privateGet$7(this, _namespaces).records)
600
+ __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
601
+ return __privateGet$7(this, _namespaces).records;
499
602
  }
500
603
  }
501
604
  _extraProps = new WeakMap();
@@ -629,6 +732,33 @@ class DatabaseApi {
629
732
  ...this.extraProps
630
733
  });
631
734
  }
735
+ getGitBranchesMapping(workspace, dbName) {
736
+ return operationsByTag.database.getGitBranchesMapping({
737
+ pathParams: { workspace, dbName },
738
+ ...this.extraProps
739
+ });
740
+ }
741
+ addGitBranchesEntry(workspace, dbName, body) {
742
+ return operationsByTag.database.addGitBranchesEntry({
743
+ pathParams: { workspace, dbName },
744
+ body,
745
+ ...this.extraProps
746
+ });
747
+ }
748
+ removeGitBranchesEntry(workspace, dbName, gitBranch) {
749
+ return operationsByTag.database.removeGitBranchesEntry({
750
+ pathParams: { workspace, dbName },
751
+ queryParams: { gitBranch },
752
+ ...this.extraProps
753
+ });
754
+ }
755
+ resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
756
+ return operationsByTag.database.resolveBranch({
757
+ pathParams: { workspace, dbName },
758
+ queryParams: { gitBranch, fallbackBranch },
759
+ ...this.extraProps
760
+ });
761
+ }
632
762
  }
633
763
  class BranchApi {
634
764
  constructor(extraProps) {
@@ -646,10 +776,10 @@ class BranchApi {
646
776
  ...this.extraProps
647
777
  });
648
778
  }
649
- createBranch(workspace, database, branch, from = "", options = {}) {
779
+ createBranch(workspace, database, branch, from, options = {}) {
650
780
  return operationsByTag.branch.createBranch({
651
781
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
652
- queryParams: { from },
782
+ queryParams: isString(from) ? { from } : void 0,
653
783
  body: options,
654
784
  ...this.extraProps
655
785
  });
@@ -831,6 +961,13 @@ class RecordsApi {
831
961
  ...this.extraProps
832
962
  });
833
963
  }
964
+ searchTable(workspace, database, branch, tableName, query) {
965
+ return operationsByTag.records.searchTable({
966
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
967
+ body: query,
968
+ ...this.extraProps
969
+ });
970
+ }
834
971
  searchBranch(workspace, database, branch, query) {
835
972
  return operationsByTag.records.searchBranch({
836
973
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -850,43 +987,43 @@ class XataApiPlugin {
850
987
  class XataPlugin {
851
988
  }
852
989
 
853
- var __accessCheck$5 = (obj, member, msg) => {
990
+ var __accessCheck$6 = (obj, member, msg) => {
854
991
  if (!member.has(obj))
855
992
  throw TypeError("Cannot " + msg);
856
993
  };
857
- var __privateGet$4 = (obj, member, getter) => {
858
- __accessCheck$5(obj, member, "read from private field");
994
+ var __privateGet$6 = (obj, member, getter) => {
995
+ __accessCheck$6(obj, member, "read from private field");
859
996
  return getter ? getter.call(obj) : member.get(obj);
860
997
  };
861
- var __privateAdd$5 = (obj, member, value) => {
998
+ var __privateAdd$6 = (obj, member, value) => {
862
999
  if (member.has(obj))
863
1000
  throw TypeError("Cannot add the same private member more than once");
864
1001
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
865
1002
  };
866
- var __privateSet$3 = (obj, member, value, setter) => {
867
- __accessCheck$5(obj, member, "write to private field");
1003
+ var __privateSet$6 = (obj, member, value, setter) => {
1004
+ __accessCheck$6(obj, member, "write to private field");
868
1005
  setter ? setter.call(obj, value) : member.set(obj, value);
869
1006
  return value;
870
1007
  };
871
- var _query;
1008
+ var _query, _page;
872
1009
  class Page {
873
1010
  constructor(query, meta, records = []) {
874
- __privateAdd$5(this, _query, void 0);
875
- __privateSet$3(this, _query, query);
1011
+ __privateAdd$6(this, _query, void 0);
1012
+ __privateSet$6(this, _query, query);
876
1013
  this.meta = meta;
877
- this.records = records;
1014
+ this.records = new RecordArray(this, records);
878
1015
  }
879
1016
  async nextPage(size, offset) {
880
- return __privateGet$4(this, _query).getPaginated({ page: { size, offset, after: this.meta.page.cursor } });
1017
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
881
1018
  }
882
1019
  async previousPage(size, offset) {
883
- return __privateGet$4(this, _query).getPaginated({ page: { size, offset, before: this.meta.page.cursor } });
1020
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
884
1021
  }
885
1022
  async firstPage(size, offset) {
886
- return __privateGet$4(this, _query).getPaginated({ page: { size, offset, first: this.meta.page.cursor } });
1023
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
887
1024
  }
888
1025
  async lastPage(size, offset) {
889
- return __privateGet$4(this, _query).getPaginated({ page: { size, offset, last: this.meta.page.cursor } });
1026
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
890
1027
  }
891
1028
  hasNextPage() {
892
1029
  return this.meta.page.more;
@@ -894,50 +1031,93 @@ class Page {
894
1031
  }
895
1032
  _query = new WeakMap();
896
1033
  const PAGINATION_MAX_SIZE = 200;
897
- const PAGINATION_DEFAULT_SIZE = 200;
1034
+ const PAGINATION_DEFAULT_SIZE = 20;
898
1035
  const PAGINATION_MAX_OFFSET = 800;
899
1036
  const PAGINATION_DEFAULT_OFFSET = 0;
1037
+ function isCursorPaginationOptions(options) {
1038
+ return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
1039
+ }
1040
+ const _RecordArray = class extends Array {
1041
+ constructor(page, overrideRecords) {
1042
+ super(..._RecordArray.parseConstructorParams(page, overrideRecords));
1043
+ __privateAdd$6(this, _page, void 0);
1044
+ __privateSet$6(this, _page, page);
1045
+ }
1046
+ static parseConstructorParams(...args) {
1047
+ if (args.length === 1 && typeof args[0] === "number") {
1048
+ return new Array(args[0]);
1049
+ }
1050
+ if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
1051
+ const result = args[1] ?? args[0].records ?? [];
1052
+ return new Array(...result);
1053
+ }
1054
+ return new Array(...args);
1055
+ }
1056
+ async nextPage(size, offset) {
1057
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1058
+ return new _RecordArray(newPage);
1059
+ }
1060
+ async previousPage(size, offset) {
1061
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1062
+ return new _RecordArray(newPage);
1063
+ }
1064
+ async firstPage(size, offset) {
1065
+ const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1066
+ return new _RecordArray(newPage);
1067
+ }
1068
+ async lastPage(size, offset) {
1069
+ const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1070
+ return new _RecordArray(newPage);
1071
+ }
1072
+ hasNextPage() {
1073
+ return __privateGet$6(this, _page).meta.page.more;
1074
+ }
1075
+ };
1076
+ let RecordArray = _RecordArray;
1077
+ _page = new WeakMap();
900
1078
 
901
- var __accessCheck$4 = (obj, member, msg) => {
1079
+ var __accessCheck$5 = (obj, member, msg) => {
902
1080
  if (!member.has(obj))
903
1081
  throw TypeError("Cannot " + msg);
904
1082
  };
905
- var __privateGet$3 = (obj, member, getter) => {
906
- __accessCheck$4(obj, member, "read from private field");
1083
+ var __privateGet$5 = (obj, member, getter) => {
1084
+ __accessCheck$5(obj, member, "read from private field");
907
1085
  return getter ? getter.call(obj) : member.get(obj);
908
1086
  };
909
- var __privateAdd$4 = (obj, member, value) => {
1087
+ var __privateAdd$5 = (obj, member, value) => {
910
1088
  if (member.has(obj))
911
1089
  throw TypeError("Cannot add the same private member more than once");
912
1090
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
913
1091
  };
914
- var __privateSet$2 = (obj, member, value, setter) => {
915
- __accessCheck$4(obj, member, "write to private field");
1092
+ var __privateSet$5 = (obj, member, value, setter) => {
1093
+ __accessCheck$5(obj, member, "write to private field");
916
1094
  setter ? setter.call(obj, value) : member.set(obj, value);
917
1095
  return value;
918
1096
  };
919
1097
  var _table$1, _repository, _data;
920
1098
  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: {} });
1099
+ constructor(repository, table, data, rawParent) {
1100
+ __privateAdd$5(this, _table$1, void 0);
1101
+ __privateAdd$5(this, _repository, void 0);
1102
+ __privateAdd$5(this, _data, { filter: {} });
925
1103
  this.meta = { page: { cursor: "start", more: true } };
926
- this.records = [];
927
- __privateSet$2(this, _table$1, table);
1104
+ this.records = new RecordArray(this, []);
1105
+ __privateSet$5(this, _table$1, table);
928
1106
  if (repository) {
929
- __privateSet$2(this, _repository, repository);
1107
+ __privateSet$5(this, _repository, repository);
930
1108
  } else {
931
- __privateSet$2(this, _repository, this);
1109
+ __privateSet$5(this, _repository, this);
932
1110
  }
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;
1111
+ const parent = cleanParent(data, rawParent);
1112
+ __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
1113
+ __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
1114
+ __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
1115
+ __privateGet$5(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
1116
+ __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1117
+ __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1118
+ __privateGet$5(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
1119
+ __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1120
+ __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
941
1121
  this.any = this.any.bind(this);
942
1122
  this.all = this.all.bind(this);
943
1123
  this.not = this.not.bind(this);
@@ -948,75 +1128,88 @@ const _Query = class {
948
1128
  Object.defineProperty(this, "repository", { enumerable: false });
949
1129
  }
950
1130
  getQueryOptions() {
951
- return __privateGet$3(this, _data);
1131
+ return __privateGet$5(this, _data);
1132
+ }
1133
+ key() {
1134
+ const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$5(this, _data);
1135
+ const key = JSON.stringify({ columns, filter, sort, pagination });
1136
+ return toBase64(key);
952
1137
  }
953
1138
  any(...queries) {
954
1139
  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));
1140
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
956
1141
  }
957
1142
  all(...queries) {
958
1143
  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));
1144
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
960
1145
  }
961
1146
  not(...queries) {
962
1147
  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));
1148
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
964
1149
  }
965
1150
  none(...queries) {
966
1151
  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));
1152
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
968
1153
  }
969
1154
  filter(a, b) {
970
1155
  if (arguments.length === 1) {
971
1156
  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));
1157
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1158
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
974
1159
  } 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));
1160
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
1161
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
977
1162
  }
978
1163
  }
979
1164
  sort(column, direction) {
980
- const originalSort = [__privateGet$3(this, _data).sort ?? []].flat();
1165
+ const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
981
1166
  const sort = [...originalSort, { column, direction }];
982
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { sort }, __privateGet$3(this, _data));
1167
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
983
1168
  }
984
1169
  select(columns) {
985
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { columns }, __privateGet$3(this, _data));
1170
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { columns }, __privateGet$5(this, _data));
986
1171
  }
987
1172
  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);
1173
+ const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
1174
+ return __privateGet$5(this, _repository).query(query);
990
1175
  }
991
1176
  async *[Symbol.asyncIterator]() {
992
- for await (const [record] of this.getIterator(1)) {
1177
+ for await (const [record] of this.getIterator({ batchSize: 1 })) {
993
1178
  yield record;
994
1179
  }
995
1180
  }
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;
1181
+ async *getIterator(options = {}) {
1182
+ const { batchSize = 1 } = options;
1183
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
1184
+ let more = page.hasNextPage();
1185
+ yield page.records;
1186
+ while (more) {
1187
+ page = await page.nextPage();
1188
+ more = page.hasNextPage();
1189
+ yield page.records;
1004
1190
  }
1005
1191
  }
1006
1192
  async getMany(options = {}) {
1007
- const { records } = await this.getPaginated(options);
1008
- return records;
1193
+ const page = await this.getPaginated(options);
1194
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1195
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1196
+ }
1197
+ return page.records;
1009
1198
  }
1010
- async getAll(chunk = PAGINATION_MAX_SIZE, options = {}) {
1199
+ async getAll(options = {}) {
1200
+ const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
1011
1201
  const results = [];
1012
- for await (const page of this.getIterator(chunk, options)) {
1202
+ for await (const page of this.getIterator({ ...rest, batchSize })) {
1013
1203
  results.push(...page);
1014
1204
  }
1015
1205
  return results;
1016
1206
  }
1017
- async getOne(options = {}) {
1018
- const records = await this.getMany({ ...options, page: { size: 1 } });
1019
- return records[0] || null;
1207
+ async getFirst(options = {}) {
1208
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1209
+ return records[0] ?? null;
1210
+ }
1211
+ cache(ttl) {
1212
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1020
1213
  }
1021
1214
  nextPage(size, offset) {
1022
1215
  return this.firstPage(size, offset);
@@ -1025,10 +1218,10 @@ const _Query = class {
1025
1218
  return this.firstPage(size, offset);
1026
1219
  }
1027
1220
  firstPage(size, offset) {
1028
- return this.getPaginated({ page: { size, offset } });
1221
+ return this.getPaginated({ pagination: { size, offset } });
1029
1222
  }
1030
1223
  lastPage(size, offset) {
1031
- return this.getPaginated({ page: { size, offset, before: "end" } });
1224
+ return this.getPaginated({ pagination: { size, offset, before: "end" } });
1032
1225
  }
1033
1226
  hasNextPage() {
1034
1227
  return this.meta.page.more;
@@ -1038,12 +1231,20 @@ let Query = _Query;
1038
1231
  _table$1 = new WeakMap();
1039
1232
  _repository = new WeakMap();
1040
1233
  _data = new WeakMap();
1234
+ function cleanParent(data, parent) {
1235
+ if (isCursorPaginationOptions(data.pagination)) {
1236
+ return { ...parent, sorting: void 0, filter: void 0 };
1237
+ }
1238
+ return parent;
1239
+ }
1041
1240
 
1042
1241
  function isIdentifiable(x) {
1043
1242
  return isObject(x) && isString(x?.id);
1044
1243
  }
1045
1244
  function isXataRecord(x) {
1046
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1245
+ const record = x;
1246
+ const metadata = record?.getMetadata();
1247
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1047
1248
  }
1048
1249
 
1049
1250
  function isSortFilterString(value) {
@@ -1069,169 +1270,232 @@ function buildSortFilter(filter) {
1069
1270
  }
1070
1271
  }
1071
1272
 
1072
- var __accessCheck$3 = (obj, member, msg) => {
1273
+ var __accessCheck$4 = (obj, member, msg) => {
1073
1274
  if (!member.has(obj))
1074
1275
  throw TypeError("Cannot " + msg);
1075
1276
  };
1076
- var __privateGet$2 = (obj, member, getter) => {
1077
- __accessCheck$3(obj, member, "read from private field");
1277
+ var __privateGet$4 = (obj, member, getter) => {
1278
+ __accessCheck$4(obj, member, "read from private field");
1078
1279
  return getter ? getter.call(obj) : member.get(obj);
1079
1280
  };
1080
- var __privateAdd$3 = (obj, member, value) => {
1281
+ var __privateAdd$4 = (obj, member, value) => {
1081
1282
  if (member.has(obj))
1082
1283
  throw TypeError("Cannot add the same private member more than once");
1083
1284
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1084
1285
  };
1085
- var __privateSet$1 = (obj, member, value, setter) => {
1086
- __accessCheck$3(obj, member, "write to private field");
1286
+ var __privateSet$4 = (obj, member, value, setter) => {
1287
+ __accessCheck$4(obj, member, "write to private field");
1087
1288
  setter ? setter.call(obj, value) : member.set(obj, value);
1088
1289
  return value;
1089
1290
  };
1090
1291
  var __privateMethod$2 = (obj, member, method) => {
1091
- __accessCheck$3(obj, member, "access private method");
1292
+ __accessCheck$4(obj, member, "access private method");
1092
1293
  return method;
1093
1294
  };
1094
- var _table, _links, _getFetchProps, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn;
1295
+ var _table, _getFetchProps, _cache, _schemaTables$2, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _invalidateCache, invalidateCache_fn, _setCacheRecord, setCacheRecord_fn, _getCacheRecord, getCacheRecord_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaTables$1, getSchemaTables_fn$1;
1095
1296
  class Repository extends Query {
1096
1297
  }
1097
1298
  class RestRepository extends Query {
1098
1299
  constructor(options) {
1099
1300
  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);
1301
+ __privateAdd$4(this, _insertRecordWithoutId);
1302
+ __privateAdd$4(this, _insertRecordWithId);
1303
+ __privateAdd$4(this, _bulkInsertTableRecords);
1304
+ __privateAdd$4(this, _updateRecordWithID);
1305
+ __privateAdd$4(this, _upsertRecordWithID);
1306
+ __privateAdd$4(this, _deleteRecord);
1307
+ __privateAdd$4(this, _invalidateCache);
1308
+ __privateAdd$4(this, _setCacheRecord);
1309
+ __privateAdd$4(this, _getCacheRecord);
1310
+ __privateAdd$4(this, _setCacheQuery);
1311
+ __privateAdd$4(this, _getCacheQuery);
1312
+ __privateAdd$4(this, _getSchemaTables$1);
1313
+ __privateAdd$4(this, _table, void 0);
1314
+ __privateAdd$4(this, _getFetchProps, void 0);
1315
+ __privateAdd$4(this, _cache, void 0);
1316
+ __privateAdd$4(this, _schemaTables$2, void 0);
1317
+ __privateSet$4(this, _table, options.table);
1318
+ __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1112
1319
  this.db = options.db;
1320
+ __privateSet$4(this, _cache, options.pluginOptions.cache);
1321
+ __privateSet$4(this, _schemaTables$2, options.schemaTables);
1113
1322
  }
1114
1323
  async create(a, b) {
1115
1324
  if (Array.isArray(a)) {
1116
- return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1325
+ if (a.length === 0)
1326
+ return [];
1327
+ const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1328
+ await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1329
+ return records;
1117
1330
  }
1118
1331
  if (isString(a) && isObject(b)) {
1119
1332
  if (a === "")
1120
1333
  throw new Error("The id can't be empty");
1121
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1334
+ const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1335
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1336
+ return record;
1122
1337
  }
1123
1338
  if (isObject(a) && isString(a.id)) {
1124
1339
  if (a.id === "")
1125
1340
  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 });
1341
+ const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1342
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1343
+ return record;
1127
1344
  }
1128
1345
  if (isObject(a)) {
1129
- return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1346
+ const record = await __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1347
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1348
+ return record;
1130
1349
  }
1131
1350
  throw new Error("Invalid arguments for create method");
1132
1351
  }
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;
1352
+ async read(a) {
1353
+ if (Array.isArray(a)) {
1354
+ if (a.length === 0)
1355
+ return [];
1356
+ const ids = a.map((item) => isString(item) ? item : item.id).filter((id2) => isString(id2));
1357
+ return this.getAll({ filter: { id: { $any: ids } } });
1358
+ }
1359
+ const id = isString(a) ? a : a.id;
1360
+ if (isString(id)) {
1361
+ const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, id);
1362
+ if (cacheRecord)
1363
+ return cacheRecord;
1364
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1365
+ try {
1366
+ const response = await getRecord({
1367
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: id },
1368
+ ...fetchProps
1369
+ });
1370
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1371
+ return initObject(this.db, schemaTables, __privateGet$4(this, _table), response);
1372
+ } catch (e) {
1373
+ if (isObject(e) && e.status === 404) {
1374
+ return null;
1375
+ }
1376
+ throw e;
1144
1377
  }
1145
- throw e;
1146
1378
  }
1147
1379
  }
1148
1380
  async update(a, b) {
1149
1381
  if (Array.isArray(a)) {
1382
+ if (a.length === 0)
1383
+ return [];
1150
1384
  if (a.length > 100) {
1151
1385
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1152
1386
  }
1153
1387
  return Promise.all(a.map((object) => this.update(object)));
1154
1388
  }
1155
1389
  if (isString(a) && isObject(b)) {
1156
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1390
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1391
+ const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1392
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1393
+ return record;
1157
1394
  }
1158
1395
  if (isObject(a) && isString(a.id)) {
1159
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1396
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1397
+ const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1398
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1399
+ return record;
1160
1400
  }
1161
1401
  throw new Error("Invalid arguments for update method");
1162
1402
  }
1163
1403
  async createOrUpdate(a, b) {
1164
1404
  if (Array.isArray(a)) {
1405
+ if (a.length === 0)
1406
+ return [];
1165
1407
  if (a.length > 100) {
1166
1408
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1167
1409
  }
1168
1410
  return Promise.all(a.map((object) => this.createOrUpdate(object)));
1169
1411
  }
1170
1412
  if (isString(a) && isObject(b)) {
1171
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1413
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1414
+ const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1415
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1416
+ return record;
1172
1417
  }
1173
1418
  if (isObject(a) && isString(a.id)) {
1174
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1419
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1420
+ const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1421
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1422
+ return record;
1175
1423
  }
1176
1424
  throw new Error("Invalid arguments for createOrUpdate method");
1177
1425
  }
1178
- async delete(recordId) {
1179
- if (Array.isArray(recordId)) {
1180
- if (recordId.length > 100) {
1426
+ async delete(a) {
1427
+ if (Array.isArray(a)) {
1428
+ if (a.length === 0)
1429
+ return;
1430
+ if (a.length > 100) {
1181
1431
  console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1182
1432
  }
1183
- await Promise.all(recordId.map((id) => this.delete(id)));
1433
+ await Promise.all(a.map((id) => this.delete(id)));
1184
1434
  return;
1185
1435
  }
1186
- if (isString(recordId)) {
1187
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, recordId);
1436
+ if (isString(a)) {
1437
+ await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1438
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1188
1439
  return;
1189
1440
  }
1190
- if (isObject(recordId) && isString(recordId.id)) {
1191
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, recordId.id);
1441
+ if (isObject(a) && isString(a.id)) {
1442
+ await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1443
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1192
1444
  return;
1193
1445
  }
1194
1446
  throw new Error("Invalid arguments for delete method");
1195
1447
  }
1196
1448
  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 },
1449
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1450
+ const { records } = await searchTable({
1451
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1452
+ body: {
1453
+ query,
1454
+ fuzziness: options.fuzziness,
1455
+ highlight: options.highlight,
1456
+ filter: options.filter
1457
+ },
1201
1458
  ...fetchProps
1202
1459
  });
1203
- return records.map((item) => initObject(this.db, __privateGet$2(this, _links), __privateGet$2(this, _table), item));
1460
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1461
+ return records.map((item) => initObject(this.db, schemaTables, __privateGet$4(this, _table), item));
1204
1462
  }
1205
1463
  async query(query) {
1464
+ const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1465
+ if (cacheQuery)
1466
+ return new Page(query, cacheQuery.meta, cacheQuery.records);
1206
1467
  const data = query.getQueryOptions();
1207
1468
  const body = {
1208
1469
  filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1209
- sort: data.sort ? buildSortFilter(data.sort) : void 0,
1210
- page: data.page,
1470
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1471
+ page: data.pagination,
1211
1472
  columns: data.columns
1212
1473
  };
1213
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1474
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1214
1475
  const { meta, records: objects } = await queryTable({
1215
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table) },
1476
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1216
1477
  body,
1217
1478
  ...fetchProps
1218
1479
  });
1219
- const records = objects.map((record) => initObject(this.db, __privateGet$2(this, _links), __privateGet$2(this, _table), record));
1480
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1481
+ const records = objects.map((record) => initObject(this.db, schemaTables, __privateGet$4(this, _table), record));
1482
+ await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1220
1483
  return new Page(query, meta, records);
1221
1484
  }
1222
1485
  }
1223
1486
  _table = new WeakMap();
1224
- _links = new WeakMap();
1225
1487
  _getFetchProps = new WeakMap();
1488
+ _cache = new WeakMap();
1489
+ _schemaTables$2 = new WeakMap();
1226
1490
  _insertRecordWithoutId = new WeakSet();
1227
1491
  insertRecordWithoutId_fn = async function(object) {
1228
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1492
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1229
1493
  const record = transformObjectLinks(object);
1230
1494
  const response = await insertRecord({
1231
1495
  pathParams: {
1232
1496
  workspace: "{workspaceId}",
1233
1497
  dbBranchName: "{dbBranch}",
1234
- tableName: __privateGet$2(this, _table)
1498
+ tableName: __privateGet$4(this, _table)
1235
1499
  },
1236
1500
  body: record,
1237
1501
  ...fetchProps
@@ -1244,13 +1508,13 @@ insertRecordWithoutId_fn = async function(object) {
1244
1508
  };
1245
1509
  _insertRecordWithId = new WeakSet();
1246
1510
  insertRecordWithId_fn = async function(recordId, object) {
1247
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1511
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1248
1512
  const record = transformObjectLinks(object);
1249
1513
  const response = await insertRecordWithID({
1250
1514
  pathParams: {
1251
1515
  workspace: "{workspaceId}",
1252
1516
  dbBranchName: "{dbBranch}",
1253
- tableName: __privateGet$2(this, _table),
1517
+ tableName: __privateGet$4(this, _table),
1254
1518
  recordId
1255
1519
  },
1256
1520
  body: record,
@@ -1265,25 +1529,29 @@ insertRecordWithId_fn = async function(recordId, object) {
1265
1529
  };
1266
1530
  _bulkInsertTableRecords = new WeakSet();
1267
1531
  bulkInsertTableRecords_fn = async function(objects) {
1268
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1532
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1269
1533
  const records = objects.map((object) => transformObjectLinks(object));
1270
- const response = await bulkInsertTableRecords({
1271
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table) },
1534
+ const { recordIDs } = await bulkInsertTableRecords({
1535
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1272
1536
  body: { records },
1273
1537
  ...fetchProps
1274
1538
  });
1275
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1539
+ const finalObjects = await this.read(recordIDs);
1276
1540
  if (finalObjects.length !== objects.length) {
1277
1541
  throw new Error("The server failed to save some records");
1278
1542
  }
1279
- return finalObjects;
1543
+ const dictionary = finalObjects.reduce((acc, object) => {
1544
+ acc[object.id] = object;
1545
+ return acc;
1546
+ }, {});
1547
+ return recordIDs.map((id) => dictionary[id]);
1280
1548
  };
1281
1549
  _updateRecordWithID = new WeakSet();
1282
1550
  updateRecordWithID_fn = async function(recordId, object) {
1283
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1551
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1284
1552
  const record = transformObjectLinks(object);
1285
1553
  const response = await updateRecordWithID({
1286
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table), recordId },
1554
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1287
1555
  body: record,
1288
1556
  ...fetchProps
1289
1557
  });
@@ -1294,9 +1562,9 @@ updateRecordWithID_fn = async function(recordId, object) {
1294
1562
  };
1295
1563
  _upsertRecordWithID = new WeakSet();
1296
1564
  upsertRecordWithID_fn = async function(recordId, object) {
1297
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1565
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1298
1566
  const response = await upsertRecordWithID({
1299
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table), recordId },
1567
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1300
1568
  body: object,
1301
1569
  ...fetchProps
1302
1570
  });
@@ -1307,12 +1575,63 @@ upsertRecordWithID_fn = async function(recordId, object) {
1307
1575
  };
1308
1576
  _deleteRecord = new WeakSet();
1309
1577
  deleteRecord_fn = async function(recordId) {
1310
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1578
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1311
1579
  await deleteRecord({
1312
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table), recordId },
1580
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1313
1581
  ...fetchProps
1314
1582
  });
1315
1583
  };
1584
+ _invalidateCache = new WeakSet();
1585
+ invalidateCache_fn = async function(recordId) {
1586
+ await __privateGet$4(this, _cache).delete(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1587
+ const cacheItems = await __privateGet$4(this, _cache).getAll();
1588
+ const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1589
+ for (const [key, value] of queries) {
1590
+ const ids = getIds(value);
1591
+ if (ids.includes(recordId))
1592
+ await __privateGet$4(this, _cache).delete(key);
1593
+ }
1594
+ };
1595
+ _setCacheRecord = new WeakSet();
1596
+ setCacheRecord_fn = async function(record) {
1597
+ if (!__privateGet$4(this, _cache).cacheRecords)
1598
+ return;
1599
+ await __privateGet$4(this, _cache).set(`rec_${__privateGet$4(this, _table)}:${record.id}`, record);
1600
+ };
1601
+ _getCacheRecord = new WeakSet();
1602
+ getCacheRecord_fn = async function(recordId) {
1603
+ if (!__privateGet$4(this, _cache).cacheRecords)
1604
+ return null;
1605
+ return __privateGet$4(this, _cache).get(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1606
+ };
1607
+ _setCacheQuery = new WeakSet();
1608
+ setCacheQuery_fn = async function(query, meta, records) {
1609
+ await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1610
+ };
1611
+ _getCacheQuery = new WeakSet();
1612
+ getCacheQuery_fn = async function(query) {
1613
+ const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
1614
+ const result = await __privateGet$4(this, _cache).get(key);
1615
+ if (!result)
1616
+ return null;
1617
+ const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1618
+ if (ttl < 0)
1619
+ return null;
1620
+ const hasExpired = result.date.getTime() + ttl < Date.now();
1621
+ return hasExpired ? null : result;
1622
+ };
1623
+ _getSchemaTables$1 = new WeakSet();
1624
+ getSchemaTables_fn$1 = async function() {
1625
+ if (__privateGet$4(this, _schemaTables$2))
1626
+ return __privateGet$4(this, _schemaTables$2);
1627
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1628
+ const { schema } = await getBranchDetails({
1629
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1630
+ ...fetchProps
1631
+ });
1632
+ __privateSet$4(this, _schemaTables$2, schema.tables);
1633
+ return schema.tables;
1634
+ };
1316
1635
  const transformObjectLinks = (object) => {
1317
1636
  return Object.entries(object).reduce((acc, [key, value]) => {
1318
1637
  if (key === "xata")
@@ -1320,15 +1639,34 @@ const transformObjectLinks = (object) => {
1320
1639
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1321
1640
  }, {});
1322
1641
  };
1323
- const initObject = (db, links, table, object) => {
1642
+ const initObject = (db, schemaTables, table, object) => {
1324
1643
  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);
1644
+ const { xata, ...rest } = object ?? {};
1645
+ Object.assign(result, rest);
1646
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
1647
+ if (!columns)
1648
+ console.error(`Table ${table} not found in schema`);
1649
+ for (const column of columns ?? []) {
1650
+ const value = result[column.name];
1651
+ switch (column.type) {
1652
+ case "datetime": {
1653
+ const date = value !== void 0 ? new Date(value) : void 0;
1654
+ if (date && isNaN(date.getTime())) {
1655
+ console.error(`Failed to parse date ${value} for field ${column.name}`);
1656
+ } else if (date) {
1657
+ result[column.name] = date;
1658
+ }
1659
+ break;
1660
+ }
1661
+ case "link": {
1662
+ const linkTable = column.link?.table;
1663
+ if (!linkTable) {
1664
+ console.error(`Failed to parse link for field ${column.name}`);
1665
+ } else if (isObject(value)) {
1666
+ result[column.name] = initObject(db, schemaTables, linkTable, value);
1667
+ }
1668
+ break;
1669
+ }
1332
1670
  }
1333
1671
  }
1334
1672
  result.read = function() {
@@ -1340,12 +1678,74 @@ const initObject = (db, links, table, object) => {
1340
1678
  result.delete = function() {
1341
1679
  return db[table].delete(result["id"]);
1342
1680
  };
1343
- for (const prop of ["read", "update", "delete"]) {
1681
+ result.getMetadata = function() {
1682
+ return xata;
1683
+ };
1684
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1344
1685
  Object.defineProperty(result, prop, { enumerable: false });
1345
1686
  }
1346
1687
  Object.freeze(result);
1347
1688
  return result;
1348
1689
  };
1690
+ function getIds(value) {
1691
+ if (Array.isArray(value)) {
1692
+ return value.map((item) => getIds(item)).flat();
1693
+ }
1694
+ if (!isObject(value))
1695
+ return [];
1696
+ const nestedIds = Object.values(value).map((item) => getIds(item)).flat();
1697
+ return isString(value.id) ? [value.id, ...nestedIds] : nestedIds;
1698
+ }
1699
+
1700
+ var __accessCheck$3 = (obj, member, msg) => {
1701
+ if (!member.has(obj))
1702
+ throw TypeError("Cannot " + msg);
1703
+ };
1704
+ var __privateGet$3 = (obj, member, getter) => {
1705
+ __accessCheck$3(obj, member, "read from private field");
1706
+ return getter ? getter.call(obj) : member.get(obj);
1707
+ };
1708
+ var __privateAdd$3 = (obj, member, value) => {
1709
+ if (member.has(obj))
1710
+ throw TypeError("Cannot add the same private member more than once");
1711
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1712
+ };
1713
+ var __privateSet$3 = (obj, member, value, setter) => {
1714
+ __accessCheck$3(obj, member, "write to private field");
1715
+ setter ? setter.call(obj, value) : member.set(obj, value);
1716
+ return value;
1717
+ };
1718
+ var _map;
1719
+ class SimpleCache {
1720
+ constructor(options = {}) {
1721
+ __privateAdd$3(this, _map, void 0);
1722
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1723
+ this.capacity = options.max ?? 500;
1724
+ this.cacheRecords = options.cacheRecords ?? true;
1725
+ this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1726
+ }
1727
+ async getAll() {
1728
+ return Object.fromEntries(__privateGet$3(this, _map));
1729
+ }
1730
+ async get(key) {
1731
+ return __privateGet$3(this, _map).get(key) ?? null;
1732
+ }
1733
+ async set(key, value) {
1734
+ await this.delete(key);
1735
+ __privateGet$3(this, _map).set(key, value);
1736
+ if (__privateGet$3(this, _map).size > this.capacity) {
1737
+ const leastRecentlyUsed = __privateGet$3(this, _map).keys().next().value;
1738
+ await this.delete(leastRecentlyUsed);
1739
+ }
1740
+ }
1741
+ async delete(key) {
1742
+ __privateGet$3(this, _map).delete(key);
1743
+ }
1744
+ async clear() {
1745
+ return __privateGet$3(this, _map).clear();
1746
+ }
1747
+ }
1748
+ _map = new WeakMap();
1349
1749
 
1350
1750
  const gt = (value) => ({ $gt: value });
1351
1751
  const ge = (value) => ({ $ge: value });
@@ -1370,7 +1770,7 @@ var __accessCheck$2 = (obj, member, msg) => {
1370
1770
  if (!member.has(obj))
1371
1771
  throw TypeError("Cannot " + msg);
1372
1772
  };
1373
- var __privateGet$1 = (obj, member, getter) => {
1773
+ var __privateGet$2 = (obj, member, getter) => {
1374
1774
  __accessCheck$2(obj, member, "read from private field");
1375
1775
  return getter ? getter.call(obj) : member.get(obj);
1376
1776
  };
@@ -1379,122 +1779,158 @@ var __privateAdd$2 = (obj, member, value) => {
1379
1779
  throw TypeError("Cannot add the same private member more than once");
1380
1780
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1381
1781
  };
1382
- var _tables;
1782
+ var __privateSet$2 = (obj, member, value, setter) => {
1783
+ __accessCheck$2(obj, member, "write to private field");
1784
+ setter ? setter.call(obj, value) : member.set(obj, value);
1785
+ return value;
1786
+ };
1787
+ var _tables, _schemaTables$1;
1383
1788
  class SchemaPlugin extends XataPlugin {
1384
- constructor(links, tableNames) {
1789
+ constructor(schemaTables) {
1385
1790
  super();
1386
- this.links = links;
1387
- this.tableNames = tableNames;
1388
1791
  __privateAdd$2(this, _tables, {});
1792
+ __privateAdd$2(this, _schemaTables$1, void 0);
1793
+ __privateSet$2(this, _schemaTables$1, schemaTables);
1389
1794
  }
1390
- build(options) {
1391
- const { getFetchProps } = options;
1392
- const links = this.links;
1795
+ build(pluginOptions) {
1393
1796
  const db = new Proxy({}, {
1394
1797
  get: (_target, table) => {
1395
1798
  if (!isString(table))
1396
1799
  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];
1800
+ if (__privateGet$2(this, _tables)[table] === void 0) {
1801
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table });
1802
+ }
1803
+ return __privateGet$2(this, _tables)[table];
1400
1804
  }
1401
1805
  });
1402
- for (const table of this.tableNames ?? []) {
1403
- db[table] = new RestRepository({ db, getFetchProps, table, links });
1806
+ const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
1807
+ for (const table of tableNames) {
1808
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1404
1809
  }
1405
1810
  return db;
1406
1811
  }
1407
1812
  }
1408
1813
  _tables = new WeakMap();
1814
+ _schemaTables$1 = new WeakMap();
1409
1815
 
1410
1816
  var __accessCheck$1 = (obj, member, msg) => {
1411
1817
  if (!member.has(obj))
1412
1818
  throw TypeError("Cannot " + msg);
1413
1819
  };
1820
+ var __privateGet$1 = (obj, member, getter) => {
1821
+ __accessCheck$1(obj, member, "read from private field");
1822
+ return getter ? getter.call(obj) : member.get(obj);
1823
+ };
1414
1824
  var __privateAdd$1 = (obj, member, value) => {
1415
1825
  if (member.has(obj))
1416
1826
  throw TypeError("Cannot add the same private member more than once");
1417
1827
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1418
1828
  };
1829
+ var __privateSet$1 = (obj, member, value, setter) => {
1830
+ __accessCheck$1(obj, member, "write to private field");
1831
+ setter ? setter.call(obj, value) : member.set(obj, value);
1832
+ return value;
1833
+ };
1419
1834
  var __privateMethod$1 = (obj, member, method) => {
1420
1835
  __accessCheck$1(obj, member, "access private method");
1421
1836
  return method;
1422
1837
  };
1423
- var _search, search_fn;
1838
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1424
1839
  class SearchPlugin extends XataPlugin {
1425
- constructor(db, links) {
1840
+ constructor(db, schemaTables) {
1426
1841
  super();
1427
1842
  this.db = db;
1428
- this.links = links;
1429
1843
  __privateAdd$1(this, _search);
1844
+ __privateAdd$1(this, _getSchemaTables);
1845
+ __privateAdd$1(this, _schemaTables, void 0);
1846
+ __privateSet$1(this, _schemaTables, schemaTables);
1430
1847
  }
1431
1848
  build({ getFetchProps }) {
1432
1849
  return {
1433
1850
  all: async (query, options = {}) => {
1434
1851
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1852
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1435
1853
  return records.map((record) => {
1436
1854
  const { table = "orphan" } = record.xata;
1437
- return { table, record: initObject(this.db, this.links, table, record) };
1855
+ return { table, record: initObject(this.db, schemaTables, table, record) };
1438
1856
  });
1439
1857
  },
1440
1858
  byTable: async (query, options = {}) => {
1441
1859
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1860
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1442
1861
  return records.reduce((acc, record) => {
1443
1862
  const { table = "orphan" } = record.xata;
1444
1863
  const items = acc[table] ?? [];
1445
- const item = initObject(this.db, this.links, table, record);
1864
+ const item = initObject(this.db, schemaTables, table, record);
1446
1865
  return { ...acc, [table]: [...items, item] };
1447
1866
  }, {});
1448
1867
  }
1449
1868
  };
1450
1869
  }
1451
1870
  }
1871
+ _schemaTables = new WeakMap();
1452
1872
  _search = new WeakSet();
1453
1873
  search_fn = async function(query, options, getFetchProps) {
1454
1874
  const fetchProps = await getFetchProps();
1455
- const { tables, fuzziness } = options ?? {};
1875
+ const { tables, fuzziness, highlight } = options ?? {};
1456
1876
  const { records } = await searchBranch({
1457
1877
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1458
- body: { tables, query, fuzziness },
1878
+ body: { tables, query, fuzziness, highlight },
1459
1879
  ...fetchProps
1460
1880
  });
1461
1881
  return records;
1462
1882
  };
1883
+ _getSchemaTables = new WeakSet();
1884
+ getSchemaTables_fn = async function(getFetchProps) {
1885
+ if (__privateGet$1(this, _schemaTables))
1886
+ return __privateGet$1(this, _schemaTables);
1887
+ const fetchProps = await getFetchProps();
1888
+ const { schema } = await getBranchDetails({
1889
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1890
+ ...fetchProps
1891
+ });
1892
+ __privateSet$1(this, _schemaTables, schema.tables);
1893
+ return schema.tables;
1894
+ };
1463
1895
 
1464
1896
  const isBranchStrategyBuilder = (strategy) => {
1465
1897
  return typeof strategy === "function";
1466
1898
  };
1467
1899
 
1468
- const envBranchNames = [
1469
- "XATA_BRANCH",
1470
- "VERCEL_GIT_COMMIT_REF",
1471
- "CF_PAGES_BRANCH",
1472
- "BRANCH"
1473
- ];
1474
- const defaultBranch = "main";
1475
1900
  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;
1901
+ const { branch, envBranch } = getEnvironment();
1902
+ if (branch) {
1903
+ const details = await getDatabaseBranch(branch, options);
1904
+ if (details)
1905
+ return branch;
1906
+ console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
1907
+ }
1908
+ const gitBranch = envBranch || await getGitBranch();
1909
+ return resolveXataBranch(gitBranch, options);
1486
1910
  }
1487
1911
  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);
1912
+ const branch = await getCurrentBranchName(options);
1913
+ return getDatabaseBranch(branch, options);
1914
+ }
1915
+ async function resolveXataBranch(gitBranch, options) {
1916
+ const databaseURL = options?.databaseURL || getDatabaseURL();
1917
+ const apiKey = options?.apiKey || getAPIKey();
1918
+ if (!databaseURL)
1919
+ throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
1920
+ if (!apiKey)
1921
+ throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
1922
+ const [protocol, , host, , dbName] = databaseURL.split("/");
1923
+ const [workspace] = host.split(".");
1924
+ const { fallbackBranch } = getEnvironment();
1925
+ const { branch } = await resolveBranch({
1926
+ apiKey,
1927
+ apiUrl: databaseURL,
1928
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
1929
+ workspacesApiUrl: `${protocol}//${host}`,
1930
+ pathParams: { dbName, workspace },
1931
+ queryParams: { gitBranch, fallbackBranch }
1932
+ });
1933
+ return branch;
1498
1934
  }
1499
1935
  async function getDatabaseBranch(branch, options) {
1500
1936
  const databaseURL = options?.databaseURL || getDatabaseURL();
@@ -1512,10 +1948,7 @@ async function getDatabaseBranch(branch, options) {
1512
1948
  apiUrl: databaseURL,
1513
1949
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1514
1950
  workspacesApiUrl: `${protocol}//${host}`,
1515
- pathParams: {
1516
- dbBranchName,
1517
- workspace
1518
- }
1951
+ pathParams: { dbBranchName, workspace }
1519
1952
  });
1520
1953
  } catch (err) {
1521
1954
  if (isObject(err) && err.status === 404)
@@ -1523,21 +1956,10 @@ async function getDatabaseBranch(branch, options) {
1523
1956
  throw err;
1524
1957
  }
1525
1958
  }
1526
- function getBranchByEnvVariable() {
1527
- for (const name of envBranchNames) {
1528
- const value = getEnvVariable(name);
1529
- if (value) {
1530
- return value;
1531
- }
1532
- }
1533
- try {
1534
- return XATA_BRANCH;
1535
- } catch (err) {
1536
- }
1537
- }
1538
1959
  function getDatabaseURL() {
1539
1960
  try {
1540
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
1961
+ const { databaseURL } = getEnvironment();
1962
+ return databaseURL;
1541
1963
  } catch (err) {
1542
1964
  return void 0;
1543
1965
  }
@@ -1568,22 +1990,24 @@ var __privateMethod = (obj, member, method) => {
1568
1990
  const buildClient = (plugins) => {
1569
1991
  var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1570
1992
  return _a = class {
1571
- constructor(options = {}, links, tables) {
1993
+ constructor(options = {}, schemaTables) {
1572
1994
  __privateAdd(this, _parseOptions);
1573
1995
  __privateAdd(this, _getFetchProps);
1574
1996
  __privateAdd(this, _evaluateBranch);
1575
1997
  __privateAdd(this, _branch, void 0);
1576
1998
  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
- });
1999
+ const pluginOptions = {
2000
+ getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
2001
+ cache: safeOptions.cache
2002
+ };
2003
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2004
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1581
2005
  this.db = db;
1582
2006
  this.search = search;
1583
2007
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
1584
- if (!namespace)
2008
+ if (namespace === void 0)
1585
2009
  continue;
1586
- const result = namespace.build({ getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions) });
2010
+ const result = namespace.build(pluginOptions);
1587
2011
  if (result instanceof Promise) {
1588
2012
  void result.then((namespace2) => {
1589
2013
  this[key] = namespace2;
@@ -1597,11 +2021,12 @@ const buildClient = (plugins) => {
1597
2021
  const fetch = getFetchImplementation(options?.fetch);
1598
2022
  const databaseURL = options?.databaseURL || getDatabaseURL();
1599
2023
  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 });
2024
+ const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
2025
+ 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
2026
  if (!databaseURL || !apiKey) {
1602
2027
  throw new Error("Options databaseURL and apiKey are required");
1603
2028
  }
1604
- return { fetch, databaseURL, apiKey, branch };
2029
+ return { fetch, databaseURL, apiKey, branch, cache };
1605
2030
  }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
1606
2031
  fetch,
1607
2032
  apiKey,
@@ -1624,7 +2049,7 @@ const buildClient = (plugins) => {
1624
2049
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1625
2050
  if (__privateGet(this, _branch))
1626
2051
  return __privateGet(this, _branch);
1627
- if (!param)
2052
+ if (param === void 0)
1628
2053
  return void 0;
1629
2054
  const strategies = Array.isArray(param) ? [...param] : [param];
1630
2055
  const evaluateBranch = async (strategy) => {
@@ -1649,5 +2074,5 @@ class XataError extends Error {
1649
2074
  }
1650
2075
  }
1651
2076
 
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 };
2077
+ 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
2078
  //# sourceMappingURL=index.mjs.map