@xata.io/client 0.0.0-alpha.vf4b92f1 → 0.0.0-alpha.vf603f80

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,43 +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";
16
37
  }
17
38
  function toBase64(value) {
18
39
  try {
19
40
  return btoa(value);
20
41
  } catch (err) {
21
- return Buffer.from(value).toString("base64");
42
+ const buf = Buffer;
43
+ return buf.from(value).toString("base64");
22
44
  }
23
45
  }
24
46
 
25
- function getEnvVariable(name) {
47
+ function getEnvironment() {
26
48
  try {
27
- if (isObject(process) && isString(process?.env?.[name])) {
28
- 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
+ };
29
57
  }
30
58
  } catch (err) {
31
59
  }
32
60
  try {
33
- if (isObject(Deno) && isString(Deno?.env?.get(name))) {
34
- 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
+ };
35
69
  }
36
70
  } catch (err) {
37
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
+ }
38
107
  }
39
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"] };
40
113
  try {
41
- 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();
42
119
  } catch (err) {
43
120
  }
44
121
  try {
45
122
  if (isObject(Deno)) {
46
- const process2 = Deno.run({
47
- cmd: ["git", "branch", "--show-current"],
48
- stdout: "piped",
49
- stderr: "piped"
50
- });
123
+ const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
51
124
  return new TextDecoder().decode(await process2.output()).trim();
52
125
  }
53
126
  } catch (err) {
@@ -56,7 +129,8 @@ async function getGitBranch() {
56
129
 
57
130
  function getAPIKey() {
58
131
  try {
59
- return getEnvVariable("XATA_API_KEY") ?? XATA_API_KEY;
132
+ const { apiKey } = getEnvironment();
133
+ return apiKey;
60
134
  } catch (err) {
61
135
  return void 0;
62
136
  }
@@ -71,16 +145,28 @@ function getFetchImplementation(userFetch) {
71
145
  return fetchImpl;
72
146
  }
73
147
 
74
- class FetcherError extends Error {
75
- constructor(status, data) {
148
+ const VERSION = "0.0.0-alpha.vf603f80";
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) {
76
157
  super(getMessage(data));
77
158
  this.status = status;
78
159
  this.errors = isBulkError(data) ? data.errors : void 0;
160
+ this.requestId = requestId;
79
161
  if (data instanceof Error) {
80
162
  this.stack = data.stack;
81
163
  this.cause = data.cause;
82
164
  }
83
165
  }
166
+ toString() {
167
+ const error = super.toString();
168
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
169
+ }
84
170
  }
85
171
  function isBulkError(error) {
86
172
  return isObject(error) && Array.isArray(error.errors);
@@ -103,7 +189,12 @@ function getMessage(data) {
103
189
  }
104
190
 
105
191
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
106
- 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();
107
198
  const queryString = query.length > 0 ? `?${query}` : "";
108
199
  return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
109
200
  };
@@ -143,6 +234,7 @@ async function fetch$1({
143
234
  body: body ? JSON.stringify(body) : void 0,
144
235
  headers: {
145
236
  "Content-Type": "application/json",
237
+ "User-Agent": `Xata client-ts/${VERSION}`,
146
238
  ...headers,
147
239
  ...hostHeader(fullUrl),
148
240
  Authorization: `Bearer ${apiKey}`
@@ -151,14 +243,15 @@ async function fetch$1({
151
243
  if (response.status === 204) {
152
244
  return {};
153
245
  }
246
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
154
247
  try {
155
248
  const jsonResponse = await response.json();
156
249
  if (response.ok) {
157
250
  return jsonResponse;
158
251
  }
159
- throw new FetcherError(response.status, jsonResponse);
252
+ throw new FetcherError(response.status, jsonResponse, requestId);
160
253
  } catch (error) {
161
- throw new FetcherError(response.status, error);
254
+ throw new FetcherError(response.status, error, requestId);
162
255
  }
163
256
  }
164
257
 
@@ -217,6 +310,7 @@ const removeWorkspaceMember = (variables) => fetch$1({
217
310
  ...variables
218
311
  });
219
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 });
220
314
  const cancelWorkspaceMemberInvite = (variables) => fetch$1({
221
315
  url: "/workspaces/{workspaceId}/invites/{inviteId}",
222
316
  method: "delete",
@@ -252,6 +346,14 @@ const deleteDatabase = (variables) => fetch$1({
252
346
  method: "delete",
253
347
  ...variables
254
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
+ });
255
357
  const getBranchDetails = (variables) => fetch$1({
256
358
  url: "/db/{dbBranchName}",
257
359
  method: "get",
@@ -359,6 +461,11 @@ const queryTable = (variables) => fetch$1({
359
461
  method: "post",
360
462
  ...variables
361
463
  });
464
+ const searchTable = (variables) => fetch$1({
465
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
466
+ method: "post",
467
+ ...variables
468
+ });
362
469
  const searchBranch = (variables) => fetch$1({
363
470
  url: "/db/{dbBranchName}/search",
364
471
  method: "post",
@@ -376,11 +483,20 @@ const operationsByTag = {
376
483
  updateWorkspaceMemberRole,
377
484
  removeWorkspaceMember,
378
485
  inviteWorkspaceMember,
486
+ updateWorkspaceMemberInvite,
379
487
  cancelWorkspaceMemberInvite,
380
488
  resendWorkspaceMemberInvite,
381
489
  acceptWorkspaceMemberInvite
382
490
  },
383
- database: { getDatabaseList, createDatabase, deleteDatabase },
491
+ database: {
492
+ getDatabaseList,
493
+ createDatabase,
494
+ deleteDatabase,
495
+ getGitBranchesMapping,
496
+ addGitBranchesEntry,
497
+ removeGitBranchesEntry,
498
+ resolveBranch
499
+ },
384
500
  branch: {
385
501
  getBranchList,
386
502
  getBranchDetails,
@@ -414,6 +530,7 @@ const operationsByTag = {
414
530
  getRecord,
415
531
  bulkInsertTableRecords,
416
532
  queryTable,
533
+ searchTable,
417
534
  searchBranch
418
535
  }
419
536
  };
@@ -447,7 +564,7 @@ var __accessCheck$7 = (obj, member, msg) => {
447
564
  if (!member.has(obj))
448
565
  throw TypeError("Cannot " + msg);
449
566
  };
450
- var __privateGet$6 = (obj, member, getter) => {
567
+ var __privateGet$7 = (obj, member, getter) => {
451
568
  __accessCheck$7(obj, member, "read from private field");
452
569
  return getter ? getter.call(obj) : member.get(obj);
453
570
  };
@@ -456,7 +573,7 @@ var __privateAdd$7 = (obj, member, value) => {
456
573
  throw TypeError("Cannot add the same private member more than once");
457
574
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
458
575
  };
459
- var __privateSet$5 = (obj, member, value, setter) => {
576
+ var __privateSet$7 = (obj, member, value, setter) => {
460
577
  __accessCheck$7(obj, member, "write to private field");
461
578
  setter ? setter.call(obj, value) : member.set(obj, value);
462
579
  return value;
@@ -471,7 +588,7 @@ class XataApiClient {
471
588
  if (!apiKey) {
472
589
  throw new Error("Could not resolve a valid apiKey");
473
590
  }
474
- __privateSet$5(this, _extraProps, {
591
+ __privateSet$7(this, _extraProps, {
475
592
  apiUrl: getHostUrl(provider, "main"),
476
593
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
477
594
  fetchImpl: getFetchImplementation(options.fetch),
@@ -479,34 +596,34 @@ class XataApiClient {
479
596
  });
480
597
  }
481
598
  get user() {
482
- if (!__privateGet$6(this, _namespaces).user)
483
- __privateGet$6(this, _namespaces).user = new UserApi(__privateGet$6(this, _extraProps));
484
- return __privateGet$6(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;
485
602
  }
486
603
  get workspaces() {
487
- if (!__privateGet$6(this, _namespaces).workspaces)
488
- __privateGet$6(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$6(this, _extraProps));
489
- return __privateGet$6(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;
490
607
  }
491
608
  get databases() {
492
- if (!__privateGet$6(this, _namespaces).databases)
493
- __privateGet$6(this, _namespaces).databases = new DatabaseApi(__privateGet$6(this, _extraProps));
494
- return __privateGet$6(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;
495
612
  }
496
613
  get branches() {
497
- if (!__privateGet$6(this, _namespaces).branches)
498
- __privateGet$6(this, _namespaces).branches = new BranchApi(__privateGet$6(this, _extraProps));
499
- return __privateGet$6(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;
500
617
  }
501
618
  get tables() {
502
- if (!__privateGet$6(this, _namespaces).tables)
503
- __privateGet$6(this, _namespaces).tables = new TableApi(__privateGet$6(this, _extraProps));
504
- return __privateGet$6(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;
505
622
  }
506
623
  get records() {
507
- if (!__privateGet$6(this, _namespaces).records)
508
- __privateGet$6(this, _namespaces).records = new RecordsApi(__privateGet$6(this, _extraProps));
509
- return __privateGet$6(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;
510
627
  }
511
628
  }
512
629
  _extraProps = new WeakMap();
@@ -598,6 +715,13 @@ class WorkspaceApi {
598
715
  ...this.extraProps
599
716
  });
600
717
  }
718
+ updateWorkspaceMemberInvite(workspaceId, inviteId, role) {
719
+ return operationsByTag.workspaces.updateWorkspaceMemberInvite({
720
+ pathParams: { workspaceId, inviteId },
721
+ body: { role },
722
+ ...this.extraProps
723
+ });
724
+ }
601
725
  cancelWorkspaceMemberInvite(workspaceId, inviteId) {
602
726
  return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
603
727
  pathParams: { workspaceId, inviteId },
@@ -640,6 +764,33 @@ class DatabaseApi {
640
764
  ...this.extraProps
641
765
  });
642
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
+ }
643
794
  }
644
795
  class BranchApi {
645
796
  constructor(extraProps) {
@@ -657,10 +808,10 @@ class BranchApi {
657
808
  ...this.extraProps
658
809
  });
659
810
  }
660
- createBranch(workspace, database, branch, from = "", options = {}) {
811
+ createBranch(workspace, database, branch, from, options = {}) {
661
812
  return operationsByTag.branch.createBranch({
662
813
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
663
- queryParams: { from },
814
+ queryParams: isString(from) ? { from } : void 0,
664
815
  body: options,
665
816
  ...this.extraProps
666
817
  });
@@ -842,6 +993,13 @@ class RecordsApi {
842
993
  ...this.extraProps
843
994
  });
844
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
+ }
845
1003
  searchBranch(workspace, database, branch, query) {
846
1004
  return operationsByTag.records.searchBranch({
847
1005
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -865,7 +1023,7 @@ var __accessCheck$6 = (obj, member, msg) => {
865
1023
  if (!member.has(obj))
866
1024
  throw TypeError("Cannot " + msg);
867
1025
  };
868
- var __privateGet$5 = (obj, member, getter) => {
1026
+ var __privateGet$6 = (obj, member, getter) => {
869
1027
  __accessCheck$6(obj, member, "read from private field");
870
1028
  return getter ? getter.call(obj) : member.get(obj);
871
1029
  };
@@ -874,30 +1032,30 @@ var __privateAdd$6 = (obj, member, value) => {
874
1032
  throw TypeError("Cannot add the same private member more than once");
875
1033
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
876
1034
  };
877
- var __privateSet$4 = (obj, member, value, setter) => {
1035
+ var __privateSet$6 = (obj, member, value, setter) => {
878
1036
  __accessCheck$6(obj, member, "write to private field");
879
1037
  setter ? setter.call(obj, value) : member.set(obj, value);
880
1038
  return value;
881
1039
  };
882
- var _query;
1040
+ var _query, _page;
883
1041
  class Page {
884
1042
  constructor(query, meta, records = []) {
885
1043
  __privateAdd$6(this, _query, void 0);
886
- __privateSet$4(this, _query, query);
1044
+ __privateSet$6(this, _query, query);
887
1045
  this.meta = meta;
888
- this.records = records;
1046
+ this.records = new RecordArray(this, records);
889
1047
  }
890
1048
  async nextPage(size, offset) {
891
- return __privateGet$5(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 } });
892
1050
  }
893
1051
  async previousPage(size, offset) {
894
- return __privateGet$5(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 } });
895
1053
  }
896
1054
  async firstPage(size, offset) {
897
- return __privateGet$5(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 } });
898
1056
  }
899
1057
  async lastPage(size, offset) {
900
- return __privateGet$5(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 } });
901
1059
  }
902
1060
  hasNextPage() {
903
1061
  return this.meta.page.more;
@@ -905,15 +1063,62 @@ class Page {
905
1063
  }
906
1064
  _query = new WeakMap();
907
1065
  const PAGINATION_MAX_SIZE = 200;
908
- const PAGINATION_DEFAULT_SIZE = 200;
1066
+ const PAGINATION_DEFAULT_SIZE = 20;
909
1067
  const PAGINATION_MAX_OFFSET = 800;
910
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();
911
1116
 
912
1117
  var __accessCheck$5 = (obj, member, msg) => {
913
1118
  if (!member.has(obj))
914
1119
  throw TypeError("Cannot " + msg);
915
1120
  };
916
- var __privateGet$4 = (obj, member, getter) => {
1121
+ var __privateGet$5 = (obj, member, getter) => {
917
1122
  __accessCheck$5(obj, member, "read from private field");
918
1123
  return getter ? getter.call(obj) : member.get(obj);
919
1124
  };
@@ -922,34 +1127,35 @@ var __privateAdd$5 = (obj, member, value) => {
922
1127
  throw TypeError("Cannot add the same private member more than once");
923
1128
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
924
1129
  };
925
- var __privateSet$3 = (obj, member, value, setter) => {
1130
+ var __privateSet$5 = (obj, member, value, setter) => {
926
1131
  __accessCheck$5(obj, member, "write to private field");
927
1132
  setter ? setter.call(obj, value) : member.set(obj, value);
928
1133
  return value;
929
1134
  };
930
1135
  var _table$1, _repository, _data;
931
1136
  const _Query = class {
932
- constructor(repository, table, data, parent) {
1137
+ constructor(repository, table, data, rawParent) {
933
1138
  __privateAdd$5(this, _table$1, void 0);
934
1139
  __privateAdd$5(this, _repository, void 0);
935
1140
  __privateAdd$5(this, _data, { filter: {} });
936
1141
  this.meta = { page: { cursor: "start", more: true } };
937
- this.records = [];
938
- __privateSet$3(this, _table$1, table);
1142
+ this.records = new RecordArray(this, []);
1143
+ __privateSet$5(this, _table$1, table);
939
1144
  if (repository) {
940
- __privateSet$3(this, _repository, repository);
1145
+ __privateSet$5(this, _repository, repository);
941
1146
  } else {
942
- __privateSet$3(this, _repository, this);
1147
+ __privateSet$5(this, _repository, this);
943
1148
  }
944
- __privateGet$4(this, _data).filter = data.filter ?? parent?.filter ?? {};
945
- __privateGet$4(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
946
- __privateGet$4(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
947
- __privateGet$4(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
948
- __privateGet$4(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
949
- __privateGet$4(this, _data).sort = data.sort ?? parent?.sort;
950
- __privateGet$4(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
951
- __privateGet$4(this, _data).page = data.page ?? parent?.page;
952
- __privateGet$4(this, _data).cache = data.cache ?? parent?.cache;
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;
953
1159
  this.any = this.any.bind(this);
954
1160
  this.all = this.all.bind(this);
955
1161
  this.not = this.not.bind(this);
@@ -960,83 +1166,88 @@ const _Query = class {
960
1166
  Object.defineProperty(this, "repository", { enumerable: false });
961
1167
  }
962
1168
  getQueryOptions() {
963
- return __privateGet$4(this, _data);
1169
+ return __privateGet$5(this, _data);
964
1170
  }
965
1171
  key() {
966
- const { columns = [], filter = {}, sort = [], page = {} } = __privateGet$4(this, _data);
967
- const key = JSON.stringify({ columns, filter, sort, page });
1172
+ const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$5(this, _data);
1173
+ const key = JSON.stringify({ columns, filter, sort, pagination });
968
1174
  return toBase64(key);
969
1175
  }
970
1176
  any(...queries) {
971
1177
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
972
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $any } }, __privateGet$4(this, _data));
1178
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
973
1179
  }
974
1180
  all(...queries) {
975
1181
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
976
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1182
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
977
1183
  }
978
1184
  not(...queries) {
979
1185
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
980
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $not } }, __privateGet$4(this, _data));
1186
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
981
1187
  }
982
1188
  none(...queries) {
983
1189
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
984
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $none } }, __privateGet$4(this, _data));
1190
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
985
1191
  }
986
1192
  filter(a, b) {
987
1193
  if (arguments.length === 1) {
988
1194
  const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
989
- const $all = compact([__privateGet$4(this, _data).filter?.$all].flat().concat(constraints));
990
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(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));
991
1197
  } else {
992
- const $all = compact([__privateGet$4(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
993
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(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));
994
1200
  }
995
1201
  }
996
1202
  sort(column, direction) {
997
- const originalSort = [__privateGet$4(this, _data).sort ?? []].flat();
1203
+ const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
998
1204
  const sort = [...originalSort, { column, direction }];
999
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { sort }, __privateGet$4(this, _data));
1205
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
1000
1206
  }
1001
1207
  select(columns) {
1002
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { columns }, __privateGet$4(this, _data));
1208
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { columns }, __privateGet$5(this, _data));
1003
1209
  }
1004
1210
  getPaginated(options = {}) {
1005
- const query = new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), options, __privateGet$4(this, _data));
1006
- return __privateGet$4(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);
1007
1213
  }
1008
1214
  async *[Symbol.asyncIterator]() {
1009
- for await (const [record] of this.getIterator(1)) {
1215
+ for await (const [record] of this.getIterator({ batchSize: 1 })) {
1010
1216
  yield record;
1011
1217
  }
1012
1218
  }
1013
- async *getIterator(chunk, options = {}) {
1014
- let offset = 0;
1015
- let end = false;
1016
- while (!end) {
1017
- const { records, meta } = await this.getPaginated({ ...options, page: { size: chunk, offset } });
1018
- yield records;
1019
- offset += chunk;
1020
- 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;
1021
1228
  }
1022
1229
  }
1023
1230
  async getMany(options = {}) {
1024
- const { records } = await this.getPaginated(options);
1025
- 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;
1026
1236
  }
1027
- async getAll(chunk = PAGINATION_MAX_SIZE, options = {}) {
1237
+ async getAll(options = {}) {
1238
+ const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
1028
1239
  const results = [];
1029
- for await (const page of this.getIterator(chunk, options)) {
1240
+ for await (const page of this.getIterator({ ...rest, batchSize })) {
1030
1241
  results.push(...page);
1031
1242
  }
1032
1243
  return results;
1033
1244
  }
1034
1245
  async getFirst(options = {}) {
1035
- const records = await this.getMany({ ...options, page: { size: 1 } });
1036
- return records[0] || null;
1246
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1247
+ return records[0] ?? null;
1037
1248
  }
1038
1249
  cache(ttl) {
1039
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { cache: ttl }, __privateGet$4(this, _data));
1250
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1040
1251
  }
1041
1252
  nextPage(size, offset) {
1042
1253
  return this.firstPage(size, offset);
@@ -1045,10 +1256,10 @@ const _Query = class {
1045
1256
  return this.firstPage(size, offset);
1046
1257
  }
1047
1258
  firstPage(size, offset) {
1048
- return this.getPaginated({ page: { size, offset } });
1259
+ return this.getPaginated({ pagination: { size, offset } });
1049
1260
  }
1050
1261
  lastPage(size, offset) {
1051
- return this.getPaginated({ page: { size, offset, before: "end" } });
1262
+ return this.getPaginated({ pagination: { size, offset, before: "end" } });
1052
1263
  }
1053
1264
  hasNextPage() {
1054
1265
  return this.meta.page.more;
@@ -1058,12 +1269,20 @@ let Query = _Query;
1058
1269
  _table$1 = new WeakMap();
1059
1270
  _repository = new WeakMap();
1060
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
+ }
1061
1278
 
1062
1279
  function isIdentifiable(x) {
1063
1280
  return isObject(x) && isString(x?.id);
1064
1281
  }
1065
1282
  function isXataRecord(x) {
1066
- 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";
1067
1286
  }
1068
1287
 
1069
1288
  function isSortFilterString(value) {
@@ -1093,7 +1312,7 @@ var __accessCheck$4 = (obj, member, msg) => {
1093
1312
  if (!member.has(obj))
1094
1313
  throw TypeError("Cannot " + msg);
1095
1314
  };
1096
- var __privateGet$3 = (obj, member, getter) => {
1315
+ var __privateGet$4 = (obj, member, getter) => {
1097
1316
  __accessCheck$4(obj, member, "read from private field");
1098
1317
  return getter ? getter.call(obj) : member.get(obj);
1099
1318
  };
@@ -1102,7 +1321,7 @@ var __privateAdd$4 = (obj, member, value) => {
1102
1321
  throw TypeError("Cannot add the same private member more than once");
1103
1322
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1104
1323
  };
1105
- var __privateSet$2 = (obj, member, value, setter) => {
1324
+ var __privateSet$4 = (obj, member, value, setter) => {
1106
1325
  __accessCheck$4(obj, member, "write to private field");
1107
1326
  setter ? setter.call(obj, value) : member.set(obj, value);
1108
1327
  return value;
@@ -1111,7 +1330,7 @@ var __privateMethod$2 = (obj, member, method) => {
1111
1330
  __accessCheck$4(obj, member, "access private method");
1112
1331
  return method;
1113
1332
  };
1114
- var _table, _links, _getFetchProps, _cache, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _invalidateCache, invalidateCache_fn, _setCacheRecord, setCacheRecord_fn, _getCacheRecord, getCacheRecord_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn;
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;
1115
1334
  class Repository extends Query {
1116
1335
  }
1117
1336
  class RestRepository extends Query {
@@ -1128,18 +1347,21 @@ class RestRepository extends Query {
1128
1347
  __privateAdd$4(this, _getCacheRecord);
1129
1348
  __privateAdd$4(this, _setCacheQuery);
1130
1349
  __privateAdd$4(this, _getCacheQuery);
1350
+ __privateAdd$4(this, _getSchemaTables$1);
1131
1351
  __privateAdd$4(this, _table, void 0);
1132
- __privateAdd$4(this, _links, void 0);
1133
1352
  __privateAdd$4(this, _getFetchProps, void 0);
1134
1353
  __privateAdd$4(this, _cache, void 0);
1135
- __privateSet$2(this, _table, options.table);
1136
- __privateSet$2(this, _links, options.links ?? {});
1137
- __privateSet$2(this, _getFetchProps, options.pluginOptions.getFetchProps);
1354
+ __privateAdd$4(this, _schemaTables$2, void 0);
1355
+ __privateSet$4(this, _table, options.table);
1356
+ __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1138
1357
  this.db = options.db;
1139
- __privateSet$2(this, _cache, options.pluginOptions.cache);
1358
+ __privateSet$4(this, _cache, options.pluginOptions.cache);
1359
+ __privateSet$4(this, _schemaTables$2, options.schemaTables);
1140
1360
  }
1141
1361
  async create(a, b) {
1142
1362
  if (Array.isArray(a)) {
1363
+ if (a.length === 0)
1364
+ return [];
1143
1365
  const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1144
1366
  await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1145
1367
  return records;
@@ -1165,26 +1387,38 @@ class RestRepository extends Query {
1165
1387
  }
1166
1388
  throw new Error("Invalid arguments for create method");
1167
1389
  }
1168
- async read(recordId) {
1169
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, recordId);
1170
- if (cacheRecord)
1171
- return cacheRecord;
1172
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1173
- try {
1174
- const response = await getRecord({
1175
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1176
- ...fetchProps
1177
- });
1178
- return initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), response);
1179
- } catch (e) {
1180
- if (isObject(e) && e.status === 404) {
1181
- 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;
1182
1415
  }
1183
- throw e;
1184
1416
  }
1185
1417
  }
1186
1418
  async update(a, b) {
1187
1419
  if (Array.isArray(a)) {
1420
+ if (a.length === 0)
1421
+ return [];
1188
1422
  if (a.length > 100) {
1189
1423
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1190
1424
  }
@@ -1206,6 +1440,8 @@ class RestRepository extends Query {
1206
1440
  }
1207
1441
  async createOrUpdate(a, b) {
1208
1442
  if (Array.isArray(a)) {
1443
+ if (a.length === 0)
1444
+ return [];
1209
1445
  if (a.length > 100) {
1210
1446
  console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1211
1447
  }
@@ -1227,6 +1463,8 @@ class RestRepository extends Query {
1227
1463
  }
1228
1464
  async delete(a) {
1229
1465
  if (Array.isArray(a)) {
1466
+ if (a.length === 0)
1467
+ return;
1230
1468
  if (a.length > 100) {
1231
1469
  console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1232
1470
  }
@@ -1246,13 +1484,19 @@ class RestRepository extends Query {
1246
1484
  throw new Error("Invalid arguments for delete method");
1247
1485
  }
1248
1486
  async search(query, options = {}) {
1249
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1250
- const { records } = await searchBranch({
1251
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1252
- body: { tables: [__privateGet$3(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
+ },
1253
1496
  ...fetchProps
1254
1497
  });
1255
- return records.map((item) => initObject(this.db, __privateGet$3(this, _links), __privateGet$3(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));
1256
1500
  }
1257
1501
  async query(query) {
1258
1502
  const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
@@ -1261,34 +1505,35 @@ class RestRepository extends Query {
1261
1505
  const data = query.getQueryOptions();
1262
1506
  const body = {
1263
1507
  filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1264
- sort: data.sort ? buildSortFilter(data.sort) : void 0,
1265
- page: data.page,
1508
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1509
+ page: data.pagination,
1266
1510
  columns: data.columns
1267
1511
  };
1268
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1512
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1269
1513
  const { meta, records: objects } = await queryTable({
1270
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table) },
1514
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1271
1515
  body,
1272
1516
  ...fetchProps
1273
1517
  });
1274
- const records = objects.map((record) => initObject(this.db, __privateGet$3(this, _links), __privateGet$3(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));
1275
1520
  await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1276
1521
  return new Page(query, meta, records);
1277
1522
  }
1278
1523
  }
1279
1524
  _table = new WeakMap();
1280
- _links = new WeakMap();
1281
1525
  _getFetchProps = new WeakMap();
1282
1526
  _cache = new WeakMap();
1527
+ _schemaTables$2 = new WeakMap();
1283
1528
  _insertRecordWithoutId = new WeakSet();
1284
1529
  insertRecordWithoutId_fn = async function(object) {
1285
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1530
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1286
1531
  const record = transformObjectLinks(object);
1287
1532
  const response = await insertRecord({
1288
1533
  pathParams: {
1289
1534
  workspace: "{workspaceId}",
1290
1535
  dbBranchName: "{dbBranch}",
1291
- tableName: __privateGet$3(this, _table)
1536
+ tableName: __privateGet$4(this, _table)
1292
1537
  },
1293
1538
  body: record,
1294
1539
  ...fetchProps
@@ -1301,13 +1546,13 @@ insertRecordWithoutId_fn = async function(object) {
1301
1546
  };
1302
1547
  _insertRecordWithId = new WeakSet();
1303
1548
  insertRecordWithId_fn = async function(recordId, object) {
1304
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1549
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1305
1550
  const record = transformObjectLinks(object);
1306
1551
  const response = await insertRecordWithID({
1307
1552
  pathParams: {
1308
1553
  workspace: "{workspaceId}",
1309
1554
  dbBranchName: "{dbBranch}",
1310
- tableName: __privateGet$3(this, _table),
1555
+ tableName: __privateGet$4(this, _table),
1311
1556
  recordId
1312
1557
  },
1313
1558
  body: record,
@@ -1322,25 +1567,29 @@ insertRecordWithId_fn = async function(recordId, object) {
1322
1567
  };
1323
1568
  _bulkInsertTableRecords = new WeakSet();
1324
1569
  bulkInsertTableRecords_fn = async function(objects) {
1325
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1570
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1326
1571
  const records = objects.map((object) => transformObjectLinks(object));
1327
- const response = await bulkInsertTableRecords({
1328
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table) },
1572
+ const { recordIDs } = await bulkInsertTableRecords({
1573
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1329
1574
  body: { records },
1330
1575
  ...fetchProps
1331
1576
  });
1332
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1577
+ const finalObjects = await this.read(recordIDs);
1333
1578
  if (finalObjects.length !== objects.length) {
1334
1579
  throw new Error("The server failed to save some records");
1335
1580
  }
1336
- 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]);
1337
1586
  };
1338
1587
  _updateRecordWithID = new WeakSet();
1339
1588
  updateRecordWithID_fn = async function(recordId, object) {
1340
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1589
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1341
1590
  const record = transformObjectLinks(object);
1342
1591
  const response = await updateRecordWithID({
1343
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1592
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1344
1593
  body: record,
1345
1594
  ...fetchProps
1346
1595
  });
@@ -1351,9 +1600,9 @@ updateRecordWithID_fn = async function(recordId, object) {
1351
1600
  };
1352
1601
  _upsertRecordWithID = new WeakSet();
1353
1602
  upsertRecordWithID_fn = async function(recordId, object) {
1354
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1603
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1355
1604
  const response = await upsertRecordWithID({
1356
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1605
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1357
1606
  body: object,
1358
1607
  ...fetchProps
1359
1608
  });
@@ -1364,51 +1613,63 @@ upsertRecordWithID_fn = async function(recordId, object) {
1364
1613
  };
1365
1614
  _deleteRecord = new WeakSet();
1366
1615
  deleteRecord_fn = async function(recordId) {
1367
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1616
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1368
1617
  await deleteRecord({
1369
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1618
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1370
1619
  ...fetchProps
1371
1620
  });
1372
1621
  };
1373
1622
  _invalidateCache = new WeakSet();
1374
1623
  invalidateCache_fn = async function(recordId) {
1375
- await __privateGet$3(this, _cache).delete(`rec_${__privateGet$3(this, _table)}:${recordId}`);
1376
- const cacheItems = await __privateGet$3(this, _cache).getAll();
1624
+ await __privateGet$4(this, _cache).delete(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1625
+ const cacheItems = await __privateGet$4(this, _cache).getAll();
1377
1626
  const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1378
1627
  for (const [key, value] of queries) {
1379
1628
  const ids = getIds(value);
1380
1629
  if (ids.includes(recordId))
1381
- await __privateGet$3(this, _cache).delete(key);
1630
+ await __privateGet$4(this, _cache).delete(key);
1382
1631
  }
1383
1632
  };
1384
1633
  _setCacheRecord = new WeakSet();
1385
1634
  setCacheRecord_fn = async function(record) {
1386
- if (!__privateGet$3(this, _cache).cacheRecords)
1635
+ if (!__privateGet$4(this, _cache).cacheRecords)
1387
1636
  return;
1388
- await __privateGet$3(this, _cache).set(`rec_${__privateGet$3(this, _table)}:${record.id}`, record);
1637
+ await __privateGet$4(this, _cache).set(`rec_${__privateGet$4(this, _table)}:${record.id}`, record);
1389
1638
  };
1390
1639
  _getCacheRecord = new WeakSet();
1391
1640
  getCacheRecord_fn = async function(recordId) {
1392
- if (!__privateGet$3(this, _cache).cacheRecords)
1641
+ if (!__privateGet$4(this, _cache).cacheRecords)
1393
1642
  return null;
1394
- return __privateGet$3(this, _cache).get(`rec_${__privateGet$3(this, _table)}:${recordId}`);
1643
+ return __privateGet$4(this, _cache).get(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1395
1644
  };
1396
1645
  _setCacheQuery = new WeakSet();
1397
1646
  setCacheQuery_fn = async function(query, meta, records) {
1398
- await __privateGet$3(this, _cache).set(`query_${__privateGet$3(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1647
+ await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1399
1648
  };
1400
1649
  _getCacheQuery = new WeakSet();
1401
1650
  getCacheQuery_fn = async function(query) {
1402
- const key = `query_${__privateGet$3(this, _table)}:${query.key()}`;
1403
- const result = await __privateGet$3(this, _cache).get(key);
1651
+ const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
1652
+ const result = await __privateGet$4(this, _cache).get(key);
1404
1653
  if (!result)
1405
1654
  return null;
1406
- const { cache: ttl = __privateGet$3(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1407
- if (!ttl || ttl < 0)
1408
- return result;
1655
+ const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1656
+ if (ttl < 0)
1657
+ return null;
1409
1658
  const hasExpired = result.date.getTime() + ttl < Date.now();
1410
1659
  return hasExpired ? null : result;
1411
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}" },
1668
+ ...fetchProps
1669
+ });
1670
+ __privateSet$4(this, _schemaTables$2, schema.tables);
1671
+ return schema.tables;
1672
+ };
1412
1673
  const transformObjectLinks = (object) => {
1413
1674
  return Object.entries(object).reduce((acc, [key, value]) => {
1414
1675
  if (key === "xata")
@@ -1416,15 +1677,34 @@ const transformObjectLinks = (object) => {
1416
1677
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1417
1678
  }, {});
1418
1679
  };
1419
- const initObject = (db, links, table, object) => {
1680
+ const initObject = (db, schemaTables, table, object) => {
1420
1681
  const result = {};
1421
- Object.assign(result, object);
1422
- const tableLinks = links[table] || [];
1423
- for (const link of tableLinks) {
1424
- const [field, linkTable] = link;
1425
- const value = result[field];
1426
- if (value && isObject(value)) {
1427
- 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
+ }
1428
1708
  }
1429
1709
  }
1430
1710
  result.read = function() {
@@ -1436,7 +1716,10 @@ const initObject = (db, links, table, object) => {
1436
1716
  result.delete = function() {
1437
1717
  return db[table].delete(result["id"]);
1438
1718
  };
1439
- for (const prop of ["read", "update", "delete"]) {
1719
+ result.getMetadata = function() {
1720
+ return xata;
1721
+ };
1722
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1440
1723
  Object.defineProperty(result, prop, { enumerable: false });
1441
1724
  }
1442
1725
  Object.freeze(result);
@@ -1456,7 +1739,7 @@ var __accessCheck$3 = (obj, member, msg) => {
1456
1739
  if (!member.has(obj))
1457
1740
  throw TypeError("Cannot " + msg);
1458
1741
  };
1459
- var __privateGet$2 = (obj, member, getter) => {
1742
+ var __privateGet$3 = (obj, member, getter) => {
1460
1743
  __accessCheck$3(obj, member, "read from private field");
1461
1744
  return getter ? getter.call(obj) : member.get(obj);
1462
1745
  };
@@ -1465,7 +1748,7 @@ var __privateAdd$3 = (obj, member, value) => {
1465
1748
  throw TypeError("Cannot add the same private member more than once");
1466
1749
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1467
1750
  };
1468
- var __privateSet$1 = (obj, member, value, setter) => {
1751
+ var __privateSet$3 = (obj, member, value, setter) => {
1469
1752
  __accessCheck$3(obj, member, "write to private field");
1470
1753
  setter ? setter.call(obj, value) : member.set(obj, value);
1471
1754
  return value;
@@ -1474,30 +1757,30 @@ var _map;
1474
1757
  class SimpleCache {
1475
1758
  constructor(options = {}) {
1476
1759
  __privateAdd$3(this, _map, void 0);
1477
- __privateSet$1(this, _map, /* @__PURE__ */ new Map());
1760
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1478
1761
  this.capacity = options.max ?? 500;
1479
1762
  this.cacheRecords = options.cacheRecords ?? true;
1480
1763
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1481
1764
  }
1482
1765
  async getAll() {
1483
- return Object.fromEntries(__privateGet$2(this, _map));
1766
+ return Object.fromEntries(__privateGet$3(this, _map));
1484
1767
  }
1485
1768
  async get(key) {
1486
- return __privateGet$2(this, _map).get(key) ?? null;
1769
+ return __privateGet$3(this, _map).get(key) ?? null;
1487
1770
  }
1488
1771
  async set(key, value) {
1489
1772
  await this.delete(key);
1490
- __privateGet$2(this, _map).set(key, value);
1491
- if (__privateGet$2(this, _map).size > this.capacity) {
1492
- const leastRecentlyUsed = __privateGet$2(this, _map).keys().next().value;
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;
1493
1776
  await this.delete(leastRecentlyUsed);
1494
1777
  }
1495
1778
  }
1496
1779
  async delete(key) {
1497
- __privateGet$2(this, _map).delete(key);
1780
+ __privateGet$3(this, _map).delete(key);
1498
1781
  }
1499
1782
  async clear() {
1500
- return __privateGet$2(this, _map).clear();
1783
+ return __privateGet$3(this, _map).clear();
1501
1784
  }
1502
1785
  }
1503
1786
  _map = new WeakMap();
@@ -1525,7 +1808,7 @@ var __accessCheck$2 = (obj, member, msg) => {
1525
1808
  if (!member.has(obj))
1526
1809
  throw TypeError("Cannot " + msg);
1527
1810
  };
1528
- var __privateGet$1 = (obj, member, getter) => {
1811
+ var __privateGet$2 = (obj, member, getter) => {
1529
1812
  __accessCheck$2(obj, member, "read from private field");
1530
1813
  return getter ? getter.call(obj) : member.get(obj);
1531
1814
  };
@@ -1534,122 +1817,158 @@ var __privateAdd$2 = (obj, member, value) => {
1534
1817
  throw TypeError("Cannot add the same private member more than once");
1535
1818
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1536
1819
  };
1537
- 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;
1538
1826
  class SchemaPlugin extends XataPlugin {
1539
- constructor(links, tableNames) {
1827
+ constructor(schemaTables) {
1540
1828
  super();
1541
- this.links = links;
1542
- this.tableNames = tableNames;
1543
1829
  __privateAdd$2(this, _tables, {});
1830
+ __privateAdd$2(this, _schemaTables$1, void 0);
1831
+ __privateSet$2(this, _schemaTables$1, schemaTables);
1544
1832
  }
1545
1833
  build(pluginOptions) {
1546
- const links = this.links;
1547
1834
  const db = new Proxy({}, {
1548
1835
  get: (_target, table) => {
1549
1836
  if (!isString(table))
1550
1837
  throw new Error("Invalid table name");
1551
- if (!__privateGet$1(this, _tables)[table]) {
1552
- __privateGet$1(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, links });
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) });
1553
1840
  }
1554
- return __privateGet$1(this, _tables)[table];
1841
+ return __privateGet$2(this, _tables)[table];
1555
1842
  }
1556
1843
  });
1557
- for (const table of this.tableNames ?? []) {
1558
- db[table] = new RestRepository({ db, pluginOptions, 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) });
1559
1847
  }
1560
1848
  return db;
1561
1849
  }
1562
1850
  }
1563
1851
  _tables = new WeakMap();
1852
+ _schemaTables$1 = new WeakMap();
1564
1853
 
1565
1854
  var __accessCheck$1 = (obj, member, msg) => {
1566
1855
  if (!member.has(obj))
1567
1856
  throw TypeError("Cannot " + msg);
1568
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
+ };
1569
1862
  var __privateAdd$1 = (obj, member, value) => {
1570
1863
  if (member.has(obj))
1571
1864
  throw TypeError("Cannot add the same private member more than once");
1572
1865
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1573
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
+ };
1574
1872
  var __privateMethod$1 = (obj, member, method) => {
1575
1873
  __accessCheck$1(obj, member, "access private method");
1576
1874
  return method;
1577
1875
  };
1578
- var _search, search_fn;
1876
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1579
1877
  class SearchPlugin extends XataPlugin {
1580
- constructor(db, links) {
1878
+ constructor(db, schemaTables) {
1581
1879
  super();
1582
1880
  this.db = db;
1583
- this.links = links;
1584
1881
  __privateAdd$1(this, _search);
1882
+ __privateAdd$1(this, _getSchemaTables);
1883
+ __privateAdd$1(this, _schemaTables, void 0);
1884
+ __privateSet$1(this, _schemaTables, schemaTables);
1585
1885
  }
1586
1886
  build({ getFetchProps }) {
1587
1887
  return {
1588
1888
  all: async (query, options = {}) => {
1589
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);
1590
1891
  return records.map((record) => {
1591
1892
  const { table = "orphan" } = record.xata;
1592
- return { table, record: initObject(this.db, this.links, table, record) };
1893
+ return { table, record: initObject(this.db, schemaTables, table, record) };
1593
1894
  });
1594
1895
  },
1595
1896
  byTable: async (query, options = {}) => {
1596
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);
1597
1899
  return records.reduce((acc, record) => {
1598
1900
  const { table = "orphan" } = record.xata;
1599
1901
  const items = acc[table] ?? [];
1600
- const item = initObject(this.db, this.links, table, record);
1902
+ const item = initObject(this.db, schemaTables, table, record);
1601
1903
  return { ...acc, [table]: [...items, item] };
1602
1904
  }, {});
1603
1905
  }
1604
1906
  };
1605
1907
  }
1606
1908
  }
1909
+ _schemaTables = new WeakMap();
1607
1910
  _search = new WeakSet();
1608
1911
  search_fn = async function(query, options, getFetchProps) {
1609
1912
  const fetchProps = await getFetchProps();
1610
- const { tables, fuzziness } = options ?? {};
1913
+ const { tables, fuzziness, highlight } = options ?? {};
1611
1914
  const { records } = await searchBranch({
1612
1915
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1613
- body: { tables, query, fuzziness },
1916
+ body: { tables, query, fuzziness, highlight },
1614
1917
  ...fetchProps
1615
1918
  });
1616
1919
  return records;
1617
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
+ };
1618
1933
 
1619
1934
  const isBranchStrategyBuilder = (strategy) => {
1620
1935
  return typeof strategy === "function";
1621
1936
  };
1622
1937
 
1623
- const envBranchNames = [
1624
- "XATA_BRANCH",
1625
- "VERCEL_GIT_COMMIT_REF",
1626
- "CF_PAGES_BRANCH",
1627
- "BRANCH"
1628
- ];
1629
- const defaultBranch = "main";
1630
1938
  async function getCurrentBranchName(options) {
1631
- const env = await getBranchByEnvVariable();
1632
- if (env)
1633
- return env;
1634
- const branch = await getGitBranch();
1635
- if (!branch)
1636
- return defaultBranch;
1637
- const details = await getDatabaseBranch(branch, options);
1638
- if (details)
1639
- return branch;
1640
- 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);
1641
1948
  }
1642
1949
  async function getCurrentBranchDetails(options) {
1643
- const env = await getBranchByEnvVariable();
1644
- if (env)
1645
- return getDatabaseBranch(env, options);
1646
- const branch = await getGitBranch();
1647
- if (!branch)
1648
- return getDatabaseBranch(defaultBranch, options);
1649
- const details = await getDatabaseBranch(branch, options);
1650
- if (details)
1651
- return details;
1652
- 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;
1653
1972
  }
1654
1973
  async function getDatabaseBranch(branch, options) {
1655
1974
  const databaseURL = options?.databaseURL || getDatabaseURL();
@@ -1667,10 +1986,7 @@ async function getDatabaseBranch(branch, options) {
1667
1986
  apiUrl: databaseURL,
1668
1987
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1669
1988
  workspacesApiUrl: `${protocol}//${host}`,
1670
- pathParams: {
1671
- dbBranchName,
1672
- workspace
1673
- }
1989
+ pathParams: { dbBranchName, workspace }
1674
1990
  });
1675
1991
  } catch (err) {
1676
1992
  if (isObject(err) && err.status === 404)
@@ -1678,21 +1994,10 @@ async function getDatabaseBranch(branch, options) {
1678
1994
  throw err;
1679
1995
  }
1680
1996
  }
1681
- function getBranchByEnvVariable() {
1682
- for (const name of envBranchNames) {
1683
- const value = getEnvVariable(name);
1684
- if (value) {
1685
- return value;
1686
- }
1687
- }
1688
- try {
1689
- return XATA_BRANCH;
1690
- } catch (err) {
1691
- }
1692
- }
1693
1997
  function getDatabaseURL() {
1694
1998
  try {
1695
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
1999
+ const { databaseURL } = getEnvironment();
2000
+ return databaseURL;
1696
2001
  } catch (err) {
1697
2002
  return void 0;
1698
2003
  }
@@ -1723,7 +2028,7 @@ var __privateMethod = (obj, member, method) => {
1723
2028
  const buildClient = (plugins) => {
1724
2029
  var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1725
2030
  return _a = class {
1726
- constructor(options = {}, links, tables) {
2031
+ constructor(options = {}, schemaTables) {
1727
2032
  __privateAdd(this, _parseOptions);
1728
2033
  __privateAdd(this, _getFetchProps);
1729
2034
  __privateAdd(this, _evaluateBranch);
@@ -1733,12 +2038,12 @@ const buildClient = (plugins) => {
1733
2038
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1734
2039
  cache: safeOptions.cache
1735
2040
  };
1736
- const db = new SchemaPlugin(links, tables).build(pluginOptions);
1737
- const search = new SearchPlugin(db, links ?? {}).build(pluginOptions);
2041
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2042
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1738
2043
  this.db = db;
1739
2044
  this.search = search;
1740
2045
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
1741
- if (!namespace)
2046
+ if (namespace === void 0)
1742
2047
  continue;
1743
2048
  const result = namespace.build(pluginOptions);
1744
2049
  if (result instanceof Promise) {
@@ -1755,7 +2060,7 @@ const buildClient = (plugins) => {
1755
2060
  const databaseURL = options?.databaseURL || getDatabaseURL();
1756
2061
  const apiKey = options?.apiKey || getAPIKey();
1757
2062
  const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
1758
- const branch = async () => options?.branch ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
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 });
1759
2064
  if (!databaseURL || !apiKey) {
1760
2065
  throw new Error("Options databaseURL and apiKey are required");
1761
2066
  }
@@ -1782,7 +2087,7 @@ const buildClient = (plugins) => {
1782
2087
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1783
2088
  if (__privateGet(this, _branch))
1784
2089
  return __privateGet(this, _branch);
1785
- if (!param)
2090
+ if (param === void 0)
1786
2091
  return void 0;
1787
2092
  const strategies = Array.isArray(param) ? [...param] : [param];
1788
2093
  const evaluateBranch = async (strategy) => {
@@ -1800,6 +2105,88 @@ const buildClient = (plugins) => {
1800
2105
  class BaseClient extends buildClient() {
1801
2106
  }
1802
2107
 
2108
+ const META = "__";
2109
+ const VALUE = "___";
2110
+ class Serializer {
2111
+ constructor() {
2112
+ this.classes = {};
2113
+ }
2114
+ add(clazz) {
2115
+ this.classes[clazz.name] = clazz;
2116
+ }
2117
+ toJSON(data) {
2118
+ function visit(obj) {
2119
+ if (Array.isArray(obj))
2120
+ return obj.map(visit);
2121
+ const type = typeof obj;
2122
+ if (type === "undefined")
2123
+ return { [META]: "undefined" };
2124
+ if (type === "bigint")
2125
+ return { [META]: "bigint", [VALUE]: obj.toString() };
2126
+ if (obj === null || type !== "object")
2127
+ return obj;
2128
+ const constructor = obj.constructor;
2129
+ const o = { [META]: constructor.name };
2130
+ for (const [key, value] of Object.entries(obj)) {
2131
+ o[key] = visit(value);
2132
+ }
2133
+ if (constructor === Date)
2134
+ o[VALUE] = obj.toISOString();
2135
+ if (constructor === Map)
2136
+ o[VALUE] = Object.fromEntries(obj);
2137
+ if (constructor === Set)
2138
+ o[VALUE] = [...obj];
2139
+ return o;
2140
+ }
2141
+ return JSON.stringify(visit(data));
2142
+ }
2143
+ fromJSON(json) {
2144
+ return JSON.parse(json, (key, value) => {
2145
+ if (value && typeof value === "object" && !Array.isArray(value)) {
2146
+ const { [META]: clazz, [VALUE]: val, ...rest } = value;
2147
+ const constructor = this.classes[clazz];
2148
+ if (constructor) {
2149
+ return Object.assign(Object.create(constructor.prototype), rest);
2150
+ }
2151
+ if (clazz === "Date")
2152
+ return new Date(val);
2153
+ if (clazz === "Set")
2154
+ return new Set(val);
2155
+ if (clazz === "Map")
2156
+ return new Map(Object.entries(val));
2157
+ if (clazz === "bigint")
2158
+ return BigInt(val);
2159
+ if (clazz === "undefined")
2160
+ return void 0;
2161
+ return rest;
2162
+ }
2163
+ return value;
2164
+ });
2165
+ }
2166
+ }
2167
+ const serialize = () => {
2168
+ throw new Error("Not implemented");
2169
+ };
2170
+ const deserialize = () => {
2171
+ throw new Error("Not implemented");
2172
+ };
2173
+
2174
+ function buildWorkerRunner(config) {
2175
+ return function xataWorker(name, _worker) {
2176
+ return async (...args) => {
2177
+ const result = await fetch("http://localhost:64749", {
2178
+ method: "POST",
2179
+ headers: { "Content-Type": "application/json" },
2180
+ body: JSON.stringify({
2181
+ name,
2182
+ payload: args
2183
+ })
2184
+ });
2185
+ return result.json();
2186
+ };
2187
+ };
2188
+ }
2189
+
1803
2190
  class XataError extends Error {
1804
2191
  constructor(message, status) {
1805
2192
  super(message);
@@ -1815,18 +2202,22 @@ exports.PAGINATION_MAX_OFFSET = PAGINATION_MAX_OFFSET;
1815
2202
  exports.PAGINATION_MAX_SIZE = PAGINATION_MAX_SIZE;
1816
2203
  exports.Page = Page;
1817
2204
  exports.Query = Query;
2205
+ exports.RecordArray = RecordArray;
1818
2206
  exports.Repository = Repository;
1819
2207
  exports.RestRepository = RestRepository;
1820
2208
  exports.SchemaPlugin = SchemaPlugin;
1821
2209
  exports.SearchPlugin = SearchPlugin;
2210
+ exports.Serializer = Serializer;
1822
2211
  exports.SimpleCache = SimpleCache;
1823
2212
  exports.XataApiClient = XataApiClient;
1824
2213
  exports.XataApiPlugin = XataApiPlugin;
1825
2214
  exports.XataError = XataError;
1826
2215
  exports.XataPlugin = XataPlugin;
1827
2216
  exports.acceptWorkspaceMemberInvite = acceptWorkspaceMemberInvite;
2217
+ exports.addGitBranchesEntry = addGitBranchesEntry;
1828
2218
  exports.addTableColumn = addTableColumn;
1829
2219
  exports.buildClient = buildClient;
2220
+ exports.buildWorkerRunner = buildWorkerRunner;
1830
2221
  exports.bulkInsertTableRecords = bulkInsertTableRecords;
1831
2222
  exports.cancelWorkspaceMemberInvite = cancelWorkspaceMemberInvite;
1832
2223
  exports.contains = contains;
@@ -1843,6 +2234,7 @@ exports.deleteTable = deleteTable;
1843
2234
  exports.deleteUser = deleteUser;
1844
2235
  exports.deleteUserAPIKey = deleteUserAPIKey;
1845
2236
  exports.deleteWorkspace = deleteWorkspace;
2237
+ exports.deserialize = deserialize;
1846
2238
  exports.endsWith = endsWith;
1847
2239
  exports.executeBranchMigrationPlan = executeBranchMigrationPlan;
1848
2240
  exports.exists = exists;
@@ -1859,6 +2251,7 @@ exports.getCurrentBranchDetails = getCurrentBranchDetails;
1859
2251
  exports.getCurrentBranchName = getCurrentBranchName;
1860
2252
  exports.getDatabaseList = getDatabaseList;
1861
2253
  exports.getDatabaseURL = getDatabaseURL;
2254
+ exports.getGitBranchesMapping = getGitBranchesMapping;
1862
2255
  exports.getRecord = getRecord;
1863
2256
  exports.getTableColumns = getTableColumns;
1864
2257
  exports.getTableSchema = getTableSchema;
@@ -1877,6 +2270,7 @@ exports.insertRecord = insertRecord;
1877
2270
  exports.insertRecordWithID = insertRecordWithID;
1878
2271
  exports.inviteWorkspaceMember = inviteWorkspaceMember;
1879
2272
  exports.is = is;
2273
+ exports.isCursorPaginationOptions = isCursorPaginationOptions;
1880
2274
  exports.isIdentifiable = isIdentifiable;
1881
2275
  exports.isNot = isNot;
1882
2276
  exports.isXataRecord = isXataRecord;
@@ -1887,9 +2281,13 @@ exports.notExists = notExists;
1887
2281
  exports.operationsByTag = operationsByTag;
1888
2282
  exports.pattern = pattern;
1889
2283
  exports.queryTable = queryTable;
2284
+ exports.removeGitBranchesEntry = removeGitBranchesEntry;
1890
2285
  exports.removeWorkspaceMember = removeWorkspaceMember;
1891
2286
  exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite;
2287
+ exports.resolveBranch = resolveBranch;
1892
2288
  exports.searchBranch = searchBranch;
2289
+ exports.searchTable = searchTable;
2290
+ exports.serialize = serialize;
1893
2291
  exports.setTableSchema = setTableSchema;
1894
2292
  exports.startsWith = startsWith;
1895
2293
  exports.updateBranchMetadata = updateBranchMetadata;
@@ -1898,6 +2296,7 @@ exports.updateRecordWithID = updateRecordWithID;
1898
2296
  exports.updateTable = updateTable;
1899
2297
  exports.updateUser = updateUser;
1900
2298
  exports.updateWorkspace = updateWorkspace;
2299
+ exports.updateWorkspaceMemberInvite = updateWorkspaceMemberInvite;
1901
2300
  exports.updateWorkspaceMemberRole = updateWorkspaceMemberRole;
1902
2301
  exports.upsertRecordWithID = upsertRecordWithID;
1903
2302
  //# sourceMappingURL=index.cjs.map