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

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