@xata.io/client 0.0.0-alpha.vfde9dcf → 0.0.0-alpha.vfeb24b1

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,48 @@
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
+
23
+ const defaultTrace = async (_name, fn, _options) => {
24
+ return await fn({
25
+ setAttributes: () => {
26
+ return;
27
+ },
28
+ onError: () => {
29
+ return;
30
+ }
31
+ });
32
+ };
33
+ const TraceAttributes = {
34
+ VERSION: "xata.sdk.version",
35
+ TABLE: "xata.table",
36
+ HTTP_REQUEST_ID: "http.request_id",
37
+ HTTP_STATUS_CODE: "http.status_code",
38
+ HTTP_HOST: "http.host",
39
+ HTTP_SCHEME: "http.scheme",
40
+ HTTP_USER_AGENT: "http.user_agent",
41
+ HTTP_METHOD: "http.method",
42
+ HTTP_URL: "http.url",
43
+ HTTP_ROUTE: "http.route",
44
+ HTTP_TARGET: "http.target"
45
+ };
46
+
5
47
  function notEmpty(value) {
6
48
  return value !== null && value !== void 0;
7
49
  }
@@ -17,43 +59,95 @@ function isDefined(value) {
17
59
  function isString(value) {
18
60
  return isDefined(value) && typeof value === "string";
19
61
  }
62
+ function isStringArray(value) {
63
+ return isDefined(value) && Array.isArray(value) && value.every(isString);
64
+ }
20
65
  function toBase64(value) {
21
66
  try {
22
67
  return btoa(value);
23
68
  } catch (err) {
24
- return Buffer.from(value).toString("base64");
69
+ const buf = Buffer;
70
+ return buf.from(value).toString("base64");
25
71
  }
26
72
  }
27
73
 
28
- function getEnvVariable(name) {
74
+ function getEnvironment() {
29
75
  try {
30
- if (isObject(process) && isString(process?.env?.[name])) {
31
- return process.env[name];
76
+ if (isObject(process) && isObject(process.env)) {
77
+ return {
78
+ apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
79
+ databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
80
+ branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
81
+ envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
82
+ fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
83
+ };
32
84
  }
33
85
  } catch (err) {
34
86
  }
35
87
  try {
36
- if (isObject(Deno) && isString(Deno?.env?.get(name))) {
37
- return Deno.env.get(name);
88
+ if (isObject(Deno) && isObject(Deno.env)) {
89
+ return {
90
+ apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
91
+ databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
92
+ branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
93
+ envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
94
+ fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
95
+ };
38
96
  }
39
97
  } catch (err) {
40
98
  }
99
+ return {
100
+ apiKey: getGlobalApiKey(),
101
+ databaseURL: getGlobalDatabaseURL(),
102
+ branch: getGlobalBranch(),
103
+ envBranch: void 0,
104
+ fallbackBranch: getGlobalFallbackBranch()
105
+ };
106
+ }
107
+ function getGlobalApiKey() {
108
+ try {
109
+ return XATA_API_KEY;
110
+ } catch (err) {
111
+ return void 0;
112
+ }
113
+ }
114
+ function getGlobalDatabaseURL() {
115
+ try {
116
+ return XATA_DATABASE_URL;
117
+ } catch (err) {
118
+ return void 0;
119
+ }
120
+ }
121
+ function getGlobalBranch() {
122
+ try {
123
+ return XATA_BRANCH;
124
+ } catch (err) {
125
+ return void 0;
126
+ }
127
+ }
128
+ function getGlobalFallbackBranch() {
129
+ try {
130
+ return XATA_FALLBACK_BRANCH;
131
+ } catch (err) {
132
+ return void 0;
133
+ }
41
134
  }
42
135
  async function getGitBranch() {
136
+ const cmd = ["git", "branch", "--show-current"];
137
+ const fullCmd = cmd.join(" ");
138
+ const nodeModule = ["child", "process"].join("_");
139
+ const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
43
140
  try {
44
141
  if (typeof require === "function") {
45
- const req = require;
46
- return req("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
142
+ return require(nodeModule).execSync(fullCmd, execOptions).trim();
47
143
  }
144
+ const { execSync } = await (function (t) { return Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require(t)); }); })(nodeModule);
145
+ return execSync(fullCmd, execOptions).toString().trim();
48
146
  } catch (err) {
49
147
  }
50
148
  try {
51
149
  if (isObject(Deno)) {
52
- const process2 = Deno.run({
53
- cmd: ["git", "branch", "--show-current"],
54
- stdout: "piped",
55
- stderr: "piped"
56
- });
150
+ const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
57
151
  return new TextDecoder().decode(await process2.output()).trim();
58
152
  }
59
153
  } catch (err) {
@@ -62,7 +156,8 @@ async function getGitBranch() {
62
156
 
63
157
  function getAPIKey() {
64
158
  try {
65
- return getEnvVariable("XATA_API_KEY") ?? XATA_API_KEY;
159
+ const { apiKey } = getEnvironment();
160
+ return apiKey;
66
161
  } catch (err) {
67
162
  return void 0;
68
163
  }
@@ -72,21 +167,35 @@ function getFetchImplementation(userFetch) {
72
167
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
73
168
  const fetchImpl = userFetch ?? globalFetch;
74
169
  if (!fetchImpl) {
75
- throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
170
+ throw new Error(
171
+ `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
172
+ );
76
173
  }
77
174
  return fetchImpl;
78
175
  }
79
176
 
80
- class FetcherError extends Error {
81
- constructor(status, data) {
177
+ const VERSION = "0.0.0-alpha.vfeb24b1";
178
+
179
+ class ErrorWithCause extends Error {
180
+ constructor(message, options) {
181
+ super(message, options);
182
+ }
183
+ }
184
+ class FetcherError extends ErrorWithCause {
185
+ constructor(status, data, requestId) {
82
186
  super(getMessage(data));
83
187
  this.status = status;
84
188
  this.errors = isBulkError(data) ? data.errors : void 0;
189
+ this.requestId = requestId;
85
190
  if (data instanceof Error) {
86
191
  this.stack = data.stack;
87
192
  this.cause = data.cause;
88
193
  }
89
194
  }
195
+ toString() {
196
+ const error = super.toString();
197
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
198
+ }
90
199
  }
91
200
  function isBulkError(error) {
92
201
  return isObject(error) && Array.isArray(error.errors);
@@ -109,7 +218,12 @@ function getMessage(data) {
109
218
  }
110
219
 
111
220
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
112
- const query = new URLSearchParams(queryParams).toString();
221
+ const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
222
+ if (value === void 0 || value === null)
223
+ return acc;
224
+ return { ...acc, [key]: value };
225
+ }, {});
226
+ const query = new URLSearchParams(cleanQueryParams).toString();
113
227
  const queryString = query.length > 0 ? `?${query}` : "";
114
228
  return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
115
229
  };
@@ -139,32 +253,62 @@ async function fetch$1({
139
253
  fetchImpl,
140
254
  apiKey,
141
255
  apiUrl,
142
- workspacesApiUrl
256
+ workspacesApiUrl,
257
+ trace
143
258
  }) {
144
- const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
145
- const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
146
- const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
147
- const response = await fetchImpl(url, {
148
- method: method.toUpperCase(),
149
- body: body ? JSON.stringify(body) : void 0,
150
- headers: {
151
- "Content-Type": "application/json",
152
- ...headers,
153
- ...hostHeader(fullUrl),
154
- Authorization: `Bearer ${apiKey}`
155
- }
156
- });
157
- if (response.status === 204) {
158
- return {};
159
- }
259
+ return trace(
260
+ `${method.toUpperCase()} ${path}`,
261
+ async ({ setAttributes, onError }) => {
262
+ const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
263
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
264
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
265
+ setAttributes({
266
+ [TraceAttributes.HTTP_URL]: url,
267
+ [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
268
+ });
269
+ const response = await fetchImpl(url, {
270
+ method: method.toUpperCase(),
271
+ body: body ? JSON.stringify(body) : void 0,
272
+ headers: {
273
+ "Content-Type": "application/json",
274
+ "User-Agent": `Xata client-ts/${VERSION}`,
275
+ ...headers,
276
+ ...hostHeader(fullUrl),
277
+ Authorization: `Bearer ${apiKey}`
278
+ }
279
+ });
280
+ if (response.status === 204) {
281
+ return {};
282
+ }
283
+ const { host, protocol } = parseUrl(response.url);
284
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
285
+ setAttributes({
286
+ [TraceAttributes.HTTP_REQUEST_ID]: requestId,
287
+ [TraceAttributes.HTTP_STATUS_CODE]: response.status,
288
+ [TraceAttributes.HTTP_HOST]: host,
289
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
290
+ });
291
+ try {
292
+ const jsonResponse = await response.json();
293
+ if (response.ok) {
294
+ return jsonResponse;
295
+ }
296
+ throw new FetcherError(response.status, jsonResponse, requestId);
297
+ } catch (error) {
298
+ const fetcherError = new FetcherError(response.status, error, requestId);
299
+ onError(fetcherError.message);
300
+ throw fetcherError;
301
+ }
302
+ },
303
+ { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
304
+ );
305
+ }
306
+ function parseUrl(url) {
160
307
  try {
161
- const jsonResponse = await response.json();
162
- if (response.ok) {
163
- return jsonResponse;
164
- }
165
- throw new FetcherError(response.status, jsonResponse);
308
+ const { host, protocol } = new URL(url);
309
+ return { host, protocol };
166
310
  } catch (error) {
167
- throw new FetcherError(response.status, error);
311
+ return {};
168
312
  }
169
313
  }
170
314
 
@@ -223,6 +367,7 @@ const removeWorkspaceMember = (variables) => fetch$1({
223
367
  ...variables
224
368
  });
225
369
  const inviteWorkspaceMember = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables });
370
+ const updateWorkspaceMemberInvite = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables });
226
371
  const cancelWorkspaceMemberInvite = (variables) => fetch$1({
227
372
  url: "/workspaces/{workspaceId}/invites/{inviteId}",
228
373
  method: "delete",
@@ -258,6 +403,11 @@ const deleteDatabase = (variables) => fetch$1({
258
403
  method: "delete",
259
404
  ...variables
260
405
  });
406
+ const getDatabaseMetadata = (variables) => fetch$1({
407
+ url: "/dbs/{dbName}/metadata",
408
+ method: "get",
409
+ ...variables
410
+ });
261
411
  const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
262
412
  const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
263
413
  const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
@@ -271,11 +421,7 @@ const getBranchDetails = (variables) => fetch$1({
271
421
  method: "get",
272
422
  ...variables
273
423
  });
274
- const createBranch = (variables) => fetch$1({
275
- url: "/db/{dbBranchName}",
276
- method: "put",
277
- ...variables
278
- });
424
+ const createBranch = (variables) => fetch$1({ url: "/db/{dbBranchName}", method: "put", ...variables });
279
425
  const deleteBranch = (variables) => fetch$1({
280
426
  url: "/db/{dbBranchName}",
281
427
  method: "delete",
@@ -349,11 +495,7 @@ const updateColumn = (variables) => fetch$1({
349
495
  method: "patch",
350
496
  ...variables
351
497
  });
352
- const insertRecord = (variables) => fetch$1({
353
- url: "/db/{dbBranchName}/tables/{tableName}/data",
354
- method: "post",
355
- ...variables
356
- });
498
+ const insertRecord = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables });
357
499
  const insertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables });
358
500
  const updateRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables });
359
501
  const upsertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables });
@@ -395,6 +537,7 @@ const operationsByTag = {
395
537
  updateWorkspaceMemberRole,
396
538
  removeWorkspaceMember,
397
539
  inviteWorkspaceMember,
540
+ updateWorkspaceMemberInvite,
398
541
  cancelWorkspaceMemberInvite,
399
542
  resendWorkspaceMemberInvite,
400
543
  acceptWorkspaceMemberInvite
@@ -403,6 +546,7 @@ const operationsByTag = {
403
546
  getDatabaseList,
404
547
  createDatabase,
405
548
  deleteDatabase,
549
+ getDatabaseMetadata,
406
550
  getGitBranchesMapping,
407
551
  addGitBranchesEntry,
408
552
  removeGitBranchesEntry,
@@ -484,7 +628,7 @@ var __privateAdd$7 = (obj, member, value) => {
484
628
  throw TypeError("Cannot add the same private member more than once");
485
629
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
486
630
  };
487
- var __privateSet$6 = (obj, member, value, setter) => {
631
+ var __privateSet$7 = (obj, member, value, setter) => {
488
632
  __accessCheck$7(obj, member, "write to private field");
489
633
  setter ? setter.call(obj, value) : member.set(obj, value);
490
634
  return value;
@@ -495,15 +639,17 @@ class XataApiClient {
495
639
  __privateAdd$7(this, _extraProps, void 0);
496
640
  __privateAdd$7(this, _namespaces, {});
497
641
  const provider = options.host ?? "production";
498
- const apiKey = options?.apiKey ?? getAPIKey();
642
+ const apiKey = options.apiKey ?? getAPIKey();
643
+ const trace = options.trace ?? defaultTrace;
499
644
  if (!apiKey) {
500
645
  throw new Error("Could not resolve a valid apiKey");
501
646
  }
502
- __privateSet$6(this, _extraProps, {
647
+ __privateSet$7(this, _extraProps, {
503
648
  apiUrl: getHostUrl(provider, "main"),
504
649
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
505
650
  fetchImpl: getFetchImplementation(options.fetch),
506
- apiKey
651
+ apiKey,
652
+ trace
507
653
  });
508
654
  }
509
655
  get user() {
@@ -626,6 +772,13 @@ class WorkspaceApi {
626
772
  ...this.extraProps
627
773
  });
628
774
  }
775
+ updateWorkspaceMemberInvite(workspaceId, inviteId, role) {
776
+ return operationsByTag.workspaces.updateWorkspaceMemberInvite({
777
+ pathParams: { workspaceId, inviteId },
778
+ body: { role },
779
+ ...this.extraProps
780
+ });
781
+ }
629
782
  cancelWorkspaceMemberInvite(workspaceId, inviteId) {
630
783
  return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
631
784
  pathParams: { workspaceId, inviteId },
@@ -668,6 +821,12 @@ class DatabaseApi {
668
821
  ...this.extraProps
669
822
  });
670
823
  }
824
+ getDatabaseMetadata(workspace, dbName) {
825
+ return operationsByTag.database.getDatabaseMetadata({
826
+ pathParams: { workspace, dbName },
827
+ ...this.extraProps
828
+ });
829
+ }
671
830
  getGitBranchesMapping(workspace, dbName) {
672
831
  return operationsByTag.database.getGitBranchesMapping({
673
832
  pathParams: { workspace, dbName },
@@ -688,10 +847,10 @@ class DatabaseApi {
688
847
  ...this.extraProps
689
848
  });
690
849
  }
691
- resolveBranch(workspace, dbName, gitBranch) {
850
+ resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
692
851
  return operationsByTag.database.resolveBranch({
693
852
  pathParams: { workspace, dbName },
694
- queryParams: { gitBranch },
853
+ queryParams: { gitBranch, fallbackBranch },
695
854
  ...this.extraProps
696
855
  });
697
856
  }
@@ -840,9 +999,10 @@ class RecordsApi {
840
999
  constructor(extraProps) {
841
1000
  this.extraProps = extraProps;
842
1001
  }
843
- insertRecord(workspace, database, branch, tableName, record) {
1002
+ insertRecord(workspace, database, branch, tableName, record, options = {}) {
844
1003
  return operationsByTag.records.insertRecord({
845
1004
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1005
+ queryParams: options,
846
1006
  body: record,
847
1007
  ...this.extraProps
848
1008
  });
@@ -871,21 +1031,24 @@ class RecordsApi {
871
1031
  ...this.extraProps
872
1032
  });
873
1033
  }
874
- deleteRecord(workspace, database, branch, tableName, recordId) {
1034
+ deleteRecord(workspace, database, branch, tableName, recordId, options = {}) {
875
1035
  return operationsByTag.records.deleteRecord({
876
1036
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1037
+ queryParams: options,
877
1038
  ...this.extraProps
878
1039
  });
879
1040
  }
880
1041
  getRecord(workspace, database, branch, tableName, recordId, options = {}) {
881
1042
  return operationsByTag.records.getRecord({
882
1043
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1044
+ queryParams: options,
883
1045
  ...this.extraProps
884
1046
  });
885
1047
  }
886
- bulkInsertTableRecords(workspace, database, branch, tableName, records) {
1048
+ bulkInsertTableRecords(workspace, database, branch, tableName, records, options = {}) {
887
1049
  return operationsByTag.records.bulkInsertTableRecords({
888
1050
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1051
+ queryParams: options,
889
1052
  body: { records },
890
1053
  ...this.extraProps
891
1054
  });
@@ -936,18 +1099,18 @@ var __privateAdd$6 = (obj, member, value) => {
936
1099
  throw TypeError("Cannot add the same private member more than once");
937
1100
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
938
1101
  };
939
- var __privateSet$5 = (obj, member, value, setter) => {
1102
+ var __privateSet$6 = (obj, member, value, setter) => {
940
1103
  __accessCheck$6(obj, member, "write to private field");
941
1104
  setter ? setter.call(obj, value) : member.set(obj, value);
942
1105
  return value;
943
1106
  };
944
- var _query;
1107
+ var _query, _page;
945
1108
  class Page {
946
1109
  constructor(query, meta, records = []) {
947
1110
  __privateAdd$6(this, _query, void 0);
948
- __privateSet$5(this, _query, query);
1111
+ __privateSet$6(this, _query, query);
949
1112
  this.meta = meta;
950
- this.records = records;
1113
+ this.records = new RecordArray(this, records);
951
1114
  }
952
1115
  async nextPage(size, offset) {
953
1116
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
@@ -967,12 +1130,56 @@ class Page {
967
1130
  }
968
1131
  _query = new WeakMap();
969
1132
  const PAGINATION_MAX_SIZE = 200;
970
- const PAGINATION_DEFAULT_SIZE = 200;
1133
+ const PAGINATION_DEFAULT_SIZE = 20;
971
1134
  const PAGINATION_MAX_OFFSET = 800;
972
1135
  const PAGINATION_DEFAULT_OFFSET = 0;
973
1136
  function isCursorPaginationOptions(options) {
974
1137
  return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
975
1138
  }
1139
+ const _RecordArray = class extends Array {
1140
+ constructor(...args) {
1141
+ super(..._RecordArray.parseConstructorParams(...args));
1142
+ __privateAdd$6(this, _page, void 0);
1143
+ __privateSet$6(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
1144
+ }
1145
+ static parseConstructorParams(...args) {
1146
+ if (args.length === 1 && typeof args[0] === "number") {
1147
+ return new Array(args[0]);
1148
+ }
1149
+ if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
1150
+ const result = args[1] ?? args[0].records ?? [];
1151
+ return new Array(...result);
1152
+ }
1153
+ return new Array(...args);
1154
+ }
1155
+ toArray() {
1156
+ return new Array(...this);
1157
+ }
1158
+ map(callbackfn, thisArg) {
1159
+ return this.toArray().map(callbackfn, thisArg);
1160
+ }
1161
+ async nextPage(size, offset) {
1162
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1163
+ return new _RecordArray(newPage);
1164
+ }
1165
+ async previousPage(size, offset) {
1166
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1167
+ return new _RecordArray(newPage);
1168
+ }
1169
+ async firstPage(size, offset) {
1170
+ const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1171
+ return new _RecordArray(newPage);
1172
+ }
1173
+ async lastPage(size, offset) {
1174
+ const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1175
+ return new _RecordArray(newPage);
1176
+ }
1177
+ hasNextPage() {
1178
+ return __privateGet$6(this, _page).meta.page.more;
1179
+ }
1180
+ };
1181
+ let RecordArray = _RecordArray;
1182
+ _page = new WeakMap();
976
1183
 
977
1184
  var __accessCheck$5 = (obj, member, msg) => {
978
1185
  if (!member.has(obj))
@@ -987,25 +1194,26 @@ var __privateAdd$5 = (obj, member, value) => {
987
1194
  throw TypeError("Cannot add the same private member more than once");
988
1195
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
989
1196
  };
990
- var __privateSet$4 = (obj, member, value, setter) => {
1197
+ var __privateSet$5 = (obj, member, value, setter) => {
991
1198
  __accessCheck$5(obj, member, "write to private field");
992
1199
  setter ? setter.call(obj, value) : member.set(obj, value);
993
1200
  return value;
994
1201
  };
995
1202
  var _table$1, _repository, _data;
996
1203
  const _Query = class {
997
- constructor(repository, table, data, parent) {
1204
+ constructor(repository, table, data, rawParent) {
998
1205
  __privateAdd$5(this, _table$1, void 0);
999
1206
  __privateAdd$5(this, _repository, void 0);
1000
1207
  __privateAdd$5(this, _data, { filter: {} });
1001
1208
  this.meta = { page: { cursor: "start", more: true } };
1002
- this.records = [];
1003
- __privateSet$4(this, _table$1, table);
1209
+ this.records = new RecordArray(this, []);
1210
+ __privateSet$5(this, _table$1, table);
1004
1211
  if (repository) {
1005
- __privateSet$4(this, _repository, repository);
1212
+ __privateSet$5(this, _repository, repository);
1006
1213
  } else {
1007
- __privateSet$4(this, _repository, this);
1214
+ __privateSet$5(this, _repository, this);
1008
1215
  }
1216
+ const parent = cleanParent(data, rawParent);
1009
1217
  __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
1010
1218
  __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
1011
1219
  __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
@@ -1058,13 +1266,18 @@ const _Query = class {
1058
1266
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1059
1267
  }
1060
1268
  }
1061
- sort(column, direction) {
1269
+ sort(column, direction = "asc") {
1062
1270
  const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
1063
1271
  const sort = [...originalSort, { column, direction }];
1064
1272
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
1065
1273
  }
1066
1274
  select(columns) {
1067
- return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { columns }, __privateGet$5(this, _data));
1275
+ return new _Query(
1276
+ __privateGet$5(this, _repository),
1277
+ __privateGet$5(this, _table$1),
1278
+ { columns },
1279
+ __privateGet$5(this, _data)
1280
+ );
1068
1281
  }
1069
1282
  getPaginated(options = {}) {
1070
1283
  const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
@@ -1087,8 +1300,11 @@ const _Query = class {
1087
1300
  }
1088
1301
  }
1089
1302
  async getMany(options = {}) {
1090
- const { records } = await this.getPaginated(options);
1091
- return records;
1303
+ const page = await this.getPaginated(options);
1304
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1305
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1306
+ }
1307
+ return page.records;
1092
1308
  }
1093
1309
  async getAll(options = {}) {
1094
1310
  const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
@@ -1102,6 +1318,12 @@ const _Query = class {
1102
1318
  const records = await this.getMany({ ...options, pagination: { size: 1 } });
1103
1319
  return records[0] ?? null;
1104
1320
  }
1321
+ async getFirstOrThrow(options = {}) {
1322
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1323
+ if (records[0] === void 0)
1324
+ throw new Error("No results found.");
1325
+ return records[0];
1326
+ }
1105
1327
  cache(ttl) {
1106
1328
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1107
1329
  }
@@ -1125,12 +1347,20 @@ let Query = _Query;
1125
1347
  _table$1 = new WeakMap();
1126
1348
  _repository = new WeakMap();
1127
1349
  _data = new WeakMap();
1350
+ function cleanParent(data, parent) {
1351
+ if (isCursorPaginationOptions(data.pagination)) {
1352
+ return { ...parent, sorting: void 0, filter: void 0 };
1353
+ }
1354
+ return parent;
1355
+ }
1128
1356
 
1129
1357
  function isIdentifiable(x) {
1130
1358
  return isObject(x) && isString(x?.id);
1131
1359
  }
1132
1360
  function isXataRecord(x) {
1133
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1361
+ const record = x;
1362
+ const metadata = record?.getMetadata();
1363
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1134
1364
  }
1135
1365
 
1136
1366
  function isSortFilterString(value) {
@@ -1169,7 +1399,7 @@ var __privateAdd$4 = (obj, member, value) => {
1169
1399
  throw TypeError("Cannot add the same private member more than once");
1170
1400
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1171
1401
  };
1172
- var __privateSet$3 = (obj, member, value, setter) => {
1402
+ var __privateSet$4 = (obj, member, value, setter) => {
1173
1403
  __accessCheck$4(obj, member, "write to private field");
1174
1404
  setter ? setter.call(obj, value) : member.set(obj, value);
1175
1405
  return value;
@@ -1178,7 +1408,7 @@ var __privateMethod$2 = (obj, member, method) => {
1178
1408
  __accessCheck$4(obj, member, "access private method");
1179
1409
  return method;
1180
1410
  };
1181
- var _table, _getFetchProps, _cache, _schema$1, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _invalidateCache, invalidateCache_fn, _setCacheRecord, setCacheRecord_fn, _getCacheRecord, getCacheRecord_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchema$1, getSchema_fn$1;
1411
+ var _table, _getFetchProps, _db, _cache, _schemaTables$2, _trace, _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;
1182
1412
  class Repository extends Query {
1183
1413
  }
1184
1414
  class RestRepository extends Query {
@@ -1190,175 +1420,254 @@ class RestRepository extends Query {
1190
1420
  __privateAdd$4(this, _updateRecordWithID);
1191
1421
  __privateAdd$4(this, _upsertRecordWithID);
1192
1422
  __privateAdd$4(this, _deleteRecord);
1193
- __privateAdd$4(this, _invalidateCache);
1194
- __privateAdd$4(this, _setCacheRecord);
1195
- __privateAdd$4(this, _getCacheRecord);
1196
1423
  __privateAdd$4(this, _setCacheQuery);
1197
1424
  __privateAdd$4(this, _getCacheQuery);
1198
- __privateAdd$4(this, _getSchema$1);
1425
+ __privateAdd$4(this, _getSchemaTables$1);
1199
1426
  __privateAdd$4(this, _table, void 0);
1200
1427
  __privateAdd$4(this, _getFetchProps, void 0);
1428
+ __privateAdd$4(this, _db, void 0);
1201
1429
  __privateAdd$4(this, _cache, void 0);
1202
- __privateAdd$4(this, _schema$1, void 0);
1203
- __privateSet$3(this, _table, options.table);
1204
- __privateSet$3(this, _getFetchProps, options.pluginOptions.getFetchProps);
1205
- this.db = options.db;
1206
- __privateSet$3(this, _cache, options.pluginOptions.cache);
1207
- }
1208
- async create(a, b) {
1209
- if (Array.isArray(a)) {
1210
- const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1211
- await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1212
- return records;
1213
- }
1214
- if (isString(a) && isObject(b)) {
1215
- if (a === "")
1216
- throw new Error("The id can't be empty");
1217
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1218
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1219
- return record;
1220
- }
1221
- if (isObject(a) && isString(a.id)) {
1222
- if (a.id === "")
1223
- throw new Error("The id can't be empty");
1224
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1225
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1226
- return record;
1227
- }
1228
- if (isObject(a)) {
1229
- const record = await __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1230
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1231
- return record;
1232
- }
1233
- throw new Error("Invalid arguments for create method");
1234
- }
1235
- async read(recordId) {
1236
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, recordId);
1237
- if (cacheRecord)
1238
- return cacheRecord;
1239
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1240
- try {
1241
- const response = await getRecord({
1242
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1243
- ...fetchProps
1430
+ __privateAdd$4(this, _schemaTables$2, void 0);
1431
+ __privateAdd$4(this, _trace, void 0);
1432
+ __privateSet$4(this, _table, options.table);
1433
+ __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1434
+ __privateSet$4(this, _db, options.db);
1435
+ __privateSet$4(this, _cache, options.pluginOptions.cache);
1436
+ __privateSet$4(this, _schemaTables$2, options.schemaTables);
1437
+ const trace = options.pluginOptions.trace ?? defaultTrace;
1438
+ __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
1439
+ return trace(name, fn, {
1440
+ ...options2,
1441
+ [TraceAttributes.TABLE]: __privateGet$4(this, _table),
1442
+ [TraceAttributes.VERSION]: VERSION
1244
1443
  });
1245
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1246
- return initObject(this.db, schema, __privateGet$4(this, _table), response);
1247
- } catch (e) {
1248
- if (isObject(e) && e.status === 404) {
1249
- return null;
1444
+ });
1445
+ }
1446
+ async create(a, b, c) {
1447
+ return __privateGet$4(this, _trace).call(this, "create", async () => {
1448
+ if (Array.isArray(a)) {
1449
+ if (a.length === 0)
1450
+ return [];
1451
+ const columns = isStringArray(b) ? b : void 0;
1452
+ return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
1250
1453
  }
1251
- throw e;
1252
- }
1454
+ if (isString(a) && isObject(b)) {
1455
+ if (a === "")
1456
+ throw new Error("The id can't be empty");
1457
+ const columns = isStringArray(c) ? c : void 0;
1458
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns);
1459
+ }
1460
+ if (isObject(a) && isString(a.id)) {
1461
+ if (a.id === "")
1462
+ throw new Error("The id can't be empty");
1463
+ const columns = isStringArray(b) ? b : void 0;
1464
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1465
+ }
1466
+ if (isObject(a)) {
1467
+ const columns = isStringArray(b) ? b : void 0;
1468
+ return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
1469
+ }
1470
+ throw new Error("Invalid arguments for create method");
1471
+ });
1253
1472
  }
1254
- async update(a, b) {
1255
- if (Array.isArray(a)) {
1256
- if (a.length > 100) {
1257
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1473
+ async read(a, b) {
1474
+ return __privateGet$4(this, _trace).call(this, "read", async () => {
1475
+ const columns = isStringArray(b) ? b : ["*"];
1476
+ if (Array.isArray(a)) {
1477
+ if (a.length === 0)
1478
+ return [];
1479
+ const ids = a.map((item) => extractId(item));
1480
+ const finalObjects = await this.getAll({ filter: { id: { $any: compact(ids) } }, columns });
1481
+ const dictionary = finalObjects.reduce((acc, object) => {
1482
+ acc[object.id] = object;
1483
+ return acc;
1484
+ }, {});
1485
+ return ids.map((id2) => dictionary[id2 ?? ""] ?? null);
1258
1486
  }
1259
- return Promise.all(a.map((object) => this.update(object)));
1260
- }
1261
- if (isString(a) && isObject(b)) {
1262
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1263
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1264
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1265
- return record;
1266
- }
1267
- if (isObject(a) && isString(a.id)) {
1268
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1269
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1270
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1271
- return record;
1272
- }
1273
- throw new Error("Invalid arguments for update method");
1487
+ const id = extractId(a);
1488
+ if (id) {
1489
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1490
+ try {
1491
+ const response = await getRecord({
1492
+ pathParams: {
1493
+ workspace: "{workspaceId}",
1494
+ dbBranchName: "{dbBranch}",
1495
+ tableName: __privateGet$4(this, _table),
1496
+ recordId: id
1497
+ },
1498
+ queryParams: { columns },
1499
+ ...fetchProps
1500
+ });
1501
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1502
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1503
+ } catch (e) {
1504
+ if (isObject(e) && e.status === 404) {
1505
+ return null;
1506
+ }
1507
+ throw e;
1508
+ }
1509
+ }
1510
+ return null;
1511
+ });
1274
1512
  }
1275
- async createOrUpdate(a, b) {
1276
- if (Array.isArray(a)) {
1277
- if (a.length > 100) {
1278
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1513
+ async readOrThrow(a, b) {
1514
+ return __privateGet$4(this, _trace).call(this, "readOrThrow", async () => {
1515
+ const result = await this.read(a, b);
1516
+ if (Array.isArray(result)) {
1517
+ const missingIds = compact(
1518
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
1519
+ );
1520
+ if (missingIds.length > 0) {
1521
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
1522
+ }
1523
+ return result;
1279
1524
  }
1280
- return Promise.all(a.map((object) => this.createOrUpdate(object)));
1281
- }
1282
- if (isString(a) && isObject(b)) {
1283
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1284
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1285
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1286
- return record;
1287
- }
1288
- if (isObject(a) && isString(a.id)) {
1289
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1290
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1291
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1292
- return record;
1293
- }
1294
- throw new Error("Invalid arguments for createOrUpdate method");
1525
+ if (result === null) {
1526
+ const id = extractId(a) ?? "unknown";
1527
+ throw new Error(`Record with id ${id} not found`);
1528
+ }
1529
+ return result;
1530
+ });
1295
1531
  }
1296
- async delete(a) {
1297
- if (Array.isArray(a)) {
1298
- if (a.length > 100) {
1299
- console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1532
+ async update(a, b, c) {
1533
+ return __privateGet$4(this, _trace).call(this, "update", async () => {
1534
+ if (Array.isArray(a)) {
1535
+ if (a.length === 0)
1536
+ return [];
1537
+ if (a.length > 100) {
1538
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1539
+ }
1540
+ const columns = isStringArray(b) ? b : ["*"];
1541
+ return Promise.all(a.map((object) => this.update(object, columns)));
1300
1542
  }
1301
- await Promise.all(a.map((id) => this.delete(id)));
1302
- return;
1303
- }
1304
- if (isString(a)) {
1305
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1306
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1307
- return;
1308
- }
1309
- if (isObject(a) && isString(a.id)) {
1310
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1311
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1312
- return;
1313
- }
1314
- throw new Error("Invalid arguments for delete method");
1543
+ if (isString(a) && isObject(b)) {
1544
+ const columns = isStringArray(c) ? c : void 0;
1545
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns);
1546
+ }
1547
+ if (isObject(a) && isString(a.id)) {
1548
+ const columns = isStringArray(b) ? b : void 0;
1549
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1550
+ }
1551
+ throw new Error("Invalid arguments for update method");
1552
+ });
1553
+ }
1554
+ async updateOrThrow(a, b, c) {
1555
+ return __privateGet$4(this, _trace).call(this, "updateOrThrow", async () => {
1556
+ const result = await this.update(a, b, c);
1557
+ if (Array.isArray(result)) {
1558
+ const missingIds = compact(
1559
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
1560
+ );
1561
+ if (missingIds.length > 0) {
1562
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
1563
+ }
1564
+ return result;
1565
+ }
1566
+ if (result === null) {
1567
+ const id = extractId(a) ?? "unknown";
1568
+ throw new Error(`Record with id ${id} not found`);
1569
+ }
1570
+ return result;
1571
+ });
1572
+ }
1573
+ async createOrUpdate(a, b, c) {
1574
+ return __privateGet$4(this, _trace).call(this, "createOrUpdate", async () => {
1575
+ if (Array.isArray(a)) {
1576
+ if (a.length === 0)
1577
+ return [];
1578
+ if (a.length > 100) {
1579
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1580
+ }
1581
+ const columns = isStringArray(b) ? b : ["*"];
1582
+ return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
1583
+ }
1584
+ if (isString(a) && isObject(b)) {
1585
+ const columns = isStringArray(c) ? c : void 0;
1586
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns);
1587
+ }
1588
+ if (isObject(a) && isString(a.id)) {
1589
+ const columns = isStringArray(c) ? c : void 0;
1590
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1591
+ }
1592
+ throw new Error("Invalid arguments for createOrUpdate method");
1593
+ });
1594
+ }
1595
+ async delete(a, b) {
1596
+ return __privateGet$4(this, _trace).call(this, "delete", async () => {
1597
+ if (Array.isArray(a)) {
1598
+ if (a.length === 0)
1599
+ return [];
1600
+ if (a.length > 100) {
1601
+ console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1602
+ }
1603
+ return Promise.all(a.map((id) => this.delete(id, b)));
1604
+ }
1605
+ if (isString(a)) {
1606
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
1607
+ }
1608
+ if (isObject(a) && isString(a.id)) {
1609
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id, b);
1610
+ }
1611
+ throw new Error("Invalid arguments for delete method");
1612
+ });
1613
+ }
1614
+ async deleteOrThrow(a, b) {
1615
+ return __privateGet$4(this, _trace).call(this, "delete", async () => {
1616
+ throw new Error("Not implemented");
1617
+ });
1315
1618
  }
1316
1619
  async search(query, options = {}) {
1317
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1318
- const { records } = await searchTable({
1319
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1320
- body: {
1321
- query,
1322
- fuzziness: options.fuzziness,
1323
- filter: options.filter
1324
- },
1325
- ...fetchProps
1620
+ return __privateGet$4(this, _trace).call(this, "search", async () => {
1621
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1622
+ const { records } = await searchTable({
1623
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1624
+ body: {
1625
+ query,
1626
+ fuzziness: options.fuzziness,
1627
+ prefix: options.prefix,
1628
+ highlight: options.highlight,
1629
+ filter: options.filter,
1630
+ boosters: options.boosters
1631
+ },
1632
+ ...fetchProps
1633
+ });
1634
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1635
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1326
1636
  });
1327
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1328
- return records.map((item) => initObject(this.db, schema, __privateGet$4(this, _table), item));
1329
1637
  }
1330
1638
  async query(query) {
1331
- const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1332
- if (cacheQuery)
1333
- return new Page(query, cacheQuery.meta, cacheQuery.records);
1334
- const data = query.getQueryOptions();
1335
- const filter = Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0;
1336
- const sort = data.sort !== void 0 ? buildSortFilter(data.sort) : void 0;
1337
- const isCursorPagination = isCursorPaginationOptions(data.pagination);
1338
- const body = {
1339
- filter: isCursorPagination ? void 0 : filter,
1340
- sort: isCursorPagination ? void 0 : sort,
1341
- page: data.pagination,
1342
- columns: data.columns
1343
- };
1344
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1345
- const { meta, records: objects } = await queryTable({
1346
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1347
- body,
1348
- ...fetchProps
1639
+ return __privateGet$4(this, _trace).call(this, "query", async () => {
1640
+ const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1641
+ if (cacheQuery)
1642
+ return new Page(query, cacheQuery.meta, cacheQuery.records);
1643
+ const data = query.getQueryOptions();
1644
+ const body = {
1645
+ filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1646
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1647
+ page: data.pagination,
1648
+ columns: data.columns
1649
+ };
1650
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1651
+ const { meta, records: objects } = await queryTable({
1652
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1653
+ body,
1654
+ ...fetchProps
1655
+ });
1656
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1657
+ const records = objects.map((record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record));
1658
+ await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1659
+ return new Page(query, meta, records);
1349
1660
  });
1350
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1351
- const records = objects.map((record) => initObject(this.db, schema, __privateGet$4(this, _table), record));
1352
- await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1353
- return new Page(query, meta, records);
1354
1661
  }
1355
1662
  }
1356
1663
  _table = new WeakMap();
1357
1664
  _getFetchProps = new WeakMap();
1665
+ _db = new WeakMap();
1358
1666
  _cache = new WeakMap();
1359
- _schema$1 = new WeakMap();
1667
+ _schemaTables$2 = new WeakMap();
1668
+ _trace = new WeakMap();
1360
1669
  _insertRecordWithoutId = new WeakSet();
1361
- insertRecordWithoutId_fn = async function(object) {
1670
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1362
1671
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1363
1672
  const record = transformObjectLinks(object);
1364
1673
  const response = await insertRecord({
@@ -1367,17 +1676,15 @@ insertRecordWithoutId_fn = async function(object) {
1367
1676
  dbBranchName: "{dbBranch}",
1368
1677
  tableName: __privateGet$4(this, _table)
1369
1678
  },
1679
+ queryParams: { columns },
1370
1680
  body: record,
1371
1681
  ...fetchProps
1372
1682
  });
1373
- const finalObject = await this.read(response.id);
1374
- if (!finalObject) {
1375
- throw new Error("The server failed to save the record");
1376
- }
1377
- return finalObject;
1683
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1684
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1378
1685
  };
1379
1686
  _insertRecordWithId = new WeakSet();
1380
- insertRecordWithId_fn = async function(recordId, object) {
1687
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
1381
1688
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1382
1689
  const record = transformObjectLinks(object);
1383
1690
  const response = await insertRecordWithID({
@@ -1388,87 +1695,63 @@ insertRecordWithId_fn = async function(recordId, object) {
1388
1695
  recordId
1389
1696
  },
1390
1697
  body: record,
1391
- queryParams: { createOnly: true },
1698
+ queryParams: { createOnly: true, columns },
1392
1699
  ...fetchProps
1393
1700
  });
1394
- const finalObject = await this.read(response.id);
1395
- if (!finalObject) {
1396
- throw new Error("The server failed to save the record");
1397
- }
1398
- return finalObject;
1701
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1702
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1399
1703
  };
1400
1704
  _bulkInsertTableRecords = new WeakSet();
1401
- bulkInsertTableRecords_fn = async function(objects) {
1705
+ bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
1402
1706
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1403
1707
  const records = objects.map((object) => transformObjectLinks(object));
1404
1708
  const response = await bulkInsertTableRecords({
1405
1709
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1710
+ queryParams: { columns },
1406
1711
  body: { records },
1407
1712
  ...fetchProps
1408
1713
  });
1409
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1410
- if (finalObjects.length !== objects.length) {
1411
- throw new Error("The server failed to save some records");
1714
+ if (!isResponseWithRecords(response)) {
1715
+ throw new Error("Request included columns but server didn't include them");
1412
1716
  }
1413
- return finalObjects;
1717
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1718
+ return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1414
1719
  };
1415
1720
  _updateRecordWithID = new WeakSet();
1416
- updateRecordWithID_fn = async function(recordId, object) {
1721
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1417
1722
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1418
1723
  const record = transformObjectLinks(object);
1419
1724
  const response = await updateRecordWithID({
1420
1725
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1726
+ queryParams: { columns },
1421
1727
  body: record,
1422
1728
  ...fetchProps
1423
1729
  });
1424
- const item = await this.read(response.id);
1425
- if (!item)
1426
- throw new Error("The server failed to save the record");
1427
- return item;
1730
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1731
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1428
1732
  };
1429
1733
  _upsertRecordWithID = new WeakSet();
1430
- upsertRecordWithID_fn = async function(recordId, object) {
1734
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1431
1735
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1432
1736
  const response = await upsertRecordWithID({
1433
1737
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1738
+ queryParams: { columns },
1434
1739
  body: object,
1435
1740
  ...fetchProps
1436
1741
  });
1437
- const item = await this.read(response.id);
1438
- if (!item)
1439
- throw new Error("The server failed to save the record");
1440
- return item;
1742
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1743
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1441
1744
  };
1442
1745
  _deleteRecord = new WeakSet();
1443
- deleteRecord_fn = async function(recordId) {
1746
+ deleteRecord_fn = async function(recordId, columns = ["*"]) {
1444
1747
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1445
- await deleteRecord({
1748
+ const response = await deleteRecord({
1446
1749
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1750
+ queryParams: { columns },
1447
1751
  ...fetchProps
1448
1752
  });
1449
- };
1450
- _invalidateCache = new WeakSet();
1451
- invalidateCache_fn = async function(recordId) {
1452
- await __privateGet$4(this, _cache).delete(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1453
- const cacheItems = await __privateGet$4(this, _cache).getAll();
1454
- const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1455
- for (const [key, value] of queries) {
1456
- const ids = getIds(value);
1457
- if (ids.includes(recordId))
1458
- await __privateGet$4(this, _cache).delete(key);
1459
- }
1460
- };
1461
- _setCacheRecord = new WeakSet();
1462
- setCacheRecord_fn = async function(record) {
1463
- if (!__privateGet$4(this, _cache).cacheRecords)
1464
- return;
1465
- await __privateGet$4(this, _cache).set(`rec_${__privateGet$4(this, _table)}:${record.id}`, record);
1466
- };
1467
- _getCacheRecord = new WeakSet();
1468
- getCacheRecord_fn = async function(recordId) {
1469
- if (!__privateGet$4(this, _cache).cacheRecords)
1470
- return null;
1471
- return __privateGet$4(this, _cache).get(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1753
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1754
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1472
1755
  };
1473
1756
  _setCacheQuery = new WeakSet();
1474
1757
  setCacheQuery_fn = async function(query, meta, records) {
@@ -1486,17 +1769,17 @@ getCacheQuery_fn = async function(query) {
1486
1769
  const hasExpired = result.date.getTime() + ttl < Date.now();
1487
1770
  return hasExpired ? null : result;
1488
1771
  };
1489
- _getSchema$1 = new WeakSet();
1490
- getSchema_fn$1 = async function() {
1491
- if (__privateGet$4(this, _schema$1))
1492
- return __privateGet$4(this, _schema$1);
1772
+ _getSchemaTables$1 = new WeakSet();
1773
+ getSchemaTables_fn$1 = async function() {
1774
+ if (__privateGet$4(this, _schemaTables$2))
1775
+ return __privateGet$4(this, _schemaTables$2);
1493
1776
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1494
1777
  const { schema } = await getBranchDetails({
1495
1778
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1496
1779
  ...fetchProps
1497
1780
  });
1498
- __privateSet$3(this, _schema$1, schema);
1499
- return schema;
1781
+ __privateSet$4(this, _schemaTables$2, schema.tables);
1782
+ return schema.tables;
1500
1783
  };
1501
1784
  const transformObjectLinks = (object) => {
1502
1785
  return Object.entries(object).reduce((acc, [key, value]) => {
@@ -1505,20 +1788,21 @@ const transformObjectLinks = (object) => {
1505
1788
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1506
1789
  }, {});
1507
1790
  };
1508
- const initObject = (db, schema, table, object) => {
1791
+ const initObject = (db, schemaTables, table, object) => {
1509
1792
  const result = {};
1510
- Object.assign(result, object);
1511
- const { columns } = schema.tables.find(({ name }) => name === table) ?? {};
1793
+ const { xata, ...rest } = object ?? {};
1794
+ Object.assign(result, rest);
1795
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
1512
1796
  if (!columns)
1513
1797
  console.error(`Table ${table} not found in schema`);
1514
1798
  for (const column of columns ?? []) {
1515
1799
  const value = result[column.name];
1516
1800
  switch (column.type) {
1517
1801
  case "datetime": {
1518
- const date = new Date(value);
1519
- if (isNaN(date.getTime())) {
1802
+ const date = value !== void 0 ? new Date(value) : void 0;
1803
+ if (date && isNaN(date.getTime())) {
1520
1804
  console.error(`Failed to parse date ${value} for field ${column.name}`);
1521
- } else {
1805
+ } else if (date) {
1522
1806
  result[column.name] = date;
1523
1807
  }
1524
1808
  break;
@@ -1528,35 +1812,39 @@ const initObject = (db, schema, table, object) => {
1528
1812
  if (!linkTable) {
1529
1813
  console.error(`Failed to parse link for field ${column.name}`);
1530
1814
  } else if (isObject(value)) {
1531
- result[column.name] = initObject(db, schema, linkTable, value);
1815
+ result[column.name] = initObject(db, schemaTables, linkTable, value);
1532
1816
  }
1533
1817
  break;
1534
1818
  }
1535
1819
  }
1536
1820
  }
1537
- result.read = function() {
1538
- return db[table].read(result["id"]);
1821
+ result.read = function(columns2) {
1822
+ return db[table].read(result["id"], columns2);
1539
1823
  };
1540
- result.update = function(data) {
1541
- return db[table].update(result["id"], data);
1824
+ result.update = function(data, columns2) {
1825
+ return db[table].update(result["id"], data, columns2);
1542
1826
  };
1543
1827
  result.delete = function() {
1544
1828
  return db[table].delete(result["id"]);
1545
1829
  };
1546
- for (const prop of ["read", "update", "delete"]) {
1830
+ result.getMetadata = function() {
1831
+ return xata;
1832
+ };
1833
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1547
1834
  Object.defineProperty(result, prop, { enumerable: false });
1548
1835
  }
1549
1836
  Object.freeze(result);
1550
1837
  return result;
1551
1838
  };
1552
- function getIds(value) {
1553
- if (Array.isArray(value)) {
1554
- return value.map((item) => getIds(item)).flat();
1555
- }
1556
- if (!isObject(value))
1557
- return [];
1558
- const nestedIds = Object.values(value).map((item) => getIds(item)).flat();
1559
- return isString(value.id) ? [value.id, ...nestedIds] : nestedIds;
1839
+ function isResponseWithRecords(value) {
1840
+ return isObject(value) && Array.isArray(value.records);
1841
+ }
1842
+ function extractId(value) {
1843
+ if (isString(value))
1844
+ return value;
1845
+ if (isObject(value) && isString(value.id))
1846
+ return value.id;
1847
+ return void 0;
1560
1848
  }
1561
1849
 
1562
1850
  var __accessCheck$3 = (obj, member, msg) => {
@@ -1572,7 +1860,7 @@ var __privateAdd$3 = (obj, member, value) => {
1572
1860
  throw TypeError("Cannot add the same private member more than once");
1573
1861
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1574
1862
  };
1575
- var __privateSet$2 = (obj, member, value, setter) => {
1863
+ var __privateSet$3 = (obj, member, value, setter) => {
1576
1864
  __accessCheck$3(obj, member, "write to private field");
1577
1865
  setter ? setter.call(obj, value) : member.set(obj, value);
1578
1866
  return value;
@@ -1581,9 +1869,8 @@ var _map;
1581
1869
  class SimpleCache {
1582
1870
  constructor(options = {}) {
1583
1871
  __privateAdd$3(this, _map, void 0);
1584
- __privateSet$2(this, _map, /* @__PURE__ */ new Map());
1872
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1585
1873
  this.capacity = options.max ?? 500;
1586
- this.cacheRecords = options.cacheRecords ?? true;
1587
1874
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1588
1875
  }
1589
1876
  async getAll() {
@@ -1609,18 +1896,25 @@ class SimpleCache {
1609
1896
  }
1610
1897
  _map = new WeakMap();
1611
1898
 
1612
- const gt = (value) => ({ $gt: value });
1613
- const ge = (value) => ({ $ge: value });
1614
- const gte = (value) => ({ $ge: value });
1615
- const lt = (value) => ({ $lt: value });
1616
- const lte = (value) => ({ $le: value });
1617
- const le = (value) => ({ $le: value });
1899
+ const greaterThan = (value) => ({ $gt: value });
1900
+ const gt = greaterThan;
1901
+ const greaterThanEquals = (value) => ({ $ge: value });
1902
+ const greaterEquals = greaterThanEquals;
1903
+ const gte = greaterThanEquals;
1904
+ const ge = greaterThanEquals;
1905
+ const lessThan = (value) => ({ $lt: value });
1906
+ const lt = lessThan;
1907
+ const lessThanEquals = (value) => ({ $le: value });
1908
+ const lessEquals = lessThanEquals;
1909
+ const lte = lessThanEquals;
1910
+ const le = lessThanEquals;
1618
1911
  const exists = (column) => ({ $exists: column });
1619
1912
  const notExists = (column) => ({ $notExists: column });
1620
1913
  const startsWith = (value) => ({ $startsWith: value });
1621
1914
  const endsWith = (value) => ({ $endsWith: value });
1622
1915
  const pattern = (value) => ({ $pattern: value });
1623
1916
  const is = (value) => ({ $is: value });
1917
+ const equals = is;
1624
1918
  const isNot = (value) => ({ $isNot: value });
1625
1919
  const contains = (value) => ({ $contains: value });
1626
1920
  const includes = (value) => ({ $includes: value });
@@ -1641,31 +1935,42 @@ var __privateAdd$2 = (obj, member, value) => {
1641
1935
  throw TypeError("Cannot add the same private member more than once");
1642
1936
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1643
1937
  };
1644
- var _tables;
1938
+ var __privateSet$2 = (obj, member, value, setter) => {
1939
+ __accessCheck$2(obj, member, "write to private field");
1940
+ setter ? setter.call(obj, value) : member.set(obj, value);
1941
+ return value;
1942
+ };
1943
+ var _tables, _schemaTables$1;
1645
1944
  class SchemaPlugin extends XataPlugin {
1646
- constructor(tableNames) {
1945
+ constructor(schemaTables) {
1647
1946
  super();
1648
- this.tableNames = tableNames;
1649
1947
  __privateAdd$2(this, _tables, {});
1948
+ __privateAdd$2(this, _schemaTables$1, void 0);
1949
+ __privateSet$2(this, _schemaTables$1, schemaTables);
1650
1950
  }
1651
1951
  build(pluginOptions) {
1652
- const db = new Proxy({}, {
1653
- get: (_target, table) => {
1654
- if (!isString(table))
1655
- throw new Error("Invalid table name");
1656
- if (__privateGet$2(this, _tables)[table] === void 0) {
1657
- __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table });
1952
+ const db = new Proxy(
1953
+ {},
1954
+ {
1955
+ get: (_target, table) => {
1956
+ if (!isString(table))
1957
+ throw new Error("Invalid table name");
1958
+ if (__privateGet$2(this, _tables)[table] === void 0) {
1959
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1960
+ }
1961
+ return __privateGet$2(this, _tables)[table];
1658
1962
  }
1659
- return __privateGet$2(this, _tables)[table];
1660
1963
  }
1661
- });
1662
- for (const table of this.tableNames ?? []) {
1663
- db[table] = new RestRepository({ db, pluginOptions, table });
1964
+ );
1965
+ const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
1966
+ for (const table of tableNames) {
1967
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1664
1968
  }
1665
1969
  return db;
1666
1970
  }
1667
1971
  }
1668
1972
  _tables = new WeakMap();
1973
+ _schemaTables$1 = new WeakMap();
1669
1974
 
1670
1975
  var __accessCheck$1 = (obj, member, msg) => {
1671
1976
  if (!member.has(obj))
@@ -1689,82 +1994,77 @@ var __privateMethod$1 = (obj, member, method) => {
1689
1994
  __accessCheck$1(obj, member, "access private method");
1690
1995
  return method;
1691
1996
  };
1692
- var _schema, _search, search_fn, _getSchema, getSchema_fn;
1997
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1693
1998
  class SearchPlugin extends XataPlugin {
1694
- constructor(db) {
1999
+ constructor(db, schemaTables) {
1695
2000
  super();
1696
2001
  this.db = db;
1697
2002
  __privateAdd$1(this, _search);
1698
- __privateAdd$1(this, _getSchema);
1699
- __privateAdd$1(this, _schema, void 0);
2003
+ __privateAdd$1(this, _getSchemaTables);
2004
+ __privateAdd$1(this, _schemaTables, void 0);
2005
+ __privateSet$1(this, _schemaTables, schemaTables);
1700
2006
  }
1701
2007
  build({ getFetchProps }) {
1702
2008
  return {
1703
2009
  all: async (query, options = {}) => {
1704
2010
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1705
- const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
2011
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1706
2012
  return records.map((record) => {
1707
2013
  const { table = "orphan" } = record.xata;
1708
- return { table, record: initObject(this.db, schema, table, record) };
2014
+ return { table, record: initObject(this.db, schemaTables, table, record) };
1709
2015
  });
1710
2016
  },
1711
2017
  byTable: async (query, options = {}) => {
1712
2018
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1713
- const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
2019
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1714
2020
  return records.reduce((acc, record) => {
1715
2021
  const { table = "orphan" } = record.xata;
1716
2022
  const items = acc[table] ?? [];
1717
- const item = initObject(this.db, schema, table, record);
2023
+ const item = initObject(this.db, schemaTables, table, record);
1718
2024
  return { ...acc, [table]: [...items, item] };
1719
2025
  }, {});
1720
2026
  }
1721
2027
  };
1722
2028
  }
1723
2029
  }
1724
- _schema = new WeakMap();
2030
+ _schemaTables = new WeakMap();
1725
2031
  _search = new WeakSet();
1726
2032
  search_fn = async function(query, options, getFetchProps) {
1727
2033
  const fetchProps = await getFetchProps();
1728
- const { tables, fuzziness } = options ?? {};
2034
+ const { tables, fuzziness, highlight, prefix } = options ?? {};
1729
2035
  const { records } = await searchBranch({
1730
2036
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1731
- body: { tables, query, fuzziness },
2037
+ body: { tables, query, fuzziness, prefix, highlight },
1732
2038
  ...fetchProps
1733
2039
  });
1734
2040
  return records;
1735
2041
  };
1736
- _getSchema = new WeakSet();
1737
- getSchema_fn = async function(getFetchProps) {
1738
- if (__privateGet$1(this, _schema))
1739
- return __privateGet$1(this, _schema);
2042
+ _getSchemaTables = new WeakSet();
2043
+ getSchemaTables_fn = async function(getFetchProps) {
2044
+ if (__privateGet$1(this, _schemaTables))
2045
+ return __privateGet$1(this, _schemaTables);
1740
2046
  const fetchProps = await getFetchProps();
1741
2047
  const { schema } = await getBranchDetails({
1742
2048
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1743
2049
  ...fetchProps
1744
2050
  });
1745
- __privateSet$1(this, _schema, schema);
1746
- return schema;
2051
+ __privateSet$1(this, _schemaTables, schema.tables);
2052
+ return schema.tables;
1747
2053
  };
1748
2054
 
1749
2055
  const isBranchStrategyBuilder = (strategy) => {
1750
2056
  return typeof strategy === "function";
1751
2057
  };
1752
2058
 
1753
- const envBranchNames = [
1754
- "XATA_BRANCH",
1755
- "VERCEL_GIT_COMMIT_REF",
1756
- "CF_PAGES_BRANCH",
1757
- "BRANCH"
1758
- ];
1759
2059
  async function getCurrentBranchName(options) {
1760
- const env = getBranchByEnvVariable();
1761
- if (env) {
1762
- const details = await getDatabaseBranch(env, options);
2060
+ const { branch, envBranch } = getEnvironment();
2061
+ if (branch) {
2062
+ const details = await getDatabaseBranch(branch, options);
1763
2063
  if (details)
1764
- return env;
1765
- console.warn(`Branch ${env} not found in Xata. Ignoring...`);
2064
+ return branch;
2065
+ console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
1766
2066
  }
1767
- const gitBranch = await getGitBranch();
2067
+ const gitBranch = envBranch || await getGitBranch();
1768
2068
  return resolveXataBranch(gitBranch, options);
1769
2069
  }
1770
2070
  async function getCurrentBranchDetails(options) {
@@ -1775,18 +2075,24 @@ async function resolveXataBranch(gitBranch, options) {
1775
2075
  const databaseURL = options?.databaseURL || getDatabaseURL();
1776
2076
  const apiKey = options?.apiKey || getAPIKey();
1777
2077
  if (!databaseURL)
1778
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
2078
+ throw new Error(
2079
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2080
+ );
1779
2081
  if (!apiKey)
1780
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
2082
+ throw new Error(
2083
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2084
+ );
1781
2085
  const [protocol, , host, , dbName] = databaseURL.split("/");
1782
2086
  const [workspace] = host.split(".");
2087
+ const { fallbackBranch } = getEnvironment();
1783
2088
  const { branch } = await resolveBranch({
1784
2089
  apiKey,
1785
2090
  apiUrl: databaseURL,
1786
2091
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1787
2092
  workspacesApiUrl: `${protocol}//${host}`,
1788
2093
  pathParams: { dbName, workspace },
1789
- queryParams: { gitBranch, fallbackBranch: getEnvVariable("XATA_FALLBACK_BRANCH") }
2094
+ queryParams: { gitBranch, fallbackBranch },
2095
+ trace: defaultTrace
1790
2096
  });
1791
2097
  return branch;
1792
2098
  }
@@ -1794,9 +2100,13 @@ async function getDatabaseBranch(branch, options) {
1794
2100
  const databaseURL = options?.databaseURL || getDatabaseURL();
1795
2101
  const apiKey = options?.apiKey || getAPIKey();
1796
2102
  if (!databaseURL)
1797
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
2103
+ throw new Error(
2104
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2105
+ );
1798
2106
  if (!apiKey)
1799
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
2107
+ throw new Error(
2108
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2109
+ );
1800
2110
  const [protocol, , host, , database] = databaseURL.split("/");
1801
2111
  const [workspace] = host.split(".");
1802
2112
  const dbBranchName = `${database}:${branch}`;
@@ -1806,10 +2116,8 @@ async function getDatabaseBranch(branch, options) {
1806
2116
  apiUrl: databaseURL,
1807
2117
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1808
2118
  workspacesApiUrl: `${protocol}//${host}`,
1809
- pathParams: {
1810
- dbBranchName,
1811
- workspace
1812
- }
2119
+ pathParams: { dbBranchName, workspace },
2120
+ trace: defaultTrace
1813
2121
  });
1814
2122
  } catch (err) {
1815
2123
  if (isObject(err) && err.status === 404)
@@ -1817,21 +2125,10 @@ async function getDatabaseBranch(branch, options) {
1817
2125
  throw err;
1818
2126
  }
1819
2127
  }
1820
- function getBranchByEnvVariable() {
1821
- for (const name of envBranchNames) {
1822
- const value = getEnvVariable(name);
1823
- if (value) {
1824
- return value;
1825
- }
1826
- }
1827
- try {
1828
- return XATA_BRANCH;
1829
- } catch (err) {
1830
- }
1831
- }
1832
2128
  function getDatabaseURL() {
1833
2129
  try {
1834
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
2130
+ const { databaseURL } = getEnvironment();
2131
+ return databaseURL;
1835
2132
  } catch (err) {
1836
2133
  return void 0;
1837
2134
  }
@@ -1860,20 +2157,23 @@ var __privateMethod = (obj, member, method) => {
1860
2157
  return method;
1861
2158
  };
1862
2159
  const buildClient = (plugins) => {
1863
- var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
2160
+ var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1864
2161
  return _a = class {
1865
- constructor(options = {}, tables) {
2162
+ constructor(options = {}, schemaTables) {
1866
2163
  __privateAdd(this, _parseOptions);
1867
2164
  __privateAdd(this, _getFetchProps);
1868
2165
  __privateAdd(this, _evaluateBranch);
1869
2166
  __privateAdd(this, _branch, void 0);
2167
+ __privateAdd(this, _options, void 0);
1870
2168
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
2169
+ __privateSet(this, _options, safeOptions);
1871
2170
  const pluginOptions = {
1872
2171
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1873
- cache: safeOptions.cache
2172
+ cache: safeOptions.cache,
2173
+ trace: safeOptions.trace
1874
2174
  };
1875
- const db = new SchemaPlugin(tables).build(pluginOptions);
1876
- const search = new SearchPlugin(db).build(pluginOptions);
2175
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2176
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1877
2177
  this.db = db;
1878
2178
  this.search = search;
1879
2179
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
@@ -1889,22 +2189,26 @@ const buildClient = (plugins) => {
1889
2189
  }
1890
2190
  }
1891
2191
  }
1892
- }, _branch = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
2192
+ async getConfig() {
2193
+ const databaseURL = __privateGet(this, _options).databaseURL;
2194
+ const branch = await __privateGet(this, _options).branch();
2195
+ return { databaseURL, branch };
2196
+ }
2197
+ }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
1893
2198
  const fetch = getFetchImplementation(options?.fetch);
1894
2199
  const databaseURL = options?.databaseURL || getDatabaseURL();
1895
2200
  const apiKey = options?.apiKey || getAPIKey();
1896
- const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
2201
+ const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
2202
+ const trace = options?.trace ?? defaultTrace;
1897
2203
  const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1898
- if (!databaseURL || !apiKey) {
1899
- throw new Error("Options databaseURL and apiKey are required");
2204
+ if (!apiKey) {
2205
+ throw new Error("Option apiKey is required");
1900
2206
  }
1901
- return { fetch, databaseURL, apiKey, branch, cache };
1902
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
1903
- fetch,
1904
- apiKey,
1905
- databaseURL,
1906
- branch
1907
- }) {
2207
+ if (!databaseURL) {
2208
+ throw new Error("Option databaseURL is required");
2209
+ }
2210
+ return { fetch, databaseURL, apiKey, branch, cache, trace };
2211
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace }) {
1908
2212
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
1909
2213
  if (!branchValue)
1910
2214
  throw new Error("Unable to resolve branch value");
@@ -1916,7 +2220,8 @@ const buildClient = (plugins) => {
1916
2220
  const hasBranch = params.dbBranchName ?? params.branch;
1917
2221
  const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branchValue}` : "");
1918
2222
  return databaseURL + newPath;
1919
- }
2223
+ },
2224
+ trace
1920
2225
  };
1921
2226
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1922
2227
  if (__privateGet(this, _branch))
@@ -1939,6 +2244,88 @@ const buildClient = (plugins) => {
1939
2244
  class BaseClient extends buildClient() {
1940
2245
  }
1941
2246
 
2247
+ const META = "__";
2248
+ const VALUE = "___";
2249
+ class Serializer {
2250
+ constructor() {
2251
+ this.classes = {};
2252
+ }
2253
+ add(clazz) {
2254
+ this.classes[clazz.name] = clazz;
2255
+ }
2256
+ toJSON(data) {
2257
+ function visit(obj) {
2258
+ if (Array.isArray(obj))
2259
+ return obj.map(visit);
2260
+ const type = typeof obj;
2261
+ if (type === "undefined")
2262
+ return { [META]: "undefined" };
2263
+ if (type === "bigint")
2264
+ return { [META]: "bigint", [VALUE]: obj.toString() };
2265
+ if (obj === null || type !== "object")
2266
+ return obj;
2267
+ const constructor = obj.constructor;
2268
+ const o = { [META]: constructor.name };
2269
+ for (const [key, value] of Object.entries(obj)) {
2270
+ o[key] = visit(value);
2271
+ }
2272
+ if (constructor === Date)
2273
+ o[VALUE] = obj.toISOString();
2274
+ if (constructor === Map)
2275
+ o[VALUE] = Object.fromEntries(obj);
2276
+ if (constructor === Set)
2277
+ o[VALUE] = [...obj];
2278
+ return o;
2279
+ }
2280
+ return JSON.stringify(visit(data));
2281
+ }
2282
+ fromJSON(json) {
2283
+ return JSON.parse(json, (key, value) => {
2284
+ if (value && typeof value === "object" && !Array.isArray(value)) {
2285
+ const { [META]: clazz, [VALUE]: val, ...rest } = value;
2286
+ const constructor = this.classes[clazz];
2287
+ if (constructor) {
2288
+ return Object.assign(Object.create(constructor.prototype), rest);
2289
+ }
2290
+ if (clazz === "Date")
2291
+ return new Date(val);
2292
+ if (clazz === "Set")
2293
+ return new Set(val);
2294
+ if (clazz === "Map")
2295
+ return new Map(Object.entries(val));
2296
+ if (clazz === "bigint")
2297
+ return BigInt(val);
2298
+ if (clazz === "undefined")
2299
+ return void 0;
2300
+ return rest;
2301
+ }
2302
+ return value;
2303
+ });
2304
+ }
2305
+ }
2306
+ const defaultSerializer = new Serializer();
2307
+ const serialize = (data) => {
2308
+ return defaultSerializer.toJSON(data);
2309
+ };
2310
+ const deserialize = (json) => {
2311
+ return defaultSerializer.fromJSON(json);
2312
+ };
2313
+
2314
+ function buildWorkerRunner(config) {
2315
+ return function xataWorker(name, _worker) {
2316
+ return async (...args) => {
2317
+ const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
2318
+ const result = await fetch(url, {
2319
+ method: "POST",
2320
+ headers: { "Content-Type": "application/json" },
2321
+ body: serialize({ args })
2322
+ });
2323
+ const text = await result.text();
2324
+ return deserialize(text);
2325
+ };
2326
+ };
2327
+ }
2328
+
1942
2329
  class XataError extends Error {
1943
2330
  constructor(message, status) {
1944
2331
  super(message);
@@ -1954,10 +2341,12 @@ exports.PAGINATION_MAX_OFFSET = PAGINATION_MAX_OFFSET;
1954
2341
  exports.PAGINATION_MAX_SIZE = PAGINATION_MAX_SIZE;
1955
2342
  exports.Page = Page;
1956
2343
  exports.Query = Query;
2344
+ exports.RecordArray = RecordArray;
1957
2345
  exports.Repository = Repository;
1958
2346
  exports.RestRepository = RestRepository;
1959
2347
  exports.SchemaPlugin = SchemaPlugin;
1960
2348
  exports.SearchPlugin = SearchPlugin;
2349
+ exports.Serializer = Serializer;
1961
2350
  exports.SimpleCache = SimpleCache;
1962
2351
  exports.XataApiClient = XataApiClient;
1963
2352
  exports.XataApiPlugin = XataApiPlugin;
@@ -1967,6 +2356,7 @@ exports.acceptWorkspaceMemberInvite = acceptWorkspaceMemberInvite;
1967
2356
  exports.addGitBranchesEntry = addGitBranchesEntry;
1968
2357
  exports.addTableColumn = addTableColumn;
1969
2358
  exports.buildClient = buildClient;
2359
+ exports.buildWorkerRunner = buildWorkerRunner;
1970
2360
  exports.bulkInsertTableRecords = bulkInsertTableRecords;
1971
2361
  exports.cancelWorkspaceMemberInvite = cancelWorkspaceMemberInvite;
1972
2362
  exports.contains = contains;
@@ -1983,7 +2373,9 @@ exports.deleteTable = deleteTable;
1983
2373
  exports.deleteUser = deleteUser;
1984
2374
  exports.deleteUserAPIKey = deleteUserAPIKey;
1985
2375
  exports.deleteWorkspace = deleteWorkspace;
2376
+ exports.deserialize = deserialize;
1986
2377
  exports.endsWith = endsWith;
2378
+ exports.equals = equals;
1987
2379
  exports.executeBranchMigrationPlan = executeBranchMigrationPlan;
1988
2380
  exports.exists = exists;
1989
2381
  exports.ge = ge;
@@ -1998,6 +2390,7 @@ exports.getColumn = getColumn;
1998
2390
  exports.getCurrentBranchDetails = getCurrentBranchDetails;
1999
2391
  exports.getCurrentBranchName = getCurrentBranchName;
2000
2392
  exports.getDatabaseList = getDatabaseList;
2393
+ exports.getDatabaseMetadata = getDatabaseMetadata;
2001
2394
  exports.getDatabaseURL = getDatabaseURL;
2002
2395
  exports.getGitBranchesMapping = getGitBranchesMapping;
2003
2396
  exports.getRecord = getRecord;
@@ -2008,6 +2401,9 @@ exports.getUserAPIKeys = getUserAPIKeys;
2008
2401
  exports.getWorkspace = getWorkspace;
2009
2402
  exports.getWorkspaceMembersList = getWorkspaceMembersList;
2010
2403
  exports.getWorkspacesList = getWorkspacesList;
2404
+ exports.greaterEquals = greaterEquals;
2405
+ exports.greaterThan = greaterThan;
2406
+ exports.greaterThanEquals = greaterThanEquals;
2011
2407
  exports.gt = gt;
2012
2408
  exports.gte = gte;
2013
2409
  exports.includes = includes;
@@ -2023,6 +2419,9 @@ exports.isIdentifiable = isIdentifiable;
2023
2419
  exports.isNot = isNot;
2024
2420
  exports.isXataRecord = isXataRecord;
2025
2421
  exports.le = le;
2422
+ exports.lessEquals = lessEquals;
2423
+ exports.lessThan = lessThan;
2424
+ exports.lessThanEquals = lessThanEquals;
2026
2425
  exports.lt = lt;
2027
2426
  exports.lte = lte;
2028
2427
  exports.notExists = notExists;
@@ -2035,6 +2434,7 @@ exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite;
2035
2434
  exports.resolveBranch = resolveBranch;
2036
2435
  exports.searchBranch = searchBranch;
2037
2436
  exports.searchTable = searchTable;
2437
+ exports.serialize = serialize;
2038
2438
  exports.setTableSchema = setTableSchema;
2039
2439
  exports.startsWith = startsWith;
2040
2440
  exports.updateBranchMetadata = updateBranchMetadata;
@@ -2043,6 +2443,7 @@ exports.updateRecordWithID = updateRecordWithID;
2043
2443
  exports.updateTable = updateTable;
2044
2444
  exports.updateUser = updateUser;
2045
2445
  exports.updateWorkspace = updateWorkspace;
2446
+ exports.updateWorkspaceMemberInvite = updateWorkspaceMemberInvite;
2046
2447
  exports.updateWorkspaceMemberRole = updateWorkspaceMemberRole;
2047
2448
  exports.upsertRecordWithID = upsertRecordWithID;
2048
2449
  //# sourceMappingURL=index.cjs.map