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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -2,6 +2,24 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
+ function _interopNamespace(e) {
6
+ if (e && e.__esModule) return e;
7
+ var n = Object.create(null);
8
+ if (e) {
9
+ Object.keys(e).forEach(function (k) {
10
+ if (k !== 'default') {
11
+ var d = Object.getOwnPropertyDescriptor(e, k);
12
+ Object.defineProperty(n, k, d.get ? d : {
13
+ enumerable: true,
14
+ get: function () { return e[k]; }
15
+ });
16
+ }
17
+ });
18
+ }
19
+ n["default"] = e;
20
+ return Object.freeze(n);
21
+ }
22
+
5
23
  function notEmpty(value) {
6
24
  return value !== null && value !== void 0;
7
25
  }
@@ -11,36 +29,98 @@ function compact(arr) {
11
29
  function isObject(value) {
12
30
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
13
31
  }
32
+ function isDefined(value) {
33
+ return value !== null && value !== void 0;
34
+ }
14
35
  function isString(value) {
15
- return value !== void 0 && value !== null && typeof value === "string";
36
+ return isDefined(value) && typeof value === "string";
37
+ }
38
+ function toBase64(value) {
39
+ try {
40
+ return btoa(value);
41
+ } catch (err) {
42
+ const buf = Buffer;
43
+ return buf.from(value).toString("base64");
44
+ }
16
45
  }
17
46
 
18
- function getEnvVariable(name) {
47
+ function getEnvironment() {
19
48
  try {
20
- if (isObject(process) && isString(process?.env?.[name])) {
21
- return process.env[name];
49
+ if (isObject(process) && isObject(process.env)) {
50
+ return {
51
+ apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
52
+ databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
53
+ branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
54
+ envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
55
+ fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
56
+ };
22
57
  }
23
58
  } catch (err) {
24
59
  }
25
60
  try {
26
- if (isObject(Deno) && isString(Deno?.env?.get(name))) {
27
- return Deno.env.get(name);
61
+ if (isObject(Deno) && isObject(Deno.env)) {
62
+ return {
63
+ apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
64
+ databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
65
+ branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
66
+ envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
67
+ fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
68
+ };
28
69
  }
29
70
  } catch (err) {
30
71
  }
72
+ return {
73
+ apiKey: getGlobalApiKey(),
74
+ databaseURL: getGlobalDatabaseURL(),
75
+ branch: getGlobalBranch(),
76
+ envBranch: void 0,
77
+ fallbackBranch: getGlobalFallbackBranch()
78
+ };
79
+ }
80
+ function getGlobalApiKey() {
81
+ try {
82
+ return XATA_API_KEY;
83
+ } catch (err) {
84
+ return void 0;
85
+ }
86
+ }
87
+ function getGlobalDatabaseURL() {
88
+ try {
89
+ return XATA_DATABASE_URL;
90
+ } catch (err) {
91
+ return void 0;
92
+ }
93
+ }
94
+ function getGlobalBranch() {
95
+ try {
96
+ return XATA_BRANCH;
97
+ } catch (err) {
98
+ return void 0;
99
+ }
100
+ }
101
+ function getGlobalFallbackBranch() {
102
+ try {
103
+ return XATA_FALLBACK_BRANCH;
104
+ } catch (err) {
105
+ return void 0;
106
+ }
31
107
  }
32
108
  async function getGitBranch() {
109
+ const cmd = ["git", "branch", "--show-current"];
110
+ const fullCmd = cmd.join(" ");
111
+ const nodeModule = ["child", "process"].join("_");
112
+ const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
33
113
  try {
34
- return require("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
114
+ if (typeof require === "function") {
115
+ return require(nodeModule).execSync(fullCmd, execOptions).trim();
116
+ }
117
+ const { execSync } = await (function (t) { return Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require(t)); }); })(nodeModule);
118
+ return execSync(fullCmd, execOptions).toString().trim();
35
119
  } catch (err) {
36
120
  }
37
121
  try {
38
122
  if (isObject(Deno)) {
39
- const process2 = Deno.run({
40
- cmd: ["git", "branch", "--show-current"],
41
- stdout: "piped",
42
- stderr: "piped"
43
- });
123
+ const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
44
124
  return new TextDecoder().decode(await process2.output()).trim();
45
125
  }
46
126
  } catch (err) {
@@ -49,7 +129,8 @@ async function getGitBranch() {
49
129
 
50
130
  function getAPIKey() {
51
131
  try {
52
- return getEnvVariable("XATA_API_KEY") ?? XATA_API_KEY;
132
+ const { apiKey } = getEnvironment();
133
+ return apiKey;
53
134
  } catch (err) {
54
135
  return void 0;
55
136
  }
@@ -64,16 +145,28 @@ function getFetchImplementation(userFetch) {
64
145
  return fetchImpl;
65
146
  }
66
147
 
67
- class FetcherError extends Error {
68
- constructor(status, data) {
148
+ const VERSION = "0.0.0-alpha.vf4789c2";
149
+
150
+ class ErrorWithCause extends Error {
151
+ constructor(message, options) {
152
+ super(message, options);
153
+ }
154
+ }
155
+ class FetcherError extends ErrorWithCause {
156
+ constructor(status, data, requestId) {
69
157
  super(getMessage(data));
70
158
  this.status = status;
71
159
  this.errors = isBulkError(data) ? data.errors : void 0;
160
+ this.requestId = requestId;
72
161
  if (data instanceof Error) {
73
162
  this.stack = data.stack;
74
163
  this.cause = data.cause;
75
164
  }
76
165
  }
166
+ toString() {
167
+ const error = super.toString();
168
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
169
+ }
77
170
  }
78
171
  function isBulkError(error) {
79
172
  return isObject(error) && Array.isArray(error.errors);
@@ -96,7 +189,12 @@ function getMessage(data) {
96
189
  }
97
190
 
98
191
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
99
- const query = new URLSearchParams(queryParams).toString();
192
+ const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
193
+ if (value === void 0 || value === null)
194
+ return acc;
195
+ return { ...acc, [key]: value };
196
+ }, {});
197
+ const query = new URLSearchParams(cleanQueryParams).toString();
100
198
  const queryString = query.length > 0 ? `?${query}` : "";
101
199
  return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
102
200
  };
@@ -136,6 +234,7 @@ async function fetch$1({
136
234
  body: body ? JSON.stringify(body) : void 0,
137
235
  headers: {
138
236
  "Content-Type": "application/json",
237
+ "User-Agent": `Xata client-ts/${VERSION}`,
139
238
  ...headers,
140
239
  ...hostHeader(fullUrl),
141
240
  Authorization: `Bearer ${apiKey}`
@@ -144,14 +243,15 @@ async function fetch$1({
144
243
  if (response.status === 204) {
145
244
  return {};
146
245
  }
246
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
147
247
  try {
148
248
  const jsonResponse = await response.json();
149
249
  if (response.ok) {
150
250
  return jsonResponse;
151
251
  }
152
- throw new FetcherError(response.status, jsonResponse);
252
+ throw new FetcherError(response.status, jsonResponse, requestId);
153
253
  } catch (error) {
154
- throw new FetcherError(response.status, error);
254
+ throw new FetcherError(response.status, error, requestId);
155
255
  }
156
256
  }
157
257
 
@@ -210,6 +310,7 @@ const removeWorkspaceMember = (variables) => fetch$1({
210
310
  ...variables
211
311
  });
212
312
  const inviteWorkspaceMember = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables });
313
+ const updateWorkspaceMemberInvite = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables });
213
314
  const cancelWorkspaceMemberInvite = (variables) => fetch$1({
214
315
  url: "/workspaces/{workspaceId}/invites/{inviteId}",
215
316
  method: "delete",
@@ -245,6 +346,14 @@ const deleteDatabase = (variables) => fetch$1({
245
346
  method: "delete",
246
347
  ...variables
247
348
  });
349
+ const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
350
+ const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
351
+ const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
352
+ const resolveBranch = (variables) => fetch$1({
353
+ url: "/dbs/{dbName}/resolveBranch",
354
+ method: "get",
355
+ ...variables
356
+ });
248
357
  const getBranchDetails = (variables) => fetch$1({
249
358
  url: "/db/{dbBranchName}",
250
359
  method: "get",
@@ -352,6 +461,11 @@ const queryTable = (variables) => fetch$1({
352
461
  method: "post",
353
462
  ...variables
354
463
  });
464
+ const searchTable = (variables) => fetch$1({
465
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
466
+ method: "post",
467
+ ...variables
468
+ });
355
469
  const searchBranch = (variables) => fetch$1({
356
470
  url: "/db/{dbBranchName}/search",
357
471
  method: "post",
@@ -369,11 +483,20 @@ const operationsByTag = {
369
483
  updateWorkspaceMemberRole,
370
484
  removeWorkspaceMember,
371
485
  inviteWorkspaceMember,
486
+ updateWorkspaceMemberInvite,
372
487
  cancelWorkspaceMemberInvite,
373
488
  resendWorkspaceMemberInvite,
374
489
  acceptWorkspaceMemberInvite
375
490
  },
376
- database: { getDatabaseList, createDatabase, deleteDatabase },
491
+ database: {
492
+ getDatabaseList,
493
+ createDatabase,
494
+ deleteDatabase,
495
+ getGitBranchesMapping,
496
+ addGitBranchesEntry,
497
+ removeGitBranchesEntry,
498
+ resolveBranch
499
+ },
377
500
  branch: {
378
501
  getBranchList,
379
502
  getBranchDetails,
@@ -407,6 +530,7 @@ const operationsByTag = {
407
530
  getRecord,
408
531
  bulkInsertTableRecords,
409
532
  queryTable,
533
+ searchTable,
410
534
  searchBranch
411
535
  }
412
536
  };
@@ -436,35 +560,35 @@ function isValidBuilder(builder) {
436
560
  return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
437
561
  }
438
562
 
439
- var __accessCheck$6 = (obj, member, msg) => {
563
+ var __accessCheck$7 = (obj, member, msg) => {
440
564
  if (!member.has(obj))
441
565
  throw TypeError("Cannot " + msg);
442
566
  };
443
- var __privateGet$5 = (obj, member, getter) => {
444
- __accessCheck$6(obj, member, "read from private field");
567
+ var __privateGet$7 = (obj, member, getter) => {
568
+ __accessCheck$7(obj, member, "read from private field");
445
569
  return getter ? getter.call(obj) : member.get(obj);
446
570
  };
447
- var __privateAdd$6 = (obj, member, value) => {
571
+ var __privateAdd$7 = (obj, member, value) => {
448
572
  if (member.has(obj))
449
573
  throw TypeError("Cannot add the same private member more than once");
450
574
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
451
575
  };
452
- var __privateSet$4 = (obj, member, value, setter) => {
453
- __accessCheck$6(obj, member, "write to private field");
576
+ var __privateSet$7 = (obj, member, value, setter) => {
577
+ __accessCheck$7(obj, member, "write to private field");
454
578
  setter ? setter.call(obj, value) : member.set(obj, value);
455
579
  return value;
456
580
  };
457
581
  var _extraProps, _namespaces;
458
582
  class XataApiClient {
459
583
  constructor(options = {}) {
460
- __privateAdd$6(this, _extraProps, void 0);
461
- __privateAdd$6(this, _namespaces, {});
584
+ __privateAdd$7(this, _extraProps, void 0);
585
+ __privateAdd$7(this, _namespaces, {});
462
586
  const provider = options.host ?? "production";
463
587
  const apiKey = options?.apiKey ?? getAPIKey();
464
588
  if (!apiKey) {
465
589
  throw new Error("Could not resolve a valid apiKey");
466
590
  }
467
- __privateSet$4(this, _extraProps, {
591
+ __privateSet$7(this, _extraProps, {
468
592
  apiUrl: getHostUrl(provider, "main"),
469
593
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
470
594
  fetchImpl: getFetchImplementation(options.fetch),
@@ -472,34 +596,34 @@ class XataApiClient {
472
596
  });
473
597
  }
474
598
  get user() {
475
- if (!__privateGet$5(this, _namespaces).user)
476
- __privateGet$5(this, _namespaces).user = new UserApi(__privateGet$5(this, _extraProps));
477
- return __privateGet$5(this, _namespaces).user;
599
+ if (!__privateGet$7(this, _namespaces).user)
600
+ __privateGet$7(this, _namespaces).user = new UserApi(__privateGet$7(this, _extraProps));
601
+ return __privateGet$7(this, _namespaces).user;
478
602
  }
479
603
  get workspaces() {
480
- if (!__privateGet$5(this, _namespaces).workspaces)
481
- __privateGet$5(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$5(this, _extraProps));
482
- return __privateGet$5(this, _namespaces).workspaces;
604
+ if (!__privateGet$7(this, _namespaces).workspaces)
605
+ __privateGet$7(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$7(this, _extraProps));
606
+ return __privateGet$7(this, _namespaces).workspaces;
483
607
  }
484
608
  get databases() {
485
- if (!__privateGet$5(this, _namespaces).databases)
486
- __privateGet$5(this, _namespaces).databases = new DatabaseApi(__privateGet$5(this, _extraProps));
487
- return __privateGet$5(this, _namespaces).databases;
609
+ if (!__privateGet$7(this, _namespaces).databases)
610
+ __privateGet$7(this, _namespaces).databases = new DatabaseApi(__privateGet$7(this, _extraProps));
611
+ return __privateGet$7(this, _namespaces).databases;
488
612
  }
489
613
  get branches() {
490
- if (!__privateGet$5(this, _namespaces).branches)
491
- __privateGet$5(this, _namespaces).branches = new BranchApi(__privateGet$5(this, _extraProps));
492
- return __privateGet$5(this, _namespaces).branches;
614
+ if (!__privateGet$7(this, _namespaces).branches)
615
+ __privateGet$7(this, _namespaces).branches = new BranchApi(__privateGet$7(this, _extraProps));
616
+ return __privateGet$7(this, _namespaces).branches;
493
617
  }
494
618
  get tables() {
495
- if (!__privateGet$5(this, _namespaces).tables)
496
- __privateGet$5(this, _namespaces).tables = new TableApi(__privateGet$5(this, _extraProps));
497
- return __privateGet$5(this, _namespaces).tables;
619
+ if (!__privateGet$7(this, _namespaces).tables)
620
+ __privateGet$7(this, _namespaces).tables = new TableApi(__privateGet$7(this, _extraProps));
621
+ return __privateGet$7(this, _namespaces).tables;
498
622
  }
499
623
  get records() {
500
- if (!__privateGet$5(this, _namespaces).records)
501
- __privateGet$5(this, _namespaces).records = new RecordsApi(__privateGet$5(this, _extraProps));
502
- return __privateGet$5(this, _namespaces).records;
624
+ if (!__privateGet$7(this, _namespaces).records)
625
+ __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
626
+ return __privateGet$7(this, _namespaces).records;
503
627
  }
504
628
  }
505
629
  _extraProps = new WeakMap();
@@ -591,6 +715,13 @@ class WorkspaceApi {
591
715
  ...this.extraProps
592
716
  });
593
717
  }
718
+ updateWorkspaceMemberInvite(workspaceId, inviteId, role) {
719
+ return operationsByTag.workspaces.updateWorkspaceMemberInvite({
720
+ pathParams: { workspaceId, inviteId },
721
+ body: { role },
722
+ ...this.extraProps
723
+ });
724
+ }
594
725
  cancelWorkspaceMemberInvite(workspaceId, inviteId) {
595
726
  return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
596
727
  pathParams: { workspaceId, inviteId },
@@ -633,6 +764,33 @@ class DatabaseApi {
633
764
  ...this.extraProps
634
765
  });
635
766
  }
767
+ getGitBranchesMapping(workspace, dbName) {
768
+ return operationsByTag.database.getGitBranchesMapping({
769
+ pathParams: { workspace, dbName },
770
+ ...this.extraProps
771
+ });
772
+ }
773
+ addGitBranchesEntry(workspace, dbName, body) {
774
+ return operationsByTag.database.addGitBranchesEntry({
775
+ pathParams: { workspace, dbName },
776
+ body,
777
+ ...this.extraProps
778
+ });
779
+ }
780
+ removeGitBranchesEntry(workspace, dbName, gitBranch) {
781
+ return operationsByTag.database.removeGitBranchesEntry({
782
+ pathParams: { workspace, dbName },
783
+ queryParams: { gitBranch },
784
+ ...this.extraProps
785
+ });
786
+ }
787
+ resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
788
+ return operationsByTag.database.resolveBranch({
789
+ pathParams: { workspace, dbName },
790
+ queryParams: { gitBranch, fallbackBranch },
791
+ ...this.extraProps
792
+ });
793
+ }
636
794
  }
637
795
  class BranchApi {
638
796
  constructor(extraProps) {
@@ -650,10 +808,10 @@ class BranchApi {
650
808
  ...this.extraProps
651
809
  });
652
810
  }
653
- createBranch(workspace, database, branch, from = "", options = {}) {
811
+ createBranch(workspace, database, branch, from, options = {}) {
654
812
  return operationsByTag.branch.createBranch({
655
813
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
656
- queryParams: { from },
814
+ queryParams: isString(from) ? { from } : void 0,
657
815
  body: options,
658
816
  ...this.extraProps
659
817
  });
@@ -835,6 +993,13 @@ class RecordsApi {
835
993
  ...this.extraProps
836
994
  });
837
995
  }
996
+ searchTable(workspace, database, branch, tableName, query) {
997
+ return operationsByTag.records.searchTable({
998
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
999
+ body: query,
1000
+ ...this.extraProps
1001
+ });
1002
+ }
838
1003
  searchBranch(workspace, database, branch, query) {
839
1004
  return operationsByTag.records.searchBranch({
840
1005
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -854,43 +1019,43 @@ class XataApiPlugin {
854
1019
  class XataPlugin {
855
1020
  }
856
1021
 
857
- var __accessCheck$5 = (obj, member, msg) => {
1022
+ var __accessCheck$6 = (obj, member, msg) => {
858
1023
  if (!member.has(obj))
859
1024
  throw TypeError("Cannot " + msg);
860
1025
  };
861
- var __privateGet$4 = (obj, member, getter) => {
862
- __accessCheck$5(obj, member, "read from private field");
1026
+ var __privateGet$6 = (obj, member, getter) => {
1027
+ __accessCheck$6(obj, member, "read from private field");
863
1028
  return getter ? getter.call(obj) : member.get(obj);
864
1029
  };
865
- var __privateAdd$5 = (obj, member, value) => {
1030
+ var __privateAdd$6 = (obj, member, value) => {
866
1031
  if (member.has(obj))
867
1032
  throw TypeError("Cannot add the same private member more than once");
868
1033
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
869
1034
  };
870
- var __privateSet$3 = (obj, member, value, setter) => {
871
- __accessCheck$5(obj, member, "write to private field");
1035
+ var __privateSet$6 = (obj, member, value, setter) => {
1036
+ __accessCheck$6(obj, member, "write to private field");
872
1037
  setter ? setter.call(obj, value) : member.set(obj, value);
873
1038
  return value;
874
1039
  };
875
- var _query;
1040
+ var _query, _page;
876
1041
  class Page {
877
1042
  constructor(query, meta, records = []) {
878
- __privateAdd$5(this, _query, void 0);
879
- __privateSet$3(this, _query, query);
1043
+ __privateAdd$6(this, _query, void 0);
1044
+ __privateSet$6(this, _query, query);
880
1045
  this.meta = meta;
881
- this.records = records;
1046
+ this.records = new RecordArray(this, records);
882
1047
  }
883
1048
  async nextPage(size, offset) {
884
- return __privateGet$4(this, _query).getPaginated({ page: { size, offset, after: this.meta.page.cursor } });
1049
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
885
1050
  }
886
1051
  async previousPage(size, offset) {
887
- return __privateGet$4(this, _query).getPaginated({ page: { size, offset, before: this.meta.page.cursor } });
1052
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
888
1053
  }
889
1054
  async firstPage(size, offset) {
890
- return __privateGet$4(this, _query).getPaginated({ page: { size, offset, first: this.meta.page.cursor } });
1055
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
891
1056
  }
892
1057
  async lastPage(size, offset) {
893
- return __privateGet$4(this, _query).getPaginated({ page: { size, offset, last: this.meta.page.cursor } });
1058
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
894
1059
  }
895
1060
  hasNextPage() {
896
1061
  return this.meta.page.more;
@@ -898,50 +1063,99 @@ class Page {
898
1063
  }
899
1064
  _query = new WeakMap();
900
1065
  const PAGINATION_MAX_SIZE = 200;
901
- const PAGINATION_DEFAULT_SIZE = 200;
1066
+ const PAGINATION_DEFAULT_SIZE = 20;
902
1067
  const PAGINATION_MAX_OFFSET = 800;
903
1068
  const PAGINATION_DEFAULT_OFFSET = 0;
1069
+ function isCursorPaginationOptions(options) {
1070
+ return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
1071
+ }
1072
+ const _RecordArray = class extends Array {
1073
+ constructor(...args) {
1074
+ super(..._RecordArray.parseConstructorParams(...args));
1075
+ __privateAdd$6(this, _page, void 0);
1076
+ __privateSet$6(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
1077
+ }
1078
+ static parseConstructorParams(...args) {
1079
+ if (args.length === 1 && typeof args[0] === "number") {
1080
+ return new Array(args[0]);
1081
+ }
1082
+ if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
1083
+ const result = args[1] ?? args[0].records ?? [];
1084
+ return new Array(...result);
1085
+ }
1086
+ return new Array(...args);
1087
+ }
1088
+ toArray() {
1089
+ return new Array(...this);
1090
+ }
1091
+ map(callbackfn, thisArg) {
1092
+ return this.toArray().map(callbackfn, thisArg);
1093
+ }
1094
+ async nextPage(size, offset) {
1095
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1096
+ return new _RecordArray(newPage);
1097
+ }
1098
+ async previousPage(size, offset) {
1099
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1100
+ return new _RecordArray(newPage);
1101
+ }
1102
+ async firstPage(size, offset) {
1103
+ const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1104
+ return new _RecordArray(newPage);
1105
+ }
1106
+ async lastPage(size, offset) {
1107
+ const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1108
+ return new _RecordArray(newPage);
1109
+ }
1110
+ hasNextPage() {
1111
+ return __privateGet$6(this, _page).meta.page.more;
1112
+ }
1113
+ };
1114
+ let RecordArray = _RecordArray;
1115
+ _page = new WeakMap();
904
1116
 
905
- var __accessCheck$4 = (obj, member, msg) => {
1117
+ var __accessCheck$5 = (obj, member, msg) => {
906
1118
  if (!member.has(obj))
907
1119
  throw TypeError("Cannot " + msg);
908
1120
  };
909
- var __privateGet$3 = (obj, member, getter) => {
910
- __accessCheck$4(obj, member, "read from private field");
1121
+ var __privateGet$5 = (obj, member, getter) => {
1122
+ __accessCheck$5(obj, member, "read from private field");
911
1123
  return getter ? getter.call(obj) : member.get(obj);
912
1124
  };
913
- var __privateAdd$4 = (obj, member, value) => {
1125
+ var __privateAdd$5 = (obj, member, value) => {
914
1126
  if (member.has(obj))
915
1127
  throw TypeError("Cannot add the same private member more than once");
916
1128
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
917
1129
  };
918
- var __privateSet$2 = (obj, member, value, setter) => {
919
- __accessCheck$4(obj, member, "write to private field");
1130
+ var __privateSet$5 = (obj, member, value, setter) => {
1131
+ __accessCheck$5(obj, member, "write to private field");
920
1132
  setter ? setter.call(obj, value) : member.set(obj, value);
921
1133
  return value;
922
1134
  };
923
1135
  var _table$1, _repository, _data;
924
1136
  const _Query = class {
925
- constructor(repository, table, data, parent) {
926
- __privateAdd$4(this, _table$1, void 0);
927
- __privateAdd$4(this, _repository, void 0);
928
- __privateAdd$4(this, _data, { filter: {} });
1137
+ constructor(repository, table, data, rawParent) {
1138
+ __privateAdd$5(this, _table$1, void 0);
1139
+ __privateAdd$5(this, _repository, void 0);
1140
+ __privateAdd$5(this, _data, { filter: {} });
929
1141
  this.meta = { page: { cursor: "start", more: true } };
930
- this.records = [];
931
- __privateSet$2(this, _table$1, table);
1142
+ this.records = new RecordArray(this, []);
1143
+ __privateSet$5(this, _table$1, table);
932
1144
  if (repository) {
933
- __privateSet$2(this, _repository, repository);
1145
+ __privateSet$5(this, _repository, repository);
934
1146
  } else {
935
- __privateSet$2(this, _repository, this);
1147
+ __privateSet$5(this, _repository, this);
936
1148
  }
937
- __privateGet$3(this, _data).filter = data.filter ?? parent?.filter ?? {};
938
- __privateGet$3(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
939
- __privateGet$3(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
940
- __privateGet$3(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
941
- __privateGet$3(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
942
- __privateGet$3(this, _data).sort = data.sort ?? parent?.sort;
943
- __privateGet$3(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
944
- __privateGet$3(this, _data).page = data.page ?? parent?.page;
1149
+ const parent = cleanParent(data, rawParent);
1150
+ __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
1151
+ __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
1152
+ __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
1153
+ __privateGet$5(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
1154
+ __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1155
+ __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1156
+ __privateGet$5(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
1157
+ __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1158
+ __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
945
1159
  this.any = this.any.bind(this);
946
1160
  this.all = this.all.bind(this);
947
1161
  this.not = this.not.bind(this);
@@ -952,75 +1166,88 @@ const _Query = class {
952
1166
  Object.defineProperty(this, "repository", { enumerable: false });
953
1167
  }
954
1168
  getQueryOptions() {
955
- return __privateGet$3(this, _data);
1169
+ return __privateGet$5(this, _data);
1170
+ }
1171
+ key() {
1172
+ const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$5(this, _data);
1173
+ const key = JSON.stringify({ columns, filter, sort, pagination });
1174
+ return toBase64(key);
956
1175
  }
957
1176
  any(...queries) {
958
1177
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
959
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $any } }, __privateGet$3(this, _data));
1178
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
960
1179
  }
961
1180
  all(...queries) {
962
1181
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
963
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $all } }, __privateGet$3(this, _data));
1182
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
964
1183
  }
965
1184
  not(...queries) {
966
1185
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
967
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $not } }, __privateGet$3(this, _data));
1186
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
968
1187
  }
969
1188
  none(...queries) {
970
1189
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
971
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $none } }, __privateGet$3(this, _data));
1190
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
972
1191
  }
973
1192
  filter(a, b) {
974
1193
  if (arguments.length === 1) {
975
1194
  const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
976
- const $all = compact([__privateGet$3(this, _data).filter?.$all].flat().concat(constraints));
977
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $all } }, __privateGet$3(this, _data));
1195
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1196
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
978
1197
  } else {
979
- const $all = compact([__privateGet$3(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
980
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $all } }, __privateGet$3(this, _data));
1198
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
1199
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
981
1200
  }
982
1201
  }
983
1202
  sort(column, direction) {
984
- const originalSort = [__privateGet$3(this, _data).sort ?? []].flat();
1203
+ const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
985
1204
  const sort = [...originalSort, { column, direction }];
986
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { sort }, __privateGet$3(this, _data));
1205
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
987
1206
  }
988
1207
  select(columns) {
989
- return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { columns }, __privateGet$3(this, _data));
1208
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { columns }, __privateGet$5(this, _data));
990
1209
  }
991
1210
  getPaginated(options = {}) {
992
- const query = new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), options, __privateGet$3(this, _data));
993
- return __privateGet$3(this, _repository).query(query);
1211
+ const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
1212
+ return __privateGet$5(this, _repository).query(query);
994
1213
  }
995
1214
  async *[Symbol.asyncIterator]() {
996
- for await (const [record] of this.getIterator(1)) {
1215
+ for await (const [record] of this.getIterator({ batchSize: 1 })) {
997
1216
  yield record;
998
1217
  }
999
1218
  }
1000
- async *getIterator(chunk, options = {}) {
1001
- let offset = 0;
1002
- let end = false;
1003
- while (!end) {
1004
- const { records, meta } = await this.getPaginated({ ...options, page: { size: chunk, offset } });
1005
- yield records;
1006
- offset += chunk;
1007
- end = !meta.page.more;
1219
+ async *getIterator(options = {}) {
1220
+ const { batchSize = 1 } = options;
1221
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
1222
+ let more = page.hasNextPage();
1223
+ yield page.records;
1224
+ while (more) {
1225
+ page = await page.nextPage();
1226
+ more = page.hasNextPage();
1227
+ yield page.records;
1008
1228
  }
1009
1229
  }
1010
1230
  async getMany(options = {}) {
1011
- const { records } = await this.getPaginated(options);
1012
- return records;
1231
+ const page = await this.getPaginated(options);
1232
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1233
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1234
+ }
1235
+ return page.records;
1013
1236
  }
1014
- async getAll(chunk = PAGINATION_MAX_SIZE, options = {}) {
1237
+ async getAll(options = {}) {
1238
+ const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
1015
1239
  const results = [];
1016
- for await (const page of this.getIterator(chunk, options)) {
1240
+ for await (const page of this.getIterator({ ...rest, batchSize })) {
1017
1241
  results.push(...page);
1018
1242
  }
1019
1243
  return results;
1020
1244
  }
1021
- async getOne(options = {}) {
1022
- const records = await this.getMany({ ...options, page: { size: 1 } });
1023
- return records[0] || null;
1245
+ async getFirst(options = {}) {
1246
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1247
+ return records[0] ?? null;
1248
+ }
1249
+ cache(ttl) {
1250
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1024
1251
  }
1025
1252
  nextPage(size, offset) {
1026
1253
  return this.firstPage(size, offset);
@@ -1029,10 +1256,10 @@ const _Query = class {
1029
1256
  return this.firstPage(size, offset);
1030
1257
  }
1031
1258
  firstPage(size, offset) {
1032
- return this.getPaginated({ page: { size, offset } });
1259
+ return this.getPaginated({ pagination: { size, offset } });
1033
1260
  }
1034
1261
  lastPage(size, offset) {
1035
- return this.getPaginated({ page: { size, offset, before: "end" } });
1262
+ return this.getPaginated({ pagination: { size, offset, before: "end" } });
1036
1263
  }
1037
1264
  hasNextPage() {
1038
1265
  return this.meta.page.more;
@@ -1042,12 +1269,20 @@ let Query = _Query;
1042
1269
  _table$1 = new WeakMap();
1043
1270
  _repository = new WeakMap();
1044
1271
  _data = new WeakMap();
1272
+ function cleanParent(data, parent) {
1273
+ if (isCursorPaginationOptions(data.pagination)) {
1274
+ return { ...parent, sorting: void 0, filter: void 0 };
1275
+ }
1276
+ return parent;
1277
+ }
1045
1278
 
1046
1279
  function isIdentifiable(x) {
1047
1280
  return isObject(x) && isString(x?.id);
1048
1281
  }
1049
1282
  function isXataRecord(x) {
1050
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1283
+ const record = x;
1284
+ const metadata = record?.getMetadata();
1285
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1051
1286
  }
1052
1287
 
1053
1288
  function isSortFilterString(value) {
@@ -1073,169 +1308,232 @@ function buildSortFilter(filter) {
1073
1308
  }
1074
1309
  }
1075
1310
 
1076
- var __accessCheck$3 = (obj, member, msg) => {
1311
+ var __accessCheck$4 = (obj, member, msg) => {
1077
1312
  if (!member.has(obj))
1078
1313
  throw TypeError("Cannot " + msg);
1079
1314
  };
1080
- var __privateGet$2 = (obj, member, getter) => {
1081
- __accessCheck$3(obj, member, "read from private field");
1315
+ var __privateGet$4 = (obj, member, getter) => {
1316
+ __accessCheck$4(obj, member, "read from private field");
1082
1317
  return getter ? getter.call(obj) : member.get(obj);
1083
1318
  };
1084
- var __privateAdd$3 = (obj, member, value) => {
1319
+ var __privateAdd$4 = (obj, member, value) => {
1085
1320
  if (member.has(obj))
1086
1321
  throw TypeError("Cannot add the same private member more than once");
1087
1322
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1088
1323
  };
1089
- var __privateSet$1 = (obj, member, value, setter) => {
1090
- __accessCheck$3(obj, member, "write to private field");
1324
+ var __privateSet$4 = (obj, member, value, setter) => {
1325
+ __accessCheck$4(obj, member, "write to private field");
1091
1326
  setter ? setter.call(obj, value) : member.set(obj, value);
1092
1327
  return value;
1093
1328
  };
1094
1329
  var __privateMethod$2 = (obj, member, method) => {
1095
- __accessCheck$3(obj, member, "access private method");
1330
+ __accessCheck$4(obj, member, "access private method");
1096
1331
  return method;
1097
1332
  };
1098
- var _table, _links, _getFetchProps, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn;
1333
+ 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;
1099
1334
  class Repository extends Query {
1100
1335
  }
1101
1336
  class RestRepository extends Query {
1102
1337
  constructor(options) {
1103
1338
  super(null, options.table, {});
1104
- __privateAdd$3(this, _insertRecordWithoutId);
1105
- __privateAdd$3(this, _insertRecordWithId);
1106
- __privateAdd$3(this, _bulkInsertTableRecords);
1107
- __privateAdd$3(this, _updateRecordWithID);
1108
- __privateAdd$3(this, _upsertRecordWithID);
1109
- __privateAdd$3(this, _deleteRecord);
1110
- __privateAdd$3(this, _table, void 0);
1111
- __privateAdd$3(this, _links, void 0);
1112
- __privateAdd$3(this, _getFetchProps, void 0);
1113
- __privateSet$1(this, _table, options.table);
1114
- __privateSet$1(this, _links, options.links ?? {});
1115
- __privateSet$1(this, _getFetchProps, options.getFetchProps);
1339
+ __privateAdd$4(this, _insertRecordWithoutId);
1340
+ __privateAdd$4(this, _insertRecordWithId);
1341
+ __privateAdd$4(this, _bulkInsertTableRecords);
1342
+ __privateAdd$4(this, _updateRecordWithID);
1343
+ __privateAdd$4(this, _upsertRecordWithID);
1344
+ __privateAdd$4(this, _deleteRecord);
1345
+ __privateAdd$4(this, _invalidateCache);
1346
+ __privateAdd$4(this, _setCacheRecord);
1347
+ __privateAdd$4(this, _getCacheRecord);
1348
+ __privateAdd$4(this, _setCacheQuery);
1349
+ __privateAdd$4(this, _getCacheQuery);
1350
+ __privateAdd$4(this, _getSchemaTables$1);
1351
+ __privateAdd$4(this, _table, void 0);
1352
+ __privateAdd$4(this, _getFetchProps, void 0);
1353
+ __privateAdd$4(this, _cache, void 0);
1354
+ __privateAdd$4(this, _schemaTables$2, void 0);
1355
+ __privateSet$4(this, _table, options.table);
1356
+ __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1116
1357
  this.db = options.db;
1358
+ __privateSet$4(this, _cache, options.pluginOptions.cache);
1359
+ __privateSet$4(this, _schemaTables$2, options.schemaTables);
1117
1360
  }
1118
1361
  async create(a, b) {
1119
1362
  if (Array.isArray(a)) {
1120
- return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1363
+ if (a.length === 0)
1364
+ return [];
1365
+ const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1366
+ await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1367
+ return records;
1121
1368
  }
1122
1369
  if (isString(a) && isObject(b)) {
1123
1370
  if (a === "")
1124
1371
  throw new Error("The id can't be empty");
1125
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1372
+ const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1373
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1374
+ return record;
1126
1375
  }
1127
1376
  if (isObject(a) && isString(a.id)) {
1128
1377
  if (a.id === "")
1129
1378
  throw new Error("The id can't be empty");
1130
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1379
+ const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1380
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1381
+ return record;
1131
1382
  }
1132
1383
  if (isObject(a)) {
1133
- return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1384
+ const record = await __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1385
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1386
+ return record;
1134
1387
  }
1135
1388
  throw new Error("Invalid arguments for create method");
1136
1389
  }
1137
- async read(recordId) {
1138
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1139
- try {
1140
- const response = await getRecord({
1141
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table), recordId },
1142
- ...fetchProps
1143
- });
1144
- return initObject(this.db, __privateGet$2(this, _links), __privateGet$2(this, _table), response);
1145
- } catch (e) {
1146
- if (isObject(e) && e.status === 404) {
1147
- return null;
1390
+ async read(a) {
1391
+ if (Array.isArray(a)) {
1392
+ if (a.length === 0)
1393
+ return [];
1394
+ const ids = a.map((item) => isString(item) ? item : item.id).filter((id2) => isString(id2));
1395
+ return this.getAll({ filter: { id: { $any: ids } } });
1396
+ }
1397
+ const id = isString(a) ? a : a.id;
1398
+ if (isString(id)) {
1399
+ const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, id);
1400
+ if (cacheRecord)
1401
+ return cacheRecord;
1402
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1403
+ try {
1404
+ const response = await getRecord({
1405
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: id },
1406
+ ...fetchProps
1407
+ });
1408
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1409
+ return initObject(this.db, schemaTables, __privateGet$4(this, _table), response);
1410
+ } catch (e) {
1411
+ if (isObject(e) && e.status === 404) {
1412
+ return null;
1413
+ }
1414
+ throw e;
1148
1415
  }
1149
- throw e;
1150
1416
  }
1151
1417
  }
1152
1418
  async update(a, b) {
1153
1419
  if (Array.isArray(a)) {
1420
+ if (a.length === 0)
1421
+ return [];
1154
1422
  if (a.length > 100) {
1155
1423
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1156
1424
  }
1157
1425
  return Promise.all(a.map((object) => this.update(object)));
1158
1426
  }
1159
1427
  if (isString(a) && isObject(b)) {
1160
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1428
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1429
+ const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1430
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1431
+ return record;
1161
1432
  }
1162
1433
  if (isObject(a) && isString(a.id)) {
1163
- return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1434
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1435
+ const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1436
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1437
+ return record;
1164
1438
  }
1165
1439
  throw new Error("Invalid arguments for update method");
1166
1440
  }
1167
1441
  async createOrUpdate(a, b) {
1168
1442
  if (Array.isArray(a)) {
1443
+ if (a.length === 0)
1444
+ return [];
1169
1445
  if (a.length > 100) {
1170
1446
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1171
1447
  }
1172
1448
  return Promise.all(a.map((object) => this.createOrUpdate(object)));
1173
1449
  }
1174
1450
  if (isString(a) && isObject(b)) {
1175
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1451
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1452
+ const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1453
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1454
+ return record;
1176
1455
  }
1177
1456
  if (isObject(a) && isString(a.id)) {
1178
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1457
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1458
+ const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1459
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1460
+ return record;
1179
1461
  }
1180
1462
  throw new Error("Invalid arguments for createOrUpdate method");
1181
1463
  }
1182
- async delete(recordId) {
1183
- if (Array.isArray(recordId)) {
1184
- if (recordId.length > 100) {
1464
+ async delete(a) {
1465
+ if (Array.isArray(a)) {
1466
+ if (a.length === 0)
1467
+ return;
1468
+ if (a.length > 100) {
1185
1469
  console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1186
1470
  }
1187
- await Promise.all(recordId.map((id) => this.delete(id)));
1471
+ await Promise.all(a.map((id) => this.delete(id)));
1188
1472
  return;
1189
1473
  }
1190
- if (isString(recordId)) {
1191
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, recordId);
1474
+ if (isString(a)) {
1475
+ await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1476
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1192
1477
  return;
1193
1478
  }
1194
- if (isObject(recordId) && isString(recordId.id)) {
1195
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, recordId.id);
1479
+ if (isObject(a) && isString(a.id)) {
1480
+ await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1481
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1196
1482
  return;
1197
1483
  }
1198
1484
  throw new Error("Invalid arguments for delete method");
1199
1485
  }
1200
1486
  async search(query, options = {}) {
1201
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1202
- const { records } = await searchBranch({
1203
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1204
- body: { tables: [__privateGet$2(this, _table)], query, fuzziness: options.fuzziness },
1487
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1488
+ const { records } = await searchTable({
1489
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1490
+ body: {
1491
+ query,
1492
+ fuzziness: options.fuzziness,
1493
+ highlight: options.highlight,
1494
+ filter: options.filter
1495
+ },
1205
1496
  ...fetchProps
1206
1497
  });
1207
- return records.map((item) => initObject(this.db, __privateGet$2(this, _links), __privateGet$2(this, _table), item));
1498
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1499
+ return records.map((item) => initObject(this.db, schemaTables, __privateGet$4(this, _table), item));
1208
1500
  }
1209
1501
  async query(query) {
1502
+ const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1503
+ if (cacheQuery)
1504
+ return new Page(query, cacheQuery.meta, cacheQuery.records);
1210
1505
  const data = query.getQueryOptions();
1211
1506
  const body = {
1212
1507
  filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1213
- sort: data.sort ? buildSortFilter(data.sort) : void 0,
1214
- page: data.page,
1508
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1509
+ page: data.pagination,
1215
1510
  columns: data.columns
1216
1511
  };
1217
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1512
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1218
1513
  const { meta, records: objects } = await queryTable({
1219
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table) },
1514
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1220
1515
  body,
1221
1516
  ...fetchProps
1222
1517
  });
1223
- const records = objects.map((record) => initObject(this.db, __privateGet$2(this, _links), __privateGet$2(this, _table), record));
1518
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1519
+ const records = objects.map((record) => initObject(this.db, schemaTables, __privateGet$4(this, _table), record));
1520
+ await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1224
1521
  return new Page(query, meta, records);
1225
1522
  }
1226
1523
  }
1227
1524
  _table = new WeakMap();
1228
- _links = new WeakMap();
1229
1525
  _getFetchProps = new WeakMap();
1526
+ _cache = new WeakMap();
1527
+ _schemaTables$2 = new WeakMap();
1230
1528
  _insertRecordWithoutId = new WeakSet();
1231
1529
  insertRecordWithoutId_fn = async function(object) {
1232
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1530
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1233
1531
  const record = transformObjectLinks(object);
1234
1532
  const response = await insertRecord({
1235
1533
  pathParams: {
1236
1534
  workspace: "{workspaceId}",
1237
1535
  dbBranchName: "{dbBranch}",
1238
- tableName: __privateGet$2(this, _table)
1536
+ tableName: __privateGet$4(this, _table)
1239
1537
  },
1240
1538
  body: record,
1241
1539
  ...fetchProps
@@ -1248,13 +1546,13 @@ insertRecordWithoutId_fn = async function(object) {
1248
1546
  };
1249
1547
  _insertRecordWithId = new WeakSet();
1250
1548
  insertRecordWithId_fn = async function(recordId, object) {
1251
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1549
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1252
1550
  const record = transformObjectLinks(object);
1253
1551
  const response = await insertRecordWithID({
1254
1552
  pathParams: {
1255
1553
  workspace: "{workspaceId}",
1256
1554
  dbBranchName: "{dbBranch}",
1257
- tableName: __privateGet$2(this, _table),
1555
+ tableName: __privateGet$4(this, _table),
1258
1556
  recordId
1259
1557
  },
1260
1558
  body: record,
@@ -1269,25 +1567,29 @@ insertRecordWithId_fn = async function(recordId, object) {
1269
1567
  };
1270
1568
  _bulkInsertTableRecords = new WeakSet();
1271
1569
  bulkInsertTableRecords_fn = async function(objects) {
1272
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1570
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1273
1571
  const records = objects.map((object) => transformObjectLinks(object));
1274
- const response = await bulkInsertTableRecords({
1275
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table) },
1572
+ const { recordIDs } = await bulkInsertTableRecords({
1573
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1276
1574
  body: { records },
1277
1575
  ...fetchProps
1278
1576
  });
1279
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1577
+ const finalObjects = await this.read(recordIDs);
1280
1578
  if (finalObjects.length !== objects.length) {
1281
1579
  throw new Error("The server failed to save some records");
1282
1580
  }
1283
- return finalObjects;
1581
+ const dictionary = finalObjects.reduce((acc, object) => {
1582
+ acc[object.id] = object;
1583
+ return acc;
1584
+ }, {});
1585
+ return recordIDs.map((id) => dictionary[id]);
1284
1586
  };
1285
1587
  _updateRecordWithID = new WeakSet();
1286
1588
  updateRecordWithID_fn = async function(recordId, object) {
1287
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1589
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1288
1590
  const record = transformObjectLinks(object);
1289
1591
  const response = await updateRecordWithID({
1290
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table), recordId },
1592
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1291
1593
  body: record,
1292
1594
  ...fetchProps
1293
1595
  });
@@ -1298,9 +1600,9 @@ updateRecordWithID_fn = async function(recordId, object) {
1298
1600
  };
1299
1601
  _upsertRecordWithID = new WeakSet();
1300
1602
  upsertRecordWithID_fn = async function(recordId, object) {
1301
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1603
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1302
1604
  const response = await upsertRecordWithID({
1303
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table), recordId },
1605
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1304
1606
  body: object,
1305
1607
  ...fetchProps
1306
1608
  });
@@ -1311,11 +1613,62 @@ upsertRecordWithID_fn = async function(recordId, object) {
1311
1613
  };
1312
1614
  _deleteRecord = new WeakSet();
1313
1615
  deleteRecord_fn = async function(recordId) {
1314
- const fetchProps = await __privateGet$2(this, _getFetchProps).call(this);
1616
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1315
1617
  await deleteRecord({
1316
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table), recordId },
1618
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1619
+ ...fetchProps
1620
+ });
1621
+ };
1622
+ _invalidateCache = new WeakSet();
1623
+ invalidateCache_fn = async function(recordId) {
1624
+ await __privateGet$4(this, _cache).delete(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1625
+ const cacheItems = await __privateGet$4(this, _cache).getAll();
1626
+ const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1627
+ for (const [key, value] of queries) {
1628
+ const ids = getIds(value);
1629
+ if (ids.includes(recordId))
1630
+ await __privateGet$4(this, _cache).delete(key);
1631
+ }
1632
+ };
1633
+ _setCacheRecord = new WeakSet();
1634
+ setCacheRecord_fn = async function(record) {
1635
+ if (!__privateGet$4(this, _cache).cacheRecords)
1636
+ return;
1637
+ await __privateGet$4(this, _cache).set(`rec_${__privateGet$4(this, _table)}:${record.id}`, record);
1638
+ };
1639
+ _getCacheRecord = new WeakSet();
1640
+ getCacheRecord_fn = async function(recordId) {
1641
+ if (!__privateGet$4(this, _cache).cacheRecords)
1642
+ return null;
1643
+ return __privateGet$4(this, _cache).get(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1644
+ };
1645
+ _setCacheQuery = new WeakSet();
1646
+ setCacheQuery_fn = async function(query, meta, records) {
1647
+ await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1648
+ };
1649
+ _getCacheQuery = new WeakSet();
1650
+ getCacheQuery_fn = async function(query) {
1651
+ const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
1652
+ const result = await __privateGet$4(this, _cache).get(key);
1653
+ if (!result)
1654
+ return null;
1655
+ const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1656
+ if (ttl < 0)
1657
+ return null;
1658
+ const hasExpired = result.date.getTime() + ttl < Date.now();
1659
+ return hasExpired ? null : result;
1660
+ };
1661
+ _getSchemaTables$1 = new WeakSet();
1662
+ getSchemaTables_fn$1 = async function() {
1663
+ if (__privateGet$4(this, _schemaTables$2))
1664
+ return __privateGet$4(this, _schemaTables$2);
1665
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1666
+ const { schema } = await getBranchDetails({
1667
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1317
1668
  ...fetchProps
1318
1669
  });
1670
+ __privateSet$4(this, _schemaTables$2, schema.tables);
1671
+ return schema.tables;
1319
1672
  };
1320
1673
  const transformObjectLinks = (object) => {
1321
1674
  return Object.entries(object).reduce((acc, [key, value]) => {
@@ -1324,15 +1677,34 @@ const transformObjectLinks = (object) => {
1324
1677
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1325
1678
  }, {});
1326
1679
  };
1327
- const initObject = (db, links, table, object) => {
1680
+ const initObject = (db, schemaTables, table, object) => {
1328
1681
  const result = {};
1329
- Object.assign(result, object);
1330
- const tableLinks = links[table] || [];
1331
- for (const link of tableLinks) {
1332
- const [field, linkTable] = link;
1333
- const value = result[field];
1334
- if (value && isObject(value)) {
1335
- result[field] = initObject(db, links, linkTable, value);
1682
+ const { xata, ...rest } = object ?? {};
1683
+ Object.assign(result, rest);
1684
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
1685
+ if (!columns)
1686
+ console.error(`Table ${table} not found in schema`);
1687
+ for (const column of columns ?? []) {
1688
+ const value = result[column.name];
1689
+ switch (column.type) {
1690
+ case "datetime": {
1691
+ const date = value !== void 0 ? new Date(value) : void 0;
1692
+ if (date && isNaN(date.getTime())) {
1693
+ console.error(`Failed to parse date ${value} for field ${column.name}`);
1694
+ } else if (date) {
1695
+ result[column.name] = date;
1696
+ }
1697
+ break;
1698
+ }
1699
+ case "link": {
1700
+ const linkTable = column.link?.table;
1701
+ if (!linkTable) {
1702
+ console.error(`Failed to parse link for field ${column.name}`);
1703
+ } else if (isObject(value)) {
1704
+ result[column.name] = initObject(db, schemaTables, linkTable, value);
1705
+ }
1706
+ break;
1707
+ }
1336
1708
  }
1337
1709
  }
1338
1710
  result.read = function() {
@@ -1344,12 +1716,74 @@ const initObject = (db, links, table, object) => {
1344
1716
  result.delete = function() {
1345
1717
  return db[table].delete(result["id"]);
1346
1718
  };
1347
- for (const prop of ["read", "update", "delete"]) {
1719
+ result.getMetadata = function() {
1720
+ return xata;
1721
+ };
1722
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1348
1723
  Object.defineProperty(result, prop, { enumerable: false });
1349
1724
  }
1350
1725
  Object.freeze(result);
1351
1726
  return result;
1352
1727
  };
1728
+ function getIds(value) {
1729
+ if (Array.isArray(value)) {
1730
+ return value.map((item) => getIds(item)).flat();
1731
+ }
1732
+ if (!isObject(value))
1733
+ return [];
1734
+ const nestedIds = Object.values(value).map((item) => getIds(item)).flat();
1735
+ return isString(value.id) ? [value.id, ...nestedIds] : nestedIds;
1736
+ }
1737
+
1738
+ var __accessCheck$3 = (obj, member, msg) => {
1739
+ if (!member.has(obj))
1740
+ throw TypeError("Cannot " + msg);
1741
+ };
1742
+ var __privateGet$3 = (obj, member, getter) => {
1743
+ __accessCheck$3(obj, member, "read from private field");
1744
+ return getter ? getter.call(obj) : member.get(obj);
1745
+ };
1746
+ var __privateAdd$3 = (obj, member, value) => {
1747
+ if (member.has(obj))
1748
+ throw TypeError("Cannot add the same private member more than once");
1749
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1750
+ };
1751
+ var __privateSet$3 = (obj, member, value, setter) => {
1752
+ __accessCheck$3(obj, member, "write to private field");
1753
+ setter ? setter.call(obj, value) : member.set(obj, value);
1754
+ return value;
1755
+ };
1756
+ var _map;
1757
+ class SimpleCache {
1758
+ constructor(options = {}) {
1759
+ __privateAdd$3(this, _map, void 0);
1760
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1761
+ this.capacity = options.max ?? 500;
1762
+ this.cacheRecords = options.cacheRecords ?? true;
1763
+ this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1764
+ }
1765
+ async getAll() {
1766
+ return Object.fromEntries(__privateGet$3(this, _map));
1767
+ }
1768
+ async get(key) {
1769
+ return __privateGet$3(this, _map).get(key) ?? null;
1770
+ }
1771
+ async set(key, value) {
1772
+ await this.delete(key);
1773
+ __privateGet$3(this, _map).set(key, value);
1774
+ if (__privateGet$3(this, _map).size > this.capacity) {
1775
+ const leastRecentlyUsed = __privateGet$3(this, _map).keys().next().value;
1776
+ await this.delete(leastRecentlyUsed);
1777
+ }
1778
+ }
1779
+ async delete(key) {
1780
+ __privateGet$3(this, _map).delete(key);
1781
+ }
1782
+ async clear() {
1783
+ return __privateGet$3(this, _map).clear();
1784
+ }
1785
+ }
1786
+ _map = new WeakMap();
1353
1787
 
1354
1788
  const gt = (value) => ({ $gt: value });
1355
1789
  const ge = (value) => ({ $ge: value });
@@ -1374,7 +1808,7 @@ var __accessCheck$2 = (obj, member, msg) => {
1374
1808
  if (!member.has(obj))
1375
1809
  throw TypeError("Cannot " + msg);
1376
1810
  };
1377
- var __privateGet$1 = (obj, member, getter) => {
1811
+ var __privateGet$2 = (obj, member, getter) => {
1378
1812
  __accessCheck$2(obj, member, "read from private field");
1379
1813
  return getter ? getter.call(obj) : member.get(obj);
1380
1814
  };
@@ -1383,122 +1817,158 @@ var __privateAdd$2 = (obj, member, value) => {
1383
1817
  throw TypeError("Cannot add the same private member more than once");
1384
1818
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1385
1819
  };
1386
- var _tables;
1820
+ var __privateSet$2 = (obj, member, value, setter) => {
1821
+ __accessCheck$2(obj, member, "write to private field");
1822
+ setter ? setter.call(obj, value) : member.set(obj, value);
1823
+ return value;
1824
+ };
1825
+ var _tables, _schemaTables$1;
1387
1826
  class SchemaPlugin extends XataPlugin {
1388
- constructor(links, tableNames) {
1827
+ constructor(schemaTables) {
1389
1828
  super();
1390
- this.links = links;
1391
- this.tableNames = tableNames;
1392
1829
  __privateAdd$2(this, _tables, {});
1830
+ __privateAdd$2(this, _schemaTables$1, void 0);
1831
+ __privateSet$2(this, _schemaTables$1, schemaTables);
1393
1832
  }
1394
- build(options) {
1395
- const { getFetchProps } = options;
1396
- const links = this.links;
1833
+ build(pluginOptions) {
1397
1834
  const db = new Proxy({}, {
1398
1835
  get: (_target, table) => {
1399
1836
  if (!isString(table))
1400
1837
  throw new Error("Invalid table name");
1401
- if (!__privateGet$1(this, _tables)[table])
1402
- __privateGet$1(this, _tables)[table] = new RestRepository({ db, getFetchProps, table, links });
1403
- return __privateGet$1(this, _tables)[table];
1838
+ if (__privateGet$2(this, _tables)[table] === void 0) {
1839
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1840
+ }
1841
+ return __privateGet$2(this, _tables)[table];
1404
1842
  }
1405
1843
  });
1406
- for (const table of this.tableNames ?? []) {
1407
- db[table] = new RestRepository({ db, getFetchProps, table, links });
1844
+ const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
1845
+ for (const table of tableNames) {
1846
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1408
1847
  }
1409
1848
  return db;
1410
1849
  }
1411
1850
  }
1412
1851
  _tables = new WeakMap();
1852
+ _schemaTables$1 = new WeakMap();
1413
1853
 
1414
1854
  var __accessCheck$1 = (obj, member, msg) => {
1415
1855
  if (!member.has(obj))
1416
1856
  throw TypeError("Cannot " + msg);
1417
1857
  };
1858
+ var __privateGet$1 = (obj, member, getter) => {
1859
+ __accessCheck$1(obj, member, "read from private field");
1860
+ return getter ? getter.call(obj) : member.get(obj);
1861
+ };
1418
1862
  var __privateAdd$1 = (obj, member, value) => {
1419
1863
  if (member.has(obj))
1420
1864
  throw TypeError("Cannot add the same private member more than once");
1421
1865
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1422
1866
  };
1867
+ var __privateSet$1 = (obj, member, value, setter) => {
1868
+ __accessCheck$1(obj, member, "write to private field");
1869
+ setter ? setter.call(obj, value) : member.set(obj, value);
1870
+ return value;
1871
+ };
1423
1872
  var __privateMethod$1 = (obj, member, method) => {
1424
1873
  __accessCheck$1(obj, member, "access private method");
1425
1874
  return method;
1426
1875
  };
1427
- var _search, search_fn;
1876
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1428
1877
  class SearchPlugin extends XataPlugin {
1429
- constructor(db, links) {
1878
+ constructor(db, schemaTables) {
1430
1879
  super();
1431
1880
  this.db = db;
1432
- this.links = links;
1433
1881
  __privateAdd$1(this, _search);
1882
+ __privateAdd$1(this, _getSchemaTables);
1883
+ __privateAdd$1(this, _schemaTables, void 0);
1884
+ __privateSet$1(this, _schemaTables, schemaTables);
1434
1885
  }
1435
1886
  build({ getFetchProps }) {
1436
1887
  return {
1437
1888
  all: async (query, options = {}) => {
1438
1889
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1890
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1439
1891
  return records.map((record) => {
1440
1892
  const { table = "orphan" } = record.xata;
1441
- return { table, record: initObject(this.db, this.links, table, record) };
1893
+ return { table, record: initObject(this.db, schemaTables, table, record) };
1442
1894
  });
1443
1895
  },
1444
1896
  byTable: async (query, options = {}) => {
1445
1897
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1898
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1446
1899
  return records.reduce((acc, record) => {
1447
1900
  const { table = "orphan" } = record.xata;
1448
1901
  const items = acc[table] ?? [];
1449
- const item = initObject(this.db, this.links, table, record);
1902
+ const item = initObject(this.db, schemaTables, table, record);
1450
1903
  return { ...acc, [table]: [...items, item] };
1451
1904
  }, {});
1452
1905
  }
1453
1906
  };
1454
1907
  }
1455
1908
  }
1909
+ _schemaTables = new WeakMap();
1456
1910
  _search = new WeakSet();
1457
1911
  search_fn = async function(query, options, getFetchProps) {
1458
1912
  const fetchProps = await getFetchProps();
1459
- const { tables, fuzziness } = options ?? {};
1913
+ const { tables, fuzziness, highlight } = options ?? {};
1460
1914
  const { records } = await searchBranch({
1461
1915
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1462
- body: { tables, query, fuzziness },
1916
+ body: { tables, query, fuzziness, highlight },
1463
1917
  ...fetchProps
1464
1918
  });
1465
1919
  return records;
1466
1920
  };
1921
+ _getSchemaTables = new WeakSet();
1922
+ getSchemaTables_fn = async function(getFetchProps) {
1923
+ if (__privateGet$1(this, _schemaTables))
1924
+ return __privateGet$1(this, _schemaTables);
1925
+ const fetchProps = await getFetchProps();
1926
+ const { schema } = await getBranchDetails({
1927
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1928
+ ...fetchProps
1929
+ });
1930
+ __privateSet$1(this, _schemaTables, schema.tables);
1931
+ return schema.tables;
1932
+ };
1467
1933
 
1468
1934
  const isBranchStrategyBuilder = (strategy) => {
1469
1935
  return typeof strategy === "function";
1470
1936
  };
1471
1937
 
1472
- const envBranchNames = [
1473
- "XATA_BRANCH",
1474
- "VERCEL_GIT_COMMIT_REF",
1475
- "CF_PAGES_BRANCH",
1476
- "BRANCH"
1477
- ];
1478
- const defaultBranch = "main";
1479
1938
  async function getCurrentBranchName(options) {
1480
- const env = await getBranchByEnvVariable();
1481
- if (env)
1482
- return env;
1483
- const branch = await getGitBranch();
1484
- if (!branch)
1485
- return defaultBranch;
1486
- const details = await getDatabaseBranch(branch, options);
1487
- if (details)
1488
- return branch;
1489
- return defaultBranch;
1939
+ const { branch, envBranch } = getEnvironment();
1940
+ if (branch) {
1941
+ const details = await getDatabaseBranch(branch, options);
1942
+ if (details)
1943
+ return branch;
1944
+ console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
1945
+ }
1946
+ const gitBranch = envBranch || await getGitBranch();
1947
+ return resolveXataBranch(gitBranch, options);
1490
1948
  }
1491
1949
  async function getCurrentBranchDetails(options) {
1492
- const env = await getBranchByEnvVariable();
1493
- if (env)
1494
- return getDatabaseBranch(env, options);
1495
- const branch = await getGitBranch();
1496
- if (!branch)
1497
- return getDatabaseBranch(defaultBranch, options);
1498
- const details = await getDatabaseBranch(branch, options);
1499
- if (details)
1500
- return details;
1501
- return getDatabaseBranch(defaultBranch, options);
1950
+ const branch = await getCurrentBranchName(options);
1951
+ return getDatabaseBranch(branch, options);
1952
+ }
1953
+ async function resolveXataBranch(gitBranch, options) {
1954
+ const databaseURL = options?.databaseURL || getDatabaseURL();
1955
+ const apiKey = options?.apiKey || getAPIKey();
1956
+ if (!databaseURL)
1957
+ throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
1958
+ if (!apiKey)
1959
+ throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
1960
+ const [protocol, , host, , dbName] = databaseURL.split("/");
1961
+ const [workspace] = host.split(".");
1962
+ const { fallbackBranch } = getEnvironment();
1963
+ const { branch } = await resolveBranch({
1964
+ apiKey,
1965
+ apiUrl: databaseURL,
1966
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
1967
+ workspacesApiUrl: `${protocol}//${host}`,
1968
+ pathParams: { dbName, workspace },
1969
+ queryParams: { gitBranch, fallbackBranch }
1970
+ });
1971
+ return branch;
1502
1972
  }
1503
1973
  async function getDatabaseBranch(branch, options) {
1504
1974
  const databaseURL = options?.databaseURL || getDatabaseURL();
@@ -1516,10 +1986,7 @@ async function getDatabaseBranch(branch, options) {
1516
1986
  apiUrl: databaseURL,
1517
1987
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1518
1988
  workspacesApiUrl: `${protocol}//${host}`,
1519
- pathParams: {
1520
- dbBranchName,
1521
- workspace
1522
- }
1989
+ pathParams: { dbBranchName, workspace }
1523
1990
  });
1524
1991
  } catch (err) {
1525
1992
  if (isObject(err) && err.status === 404)
@@ -1527,21 +1994,10 @@ async function getDatabaseBranch(branch, options) {
1527
1994
  throw err;
1528
1995
  }
1529
1996
  }
1530
- function getBranchByEnvVariable() {
1531
- for (const name of envBranchNames) {
1532
- const value = getEnvVariable(name);
1533
- if (value) {
1534
- return value;
1535
- }
1536
- }
1537
- try {
1538
- return XATA_BRANCH;
1539
- } catch (err) {
1540
- }
1541
- }
1542
1997
  function getDatabaseURL() {
1543
1998
  try {
1544
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
1999
+ const { databaseURL } = getEnvironment();
2000
+ return databaseURL;
1545
2001
  } catch (err) {
1546
2002
  return void 0;
1547
2003
  }
@@ -1572,22 +2028,24 @@ var __privateMethod = (obj, member, method) => {
1572
2028
  const buildClient = (plugins) => {
1573
2029
  var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1574
2030
  return _a = class {
1575
- constructor(options = {}, links, tables) {
2031
+ constructor(options = {}, schemaTables) {
1576
2032
  __privateAdd(this, _parseOptions);
1577
2033
  __privateAdd(this, _getFetchProps);
1578
2034
  __privateAdd(this, _evaluateBranch);
1579
2035
  __privateAdd(this, _branch, void 0);
1580
2036
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
1581
- const db = new SchemaPlugin(links, tables).build({ getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions) });
1582
- const search = new SearchPlugin(db, links ?? {}).build({
1583
- getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions)
1584
- });
2037
+ const pluginOptions = {
2038
+ getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
2039
+ cache: safeOptions.cache
2040
+ };
2041
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2042
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1585
2043
  this.db = db;
1586
2044
  this.search = search;
1587
2045
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
1588
- if (!namespace)
2046
+ if (namespace === void 0)
1589
2047
  continue;
1590
- const result = namespace.build({ getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions) });
2048
+ const result = namespace.build(pluginOptions);
1591
2049
  if (result instanceof Promise) {
1592
2050
  void result.then((namespace2) => {
1593
2051
  this[key] = namespace2;
@@ -1601,11 +2059,12 @@ const buildClient = (plugins) => {
1601
2059
  const fetch = getFetchImplementation(options?.fetch);
1602
2060
  const databaseURL = options?.databaseURL || getDatabaseURL();
1603
2061
  const apiKey = options?.apiKey || getAPIKey();
1604
- const branch = async () => options?.branch ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
2062
+ const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
2063
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1605
2064
  if (!databaseURL || !apiKey) {
1606
2065
  throw new Error("Options databaseURL and apiKey are required");
1607
2066
  }
1608
- return { fetch, databaseURL, apiKey, branch };
2067
+ return { fetch, databaseURL, apiKey, branch, cache };
1609
2068
  }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
1610
2069
  fetch,
1611
2070
  apiKey,
@@ -1628,7 +2087,7 @@ const buildClient = (plugins) => {
1628
2087
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1629
2088
  if (__privateGet(this, _branch))
1630
2089
  return __privateGet(this, _branch);
1631
- if (!param)
2090
+ if (param === void 0)
1632
2091
  return void 0;
1633
2092
  const strategies = Array.isArray(param) ? [...param] : [param];
1634
2093
  const evaluateBranch = async (strategy) => {
@@ -1661,15 +2120,18 @@ exports.PAGINATION_MAX_OFFSET = PAGINATION_MAX_OFFSET;
1661
2120
  exports.PAGINATION_MAX_SIZE = PAGINATION_MAX_SIZE;
1662
2121
  exports.Page = Page;
1663
2122
  exports.Query = Query;
2123
+ exports.RecordArray = RecordArray;
1664
2124
  exports.Repository = Repository;
1665
2125
  exports.RestRepository = RestRepository;
1666
2126
  exports.SchemaPlugin = SchemaPlugin;
1667
2127
  exports.SearchPlugin = SearchPlugin;
2128
+ exports.SimpleCache = SimpleCache;
1668
2129
  exports.XataApiClient = XataApiClient;
1669
2130
  exports.XataApiPlugin = XataApiPlugin;
1670
2131
  exports.XataError = XataError;
1671
2132
  exports.XataPlugin = XataPlugin;
1672
2133
  exports.acceptWorkspaceMemberInvite = acceptWorkspaceMemberInvite;
2134
+ exports.addGitBranchesEntry = addGitBranchesEntry;
1673
2135
  exports.addTableColumn = addTableColumn;
1674
2136
  exports.buildClient = buildClient;
1675
2137
  exports.bulkInsertTableRecords = bulkInsertTableRecords;
@@ -1704,6 +2166,7 @@ exports.getCurrentBranchDetails = getCurrentBranchDetails;
1704
2166
  exports.getCurrentBranchName = getCurrentBranchName;
1705
2167
  exports.getDatabaseList = getDatabaseList;
1706
2168
  exports.getDatabaseURL = getDatabaseURL;
2169
+ exports.getGitBranchesMapping = getGitBranchesMapping;
1707
2170
  exports.getRecord = getRecord;
1708
2171
  exports.getTableColumns = getTableColumns;
1709
2172
  exports.getTableSchema = getTableSchema;
@@ -1722,6 +2185,7 @@ exports.insertRecord = insertRecord;
1722
2185
  exports.insertRecordWithID = insertRecordWithID;
1723
2186
  exports.inviteWorkspaceMember = inviteWorkspaceMember;
1724
2187
  exports.is = is;
2188
+ exports.isCursorPaginationOptions = isCursorPaginationOptions;
1725
2189
  exports.isIdentifiable = isIdentifiable;
1726
2190
  exports.isNot = isNot;
1727
2191
  exports.isXataRecord = isXataRecord;
@@ -1732,9 +2196,12 @@ exports.notExists = notExists;
1732
2196
  exports.operationsByTag = operationsByTag;
1733
2197
  exports.pattern = pattern;
1734
2198
  exports.queryTable = queryTable;
2199
+ exports.removeGitBranchesEntry = removeGitBranchesEntry;
1735
2200
  exports.removeWorkspaceMember = removeWorkspaceMember;
1736
2201
  exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite;
2202
+ exports.resolveBranch = resolveBranch;
1737
2203
  exports.searchBranch = searchBranch;
2204
+ exports.searchTable = searchTable;
1738
2205
  exports.setTableSchema = setTableSchema;
1739
2206
  exports.startsWith = startsWith;
1740
2207
  exports.updateBranchMetadata = updateBranchMetadata;
@@ -1743,6 +2210,7 @@ exports.updateRecordWithID = updateRecordWithID;
1743
2210
  exports.updateTable = updateTable;
1744
2211
  exports.updateUser = updateUser;
1745
2212
  exports.updateWorkspace = updateWorkspace;
2213
+ exports.updateWorkspaceMemberInvite = updateWorkspaceMemberInvite;
1746
2214
  exports.updateWorkspaceMemberRole = updateWorkspaceMemberRole;
1747
2215
  exports.upsertRecordWithID = upsertRecordWithID;
1748
2216
  //# sourceMappingURL=index.cjs.map