@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.mjs CHANGED
@@ -1,3 +1,27 @@
1
+ const defaultTrace = async (_name, fn, _options) => {
2
+ return await fn({
3
+ setAttributes: () => {
4
+ return;
5
+ },
6
+ onError: () => {
7
+ return;
8
+ }
9
+ });
10
+ };
11
+ const TraceAttributes = {
12
+ VERSION: "xata.sdk.version",
13
+ TABLE: "xata.table",
14
+ HTTP_REQUEST_ID: "http.request_id",
15
+ HTTP_STATUS_CODE: "http.status_code",
16
+ HTTP_HOST: "http.host",
17
+ HTTP_SCHEME: "http.scheme",
18
+ HTTP_USER_AGENT: "http.user_agent",
19
+ HTTP_METHOD: "http.method",
20
+ HTTP_URL: "http.url",
21
+ HTTP_ROUTE: "http.route",
22
+ HTTP_TARGET: "http.target"
23
+ };
24
+
1
25
  function notEmpty(value) {
2
26
  return value !== null && value !== void 0;
3
27
  }
@@ -13,43 +37,95 @@ function isDefined(value) {
13
37
  function isString(value) {
14
38
  return isDefined(value) && typeof value === "string";
15
39
  }
40
+ function isStringArray(value) {
41
+ return isDefined(value) && Array.isArray(value) && value.every(isString);
42
+ }
16
43
  function toBase64(value) {
17
44
  try {
18
45
  return btoa(value);
19
46
  } catch (err) {
20
- return Buffer.from(value).toString("base64");
47
+ const buf = Buffer;
48
+ return buf.from(value).toString("base64");
21
49
  }
22
50
  }
23
51
 
24
- function getEnvVariable(name) {
52
+ function getEnvironment() {
25
53
  try {
26
- if (isObject(process) && isString(process?.env?.[name])) {
27
- return process.env[name];
54
+ if (isObject(process) && isObject(process.env)) {
55
+ return {
56
+ apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
57
+ databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
58
+ branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
59
+ envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
60
+ fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
61
+ };
28
62
  }
29
63
  } catch (err) {
30
64
  }
31
65
  try {
32
- if (isObject(Deno) && isString(Deno?.env?.get(name))) {
33
- return Deno.env.get(name);
66
+ if (isObject(Deno) && isObject(Deno.env)) {
67
+ return {
68
+ apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
69
+ databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
70
+ branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
71
+ envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
72
+ fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
73
+ };
34
74
  }
35
75
  } catch (err) {
36
76
  }
77
+ return {
78
+ apiKey: getGlobalApiKey(),
79
+ databaseURL: getGlobalDatabaseURL(),
80
+ branch: getGlobalBranch(),
81
+ envBranch: void 0,
82
+ fallbackBranch: getGlobalFallbackBranch()
83
+ };
84
+ }
85
+ function getGlobalApiKey() {
86
+ try {
87
+ return XATA_API_KEY;
88
+ } catch (err) {
89
+ return void 0;
90
+ }
91
+ }
92
+ function getGlobalDatabaseURL() {
93
+ try {
94
+ return XATA_DATABASE_URL;
95
+ } catch (err) {
96
+ return void 0;
97
+ }
98
+ }
99
+ function getGlobalBranch() {
100
+ try {
101
+ return XATA_BRANCH;
102
+ } catch (err) {
103
+ return void 0;
104
+ }
105
+ }
106
+ function getGlobalFallbackBranch() {
107
+ try {
108
+ return XATA_FALLBACK_BRANCH;
109
+ } catch (err) {
110
+ return void 0;
111
+ }
37
112
  }
38
113
  async function getGitBranch() {
114
+ const cmd = ["git", "branch", "--show-current"];
115
+ const fullCmd = cmd.join(" ");
116
+ const nodeModule = ["child", "process"].join("_");
117
+ const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
39
118
  try {
40
119
  if (typeof require === "function") {
41
- const req = require;
42
- return req("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
120
+ return require(nodeModule).execSync(fullCmd, execOptions).trim();
43
121
  }
122
+ const { execSync } = await import(nodeModule);
123
+ return execSync(fullCmd, execOptions).toString().trim();
44
124
  } catch (err) {
45
125
  }
46
126
  try {
47
127
  if (isObject(Deno)) {
48
- const process2 = Deno.run({
49
- cmd: ["git", "branch", "--show-current"],
50
- stdout: "piped",
51
- stderr: "piped"
52
- });
128
+ const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
53
129
  return new TextDecoder().decode(await process2.output()).trim();
54
130
  }
55
131
  } catch (err) {
@@ -58,7 +134,8 @@ async function getGitBranch() {
58
134
 
59
135
  function getAPIKey() {
60
136
  try {
61
- return getEnvVariable("XATA_API_KEY") ?? XATA_API_KEY;
137
+ const { apiKey } = getEnvironment();
138
+ return apiKey;
62
139
  } catch (err) {
63
140
  return void 0;
64
141
  }
@@ -68,21 +145,35 @@ function getFetchImplementation(userFetch) {
68
145
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
69
146
  const fetchImpl = userFetch ?? globalFetch;
70
147
  if (!fetchImpl) {
71
- throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
148
+ throw new Error(
149
+ `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
150
+ );
72
151
  }
73
152
  return fetchImpl;
74
153
  }
75
154
 
76
- class FetcherError extends Error {
77
- constructor(status, data) {
155
+ const VERSION = "0.0.0-alpha.vfeb24b1";
156
+
157
+ class ErrorWithCause extends Error {
158
+ constructor(message, options) {
159
+ super(message, options);
160
+ }
161
+ }
162
+ class FetcherError extends ErrorWithCause {
163
+ constructor(status, data, requestId) {
78
164
  super(getMessage(data));
79
165
  this.status = status;
80
166
  this.errors = isBulkError(data) ? data.errors : void 0;
167
+ this.requestId = requestId;
81
168
  if (data instanceof Error) {
82
169
  this.stack = data.stack;
83
170
  this.cause = data.cause;
84
171
  }
85
172
  }
173
+ toString() {
174
+ const error = super.toString();
175
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
176
+ }
86
177
  }
87
178
  function isBulkError(error) {
88
179
  return isObject(error) && Array.isArray(error.errors);
@@ -105,7 +196,12 @@ function getMessage(data) {
105
196
  }
106
197
 
107
198
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
108
- const query = new URLSearchParams(queryParams).toString();
199
+ const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
200
+ if (value === void 0 || value === null)
201
+ return acc;
202
+ return { ...acc, [key]: value };
203
+ }, {});
204
+ const query = new URLSearchParams(cleanQueryParams).toString();
109
205
  const queryString = query.length > 0 ? `?${query}` : "";
110
206
  return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
111
207
  };
@@ -135,32 +231,62 @@ async function fetch$1({
135
231
  fetchImpl,
136
232
  apiKey,
137
233
  apiUrl,
138
- workspacesApiUrl
234
+ workspacesApiUrl,
235
+ trace
139
236
  }) {
140
- const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
141
- const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
142
- const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
143
- const response = await fetchImpl(url, {
144
- method: method.toUpperCase(),
145
- body: body ? JSON.stringify(body) : void 0,
146
- headers: {
147
- "Content-Type": "application/json",
148
- ...headers,
149
- ...hostHeader(fullUrl),
150
- Authorization: `Bearer ${apiKey}`
151
- }
152
- });
153
- if (response.status === 204) {
154
- return {};
155
- }
237
+ return trace(
238
+ `${method.toUpperCase()} ${path}`,
239
+ async ({ setAttributes, onError }) => {
240
+ const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
241
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
242
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
243
+ setAttributes({
244
+ [TraceAttributes.HTTP_URL]: url,
245
+ [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
246
+ });
247
+ const response = await fetchImpl(url, {
248
+ method: method.toUpperCase(),
249
+ body: body ? JSON.stringify(body) : void 0,
250
+ headers: {
251
+ "Content-Type": "application/json",
252
+ "User-Agent": `Xata client-ts/${VERSION}`,
253
+ ...headers,
254
+ ...hostHeader(fullUrl),
255
+ Authorization: `Bearer ${apiKey}`
256
+ }
257
+ });
258
+ if (response.status === 204) {
259
+ return {};
260
+ }
261
+ const { host, protocol } = parseUrl(response.url);
262
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
263
+ setAttributes({
264
+ [TraceAttributes.HTTP_REQUEST_ID]: requestId,
265
+ [TraceAttributes.HTTP_STATUS_CODE]: response.status,
266
+ [TraceAttributes.HTTP_HOST]: host,
267
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
268
+ });
269
+ try {
270
+ const jsonResponse = await response.json();
271
+ if (response.ok) {
272
+ return jsonResponse;
273
+ }
274
+ throw new FetcherError(response.status, jsonResponse, requestId);
275
+ } catch (error) {
276
+ const fetcherError = new FetcherError(response.status, error, requestId);
277
+ onError(fetcherError.message);
278
+ throw fetcherError;
279
+ }
280
+ },
281
+ { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
282
+ );
283
+ }
284
+ function parseUrl(url) {
156
285
  try {
157
- const jsonResponse = await response.json();
158
- if (response.ok) {
159
- return jsonResponse;
160
- }
161
- throw new FetcherError(response.status, jsonResponse);
286
+ const { host, protocol } = new URL(url);
287
+ return { host, protocol };
162
288
  } catch (error) {
163
- throw new FetcherError(response.status, error);
289
+ return {};
164
290
  }
165
291
  }
166
292
 
@@ -219,6 +345,7 @@ const removeWorkspaceMember = (variables) => fetch$1({
219
345
  ...variables
220
346
  });
221
347
  const inviteWorkspaceMember = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables });
348
+ const updateWorkspaceMemberInvite = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables });
222
349
  const cancelWorkspaceMemberInvite = (variables) => fetch$1({
223
350
  url: "/workspaces/{workspaceId}/invites/{inviteId}",
224
351
  method: "delete",
@@ -254,6 +381,11 @@ const deleteDatabase = (variables) => fetch$1({
254
381
  method: "delete",
255
382
  ...variables
256
383
  });
384
+ const getDatabaseMetadata = (variables) => fetch$1({
385
+ url: "/dbs/{dbName}/metadata",
386
+ method: "get",
387
+ ...variables
388
+ });
257
389
  const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
258
390
  const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
259
391
  const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
@@ -267,11 +399,7 @@ const getBranchDetails = (variables) => fetch$1({
267
399
  method: "get",
268
400
  ...variables
269
401
  });
270
- const createBranch = (variables) => fetch$1({
271
- url: "/db/{dbBranchName}",
272
- method: "put",
273
- ...variables
274
- });
402
+ const createBranch = (variables) => fetch$1({ url: "/db/{dbBranchName}", method: "put", ...variables });
275
403
  const deleteBranch = (variables) => fetch$1({
276
404
  url: "/db/{dbBranchName}",
277
405
  method: "delete",
@@ -345,11 +473,7 @@ const updateColumn = (variables) => fetch$1({
345
473
  method: "patch",
346
474
  ...variables
347
475
  });
348
- const insertRecord = (variables) => fetch$1({
349
- url: "/db/{dbBranchName}/tables/{tableName}/data",
350
- method: "post",
351
- ...variables
352
- });
476
+ const insertRecord = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables });
353
477
  const insertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables });
354
478
  const updateRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables });
355
479
  const upsertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables });
@@ -391,6 +515,7 @@ const operationsByTag = {
391
515
  updateWorkspaceMemberRole,
392
516
  removeWorkspaceMember,
393
517
  inviteWorkspaceMember,
518
+ updateWorkspaceMemberInvite,
394
519
  cancelWorkspaceMemberInvite,
395
520
  resendWorkspaceMemberInvite,
396
521
  acceptWorkspaceMemberInvite
@@ -399,6 +524,7 @@ const operationsByTag = {
399
524
  getDatabaseList,
400
525
  createDatabase,
401
526
  deleteDatabase,
527
+ getDatabaseMetadata,
402
528
  getGitBranchesMapping,
403
529
  addGitBranchesEntry,
404
530
  removeGitBranchesEntry,
@@ -480,7 +606,7 @@ var __privateAdd$7 = (obj, member, value) => {
480
606
  throw TypeError("Cannot add the same private member more than once");
481
607
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
482
608
  };
483
- var __privateSet$6 = (obj, member, value, setter) => {
609
+ var __privateSet$7 = (obj, member, value, setter) => {
484
610
  __accessCheck$7(obj, member, "write to private field");
485
611
  setter ? setter.call(obj, value) : member.set(obj, value);
486
612
  return value;
@@ -491,15 +617,17 @@ class XataApiClient {
491
617
  __privateAdd$7(this, _extraProps, void 0);
492
618
  __privateAdd$7(this, _namespaces, {});
493
619
  const provider = options.host ?? "production";
494
- const apiKey = options?.apiKey ?? getAPIKey();
620
+ const apiKey = options.apiKey ?? getAPIKey();
621
+ const trace = options.trace ?? defaultTrace;
495
622
  if (!apiKey) {
496
623
  throw new Error("Could not resolve a valid apiKey");
497
624
  }
498
- __privateSet$6(this, _extraProps, {
625
+ __privateSet$7(this, _extraProps, {
499
626
  apiUrl: getHostUrl(provider, "main"),
500
627
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
501
628
  fetchImpl: getFetchImplementation(options.fetch),
502
- apiKey
629
+ apiKey,
630
+ trace
503
631
  });
504
632
  }
505
633
  get user() {
@@ -622,6 +750,13 @@ class WorkspaceApi {
622
750
  ...this.extraProps
623
751
  });
624
752
  }
753
+ updateWorkspaceMemberInvite(workspaceId, inviteId, role) {
754
+ return operationsByTag.workspaces.updateWorkspaceMemberInvite({
755
+ pathParams: { workspaceId, inviteId },
756
+ body: { role },
757
+ ...this.extraProps
758
+ });
759
+ }
625
760
  cancelWorkspaceMemberInvite(workspaceId, inviteId) {
626
761
  return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
627
762
  pathParams: { workspaceId, inviteId },
@@ -664,6 +799,12 @@ class DatabaseApi {
664
799
  ...this.extraProps
665
800
  });
666
801
  }
802
+ getDatabaseMetadata(workspace, dbName) {
803
+ return operationsByTag.database.getDatabaseMetadata({
804
+ pathParams: { workspace, dbName },
805
+ ...this.extraProps
806
+ });
807
+ }
667
808
  getGitBranchesMapping(workspace, dbName) {
668
809
  return operationsByTag.database.getGitBranchesMapping({
669
810
  pathParams: { workspace, dbName },
@@ -684,10 +825,10 @@ class DatabaseApi {
684
825
  ...this.extraProps
685
826
  });
686
827
  }
687
- resolveBranch(workspace, dbName, gitBranch) {
828
+ resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
688
829
  return operationsByTag.database.resolveBranch({
689
830
  pathParams: { workspace, dbName },
690
- queryParams: { gitBranch },
831
+ queryParams: { gitBranch, fallbackBranch },
691
832
  ...this.extraProps
692
833
  });
693
834
  }
@@ -836,9 +977,10 @@ class RecordsApi {
836
977
  constructor(extraProps) {
837
978
  this.extraProps = extraProps;
838
979
  }
839
- insertRecord(workspace, database, branch, tableName, record) {
980
+ insertRecord(workspace, database, branch, tableName, record, options = {}) {
840
981
  return operationsByTag.records.insertRecord({
841
982
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
983
+ queryParams: options,
842
984
  body: record,
843
985
  ...this.extraProps
844
986
  });
@@ -867,21 +1009,24 @@ class RecordsApi {
867
1009
  ...this.extraProps
868
1010
  });
869
1011
  }
870
- deleteRecord(workspace, database, branch, tableName, recordId) {
1012
+ deleteRecord(workspace, database, branch, tableName, recordId, options = {}) {
871
1013
  return operationsByTag.records.deleteRecord({
872
1014
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1015
+ queryParams: options,
873
1016
  ...this.extraProps
874
1017
  });
875
1018
  }
876
1019
  getRecord(workspace, database, branch, tableName, recordId, options = {}) {
877
1020
  return operationsByTag.records.getRecord({
878
1021
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1022
+ queryParams: options,
879
1023
  ...this.extraProps
880
1024
  });
881
1025
  }
882
- bulkInsertTableRecords(workspace, database, branch, tableName, records) {
1026
+ bulkInsertTableRecords(workspace, database, branch, tableName, records, options = {}) {
883
1027
  return operationsByTag.records.bulkInsertTableRecords({
884
1028
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1029
+ queryParams: options,
885
1030
  body: { records },
886
1031
  ...this.extraProps
887
1032
  });
@@ -932,18 +1077,18 @@ var __privateAdd$6 = (obj, member, value) => {
932
1077
  throw TypeError("Cannot add the same private member more than once");
933
1078
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
934
1079
  };
935
- var __privateSet$5 = (obj, member, value, setter) => {
1080
+ var __privateSet$6 = (obj, member, value, setter) => {
936
1081
  __accessCheck$6(obj, member, "write to private field");
937
1082
  setter ? setter.call(obj, value) : member.set(obj, value);
938
1083
  return value;
939
1084
  };
940
- var _query;
1085
+ var _query, _page;
941
1086
  class Page {
942
1087
  constructor(query, meta, records = []) {
943
1088
  __privateAdd$6(this, _query, void 0);
944
- __privateSet$5(this, _query, query);
1089
+ __privateSet$6(this, _query, query);
945
1090
  this.meta = meta;
946
- this.records = records;
1091
+ this.records = new RecordArray(this, records);
947
1092
  }
948
1093
  async nextPage(size, offset) {
949
1094
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
@@ -963,12 +1108,56 @@ class Page {
963
1108
  }
964
1109
  _query = new WeakMap();
965
1110
  const PAGINATION_MAX_SIZE = 200;
966
- const PAGINATION_DEFAULT_SIZE = 200;
1111
+ const PAGINATION_DEFAULT_SIZE = 20;
967
1112
  const PAGINATION_MAX_OFFSET = 800;
968
1113
  const PAGINATION_DEFAULT_OFFSET = 0;
969
1114
  function isCursorPaginationOptions(options) {
970
1115
  return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
971
1116
  }
1117
+ const _RecordArray = class extends Array {
1118
+ constructor(...args) {
1119
+ super(..._RecordArray.parseConstructorParams(...args));
1120
+ __privateAdd$6(this, _page, void 0);
1121
+ __privateSet$6(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
1122
+ }
1123
+ static parseConstructorParams(...args) {
1124
+ if (args.length === 1 && typeof args[0] === "number") {
1125
+ return new Array(args[0]);
1126
+ }
1127
+ if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
1128
+ const result = args[1] ?? args[0].records ?? [];
1129
+ return new Array(...result);
1130
+ }
1131
+ return new Array(...args);
1132
+ }
1133
+ toArray() {
1134
+ return new Array(...this);
1135
+ }
1136
+ map(callbackfn, thisArg) {
1137
+ return this.toArray().map(callbackfn, thisArg);
1138
+ }
1139
+ async nextPage(size, offset) {
1140
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1141
+ return new _RecordArray(newPage);
1142
+ }
1143
+ async previousPage(size, offset) {
1144
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1145
+ return new _RecordArray(newPage);
1146
+ }
1147
+ async firstPage(size, offset) {
1148
+ const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1149
+ return new _RecordArray(newPage);
1150
+ }
1151
+ async lastPage(size, offset) {
1152
+ const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1153
+ return new _RecordArray(newPage);
1154
+ }
1155
+ hasNextPage() {
1156
+ return __privateGet$6(this, _page).meta.page.more;
1157
+ }
1158
+ };
1159
+ let RecordArray = _RecordArray;
1160
+ _page = new WeakMap();
972
1161
 
973
1162
  var __accessCheck$5 = (obj, member, msg) => {
974
1163
  if (!member.has(obj))
@@ -983,25 +1172,26 @@ var __privateAdd$5 = (obj, member, value) => {
983
1172
  throw TypeError("Cannot add the same private member more than once");
984
1173
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
985
1174
  };
986
- var __privateSet$4 = (obj, member, value, setter) => {
1175
+ var __privateSet$5 = (obj, member, value, setter) => {
987
1176
  __accessCheck$5(obj, member, "write to private field");
988
1177
  setter ? setter.call(obj, value) : member.set(obj, value);
989
1178
  return value;
990
1179
  };
991
1180
  var _table$1, _repository, _data;
992
1181
  const _Query = class {
993
- constructor(repository, table, data, parent) {
1182
+ constructor(repository, table, data, rawParent) {
994
1183
  __privateAdd$5(this, _table$1, void 0);
995
1184
  __privateAdd$5(this, _repository, void 0);
996
1185
  __privateAdd$5(this, _data, { filter: {} });
997
1186
  this.meta = { page: { cursor: "start", more: true } };
998
- this.records = [];
999
- __privateSet$4(this, _table$1, table);
1187
+ this.records = new RecordArray(this, []);
1188
+ __privateSet$5(this, _table$1, table);
1000
1189
  if (repository) {
1001
- __privateSet$4(this, _repository, repository);
1190
+ __privateSet$5(this, _repository, repository);
1002
1191
  } else {
1003
- __privateSet$4(this, _repository, this);
1192
+ __privateSet$5(this, _repository, this);
1004
1193
  }
1194
+ const parent = cleanParent(data, rawParent);
1005
1195
  __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
1006
1196
  __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
1007
1197
  __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
@@ -1054,13 +1244,18 @@ const _Query = class {
1054
1244
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1055
1245
  }
1056
1246
  }
1057
- sort(column, direction) {
1247
+ sort(column, direction = "asc") {
1058
1248
  const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
1059
1249
  const sort = [...originalSort, { column, direction }];
1060
1250
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
1061
1251
  }
1062
1252
  select(columns) {
1063
- return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { columns }, __privateGet$5(this, _data));
1253
+ return new _Query(
1254
+ __privateGet$5(this, _repository),
1255
+ __privateGet$5(this, _table$1),
1256
+ { columns },
1257
+ __privateGet$5(this, _data)
1258
+ );
1064
1259
  }
1065
1260
  getPaginated(options = {}) {
1066
1261
  const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
@@ -1083,8 +1278,11 @@ const _Query = class {
1083
1278
  }
1084
1279
  }
1085
1280
  async getMany(options = {}) {
1086
- const { records } = await this.getPaginated(options);
1087
- return records;
1281
+ const page = await this.getPaginated(options);
1282
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1283
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1284
+ }
1285
+ return page.records;
1088
1286
  }
1089
1287
  async getAll(options = {}) {
1090
1288
  const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
@@ -1098,6 +1296,12 @@ const _Query = class {
1098
1296
  const records = await this.getMany({ ...options, pagination: { size: 1 } });
1099
1297
  return records[0] ?? null;
1100
1298
  }
1299
+ async getFirstOrThrow(options = {}) {
1300
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1301
+ if (records[0] === void 0)
1302
+ throw new Error("No results found.");
1303
+ return records[0];
1304
+ }
1101
1305
  cache(ttl) {
1102
1306
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1103
1307
  }
@@ -1121,12 +1325,20 @@ let Query = _Query;
1121
1325
  _table$1 = new WeakMap();
1122
1326
  _repository = new WeakMap();
1123
1327
  _data = new WeakMap();
1328
+ function cleanParent(data, parent) {
1329
+ if (isCursorPaginationOptions(data.pagination)) {
1330
+ return { ...parent, sorting: void 0, filter: void 0 };
1331
+ }
1332
+ return parent;
1333
+ }
1124
1334
 
1125
1335
  function isIdentifiable(x) {
1126
1336
  return isObject(x) && isString(x?.id);
1127
1337
  }
1128
1338
  function isXataRecord(x) {
1129
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1339
+ const record = x;
1340
+ const metadata = record?.getMetadata();
1341
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1130
1342
  }
1131
1343
 
1132
1344
  function isSortFilterString(value) {
@@ -1165,7 +1377,7 @@ var __privateAdd$4 = (obj, member, value) => {
1165
1377
  throw TypeError("Cannot add the same private member more than once");
1166
1378
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1167
1379
  };
1168
- var __privateSet$3 = (obj, member, value, setter) => {
1380
+ var __privateSet$4 = (obj, member, value, setter) => {
1169
1381
  __accessCheck$4(obj, member, "write to private field");
1170
1382
  setter ? setter.call(obj, value) : member.set(obj, value);
1171
1383
  return value;
@@ -1174,7 +1386,7 @@ var __privateMethod$2 = (obj, member, method) => {
1174
1386
  __accessCheck$4(obj, member, "access private method");
1175
1387
  return method;
1176
1388
  };
1177
- 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;
1389
+ 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;
1178
1390
  class Repository extends Query {
1179
1391
  }
1180
1392
  class RestRepository extends Query {
@@ -1186,175 +1398,254 @@ class RestRepository extends Query {
1186
1398
  __privateAdd$4(this, _updateRecordWithID);
1187
1399
  __privateAdd$4(this, _upsertRecordWithID);
1188
1400
  __privateAdd$4(this, _deleteRecord);
1189
- __privateAdd$4(this, _invalidateCache);
1190
- __privateAdd$4(this, _setCacheRecord);
1191
- __privateAdd$4(this, _getCacheRecord);
1192
1401
  __privateAdd$4(this, _setCacheQuery);
1193
1402
  __privateAdd$4(this, _getCacheQuery);
1194
- __privateAdd$4(this, _getSchema$1);
1403
+ __privateAdd$4(this, _getSchemaTables$1);
1195
1404
  __privateAdd$4(this, _table, void 0);
1196
1405
  __privateAdd$4(this, _getFetchProps, void 0);
1406
+ __privateAdd$4(this, _db, void 0);
1197
1407
  __privateAdd$4(this, _cache, void 0);
1198
- __privateAdd$4(this, _schema$1, void 0);
1199
- __privateSet$3(this, _table, options.table);
1200
- __privateSet$3(this, _getFetchProps, options.pluginOptions.getFetchProps);
1201
- this.db = options.db;
1202
- __privateSet$3(this, _cache, options.pluginOptions.cache);
1203
- }
1204
- async create(a, b) {
1205
- if (Array.isArray(a)) {
1206
- const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1207
- await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1208
- return records;
1209
- }
1210
- if (isString(a) && isObject(b)) {
1211
- if (a === "")
1212
- throw new Error("The id can't be empty");
1213
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1214
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1215
- return record;
1216
- }
1217
- if (isObject(a) && isString(a.id)) {
1218
- if (a.id === "")
1219
- throw new Error("The id can't be empty");
1220
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1221
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1222
- return record;
1223
- }
1224
- if (isObject(a)) {
1225
- const record = await __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1226
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1227
- return record;
1228
- }
1229
- throw new Error("Invalid arguments for create method");
1230
- }
1231
- async read(recordId) {
1232
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, recordId);
1233
- if (cacheRecord)
1234
- return cacheRecord;
1235
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1236
- try {
1237
- const response = await getRecord({
1238
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1239
- ...fetchProps
1408
+ __privateAdd$4(this, _schemaTables$2, void 0);
1409
+ __privateAdd$4(this, _trace, void 0);
1410
+ __privateSet$4(this, _table, options.table);
1411
+ __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1412
+ __privateSet$4(this, _db, options.db);
1413
+ __privateSet$4(this, _cache, options.pluginOptions.cache);
1414
+ __privateSet$4(this, _schemaTables$2, options.schemaTables);
1415
+ const trace = options.pluginOptions.trace ?? defaultTrace;
1416
+ __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
1417
+ return trace(name, fn, {
1418
+ ...options2,
1419
+ [TraceAttributes.TABLE]: __privateGet$4(this, _table),
1420
+ [TraceAttributes.VERSION]: VERSION
1240
1421
  });
1241
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1242
- return initObject(this.db, schema, __privateGet$4(this, _table), response);
1243
- } catch (e) {
1244
- if (isObject(e) && e.status === 404) {
1245
- return null;
1422
+ });
1423
+ }
1424
+ async create(a, b, c) {
1425
+ return __privateGet$4(this, _trace).call(this, "create", async () => {
1426
+ if (Array.isArray(a)) {
1427
+ if (a.length === 0)
1428
+ return [];
1429
+ const columns = isStringArray(b) ? b : void 0;
1430
+ return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
1246
1431
  }
1247
- throw e;
1248
- }
1432
+ if (isString(a) && isObject(b)) {
1433
+ if (a === "")
1434
+ throw new Error("The id can't be empty");
1435
+ const columns = isStringArray(c) ? c : void 0;
1436
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns);
1437
+ }
1438
+ if (isObject(a) && isString(a.id)) {
1439
+ if (a.id === "")
1440
+ throw new Error("The id can't be empty");
1441
+ const columns = isStringArray(b) ? b : void 0;
1442
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1443
+ }
1444
+ if (isObject(a)) {
1445
+ const columns = isStringArray(b) ? b : void 0;
1446
+ return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
1447
+ }
1448
+ throw new Error("Invalid arguments for create method");
1449
+ });
1249
1450
  }
1250
- async update(a, b) {
1251
- if (Array.isArray(a)) {
1252
- if (a.length > 100) {
1253
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1451
+ async read(a, b) {
1452
+ return __privateGet$4(this, _trace).call(this, "read", async () => {
1453
+ const columns = isStringArray(b) ? b : ["*"];
1454
+ if (Array.isArray(a)) {
1455
+ if (a.length === 0)
1456
+ return [];
1457
+ const ids = a.map((item) => extractId(item));
1458
+ const finalObjects = await this.getAll({ filter: { id: { $any: compact(ids) } }, columns });
1459
+ const dictionary = finalObjects.reduce((acc, object) => {
1460
+ acc[object.id] = object;
1461
+ return acc;
1462
+ }, {});
1463
+ return ids.map((id2) => dictionary[id2 ?? ""] ?? null);
1254
1464
  }
1255
- return Promise.all(a.map((object) => this.update(object)));
1256
- }
1257
- if (isString(a) && isObject(b)) {
1258
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1259
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1260
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1261
- return record;
1262
- }
1263
- if (isObject(a) && isString(a.id)) {
1264
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1265
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1266
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1267
- return record;
1268
- }
1269
- throw new Error("Invalid arguments for update method");
1465
+ const id = extractId(a);
1466
+ if (id) {
1467
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1468
+ try {
1469
+ const response = await getRecord({
1470
+ pathParams: {
1471
+ workspace: "{workspaceId}",
1472
+ dbBranchName: "{dbBranch}",
1473
+ tableName: __privateGet$4(this, _table),
1474
+ recordId: id
1475
+ },
1476
+ queryParams: { columns },
1477
+ ...fetchProps
1478
+ });
1479
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1480
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1481
+ } catch (e) {
1482
+ if (isObject(e) && e.status === 404) {
1483
+ return null;
1484
+ }
1485
+ throw e;
1486
+ }
1487
+ }
1488
+ return null;
1489
+ });
1270
1490
  }
1271
- async createOrUpdate(a, b) {
1272
- if (Array.isArray(a)) {
1273
- if (a.length > 100) {
1274
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1491
+ async readOrThrow(a, b) {
1492
+ return __privateGet$4(this, _trace).call(this, "readOrThrow", async () => {
1493
+ const result = await this.read(a, b);
1494
+ if (Array.isArray(result)) {
1495
+ const missingIds = compact(
1496
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
1497
+ );
1498
+ if (missingIds.length > 0) {
1499
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
1500
+ }
1501
+ return result;
1275
1502
  }
1276
- return Promise.all(a.map((object) => this.createOrUpdate(object)));
1277
- }
1278
- if (isString(a) && isObject(b)) {
1279
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1280
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1281
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1282
- return record;
1283
- }
1284
- if (isObject(a) && isString(a.id)) {
1285
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1286
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1287
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1288
- return record;
1289
- }
1290
- throw new Error("Invalid arguments for createOrUpdate method");
1503
+ if (result === null) {
1504
+ const id = extractId(a) ?? "unknown";
1505
+ throw new Error(`Record with id ${id} not found`);
1506
+ }
1507
+ return result;
1508
+ });
1291
1509
  }
1292
- async delete(a) {
1293
- if (Array.isArray(a)) {
1294
- if (a.length > 100) {
1295
- console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1510
+ async update(a, b, c) {
1511
+ return __privateGet$4(this, _trace).call(this, "update", async () => {
1512
+ if (Array.isArray(a)) {
1513
+ if (a.length === 0)
1514
+ return [];
1515
+ if (a.length > 100) {
1516
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1517
+ }
1518
+ const columns = isStringArray(b) ? b : ["*"];
1519
+ return Promise.all(a.map((object) => this.update(object, columns)));
1296
1520
  }
1297
- await Promise.all(a.map((id) => this.delete(id)));
1298
- return;
1299
- }
1300
- if (isString(a)) {
1301
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1302
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1303
- return;
1304
- }
1305
- if (isObject(a) && isString(a.id)) {
1306
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1307
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1308
- return;
1309
- }
1310
- throw new Error("Invalid arguments for delete method");
1521
+ if (isString(a) && isObject(b)) {
1522
+ const columns = isStringArray(c) ? c : void 0;
1523
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns);
1524
+ }
1525
+ if (isObject(a) && isString(a.id)) {
1526
+ const columns = isStringArray(b) ? b : void 0;
1527
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1528
+ }
1529
+ throw new Error("Invalid arguments for update method");
1530
+ });
1531
+ }
1532
+ async updateOrThrow(a, b, c) {
1533
+ return __privateGet$4(this, _trace).call(this, "updateOrThrow", async () => {
1534
+ const result = await this.update(a, b, c);
1535
+ if (Array.isArray(result)) {
1536
+ const missingIds = compact(
1537
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
1538
+ );
1539
+ if (missingIds.length > 0) {
1540
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
1541
+ }
1542
+ return result;
1543
+ }
1544
+ if (result === null) {
1545
+ const id = extractId(a) ?? "unknown";
1546
+ throw new Error(`Record with id ${id} not found`);
1547
+ }
1548
+ return result;
1549
+ });
1550
+ }
1551
+ async createOrUpdate(a, b, c) {
1552
+ return __privateGet$4(this, _trace).call(this, "createOrUpdate", async () => {
1553
+ if (Array.isArray(a)) {
1554
+ if (a.length === 0)
1555
+ return [];
1556
+ if (a.length > 100) {
1557
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1558
+ }
1559
+ const columns = isStringArray(b) ? b : ["*"];
1560
+ return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
1561
+ }
1562
+ if (isString(a) && isObject(b)) {
1563
+ const columns = isStringArray(c) ? c : void 0;
1564
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns);
1565
+ }
1566
+ if (isObject(a) && isString(a.id)) {
1567
+ const columns = isStringArray(c) ? c : void 0;
1568
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1569
+ }
1570
+ throw new Error("Invalid arguments for createOrUpdate method");
1571
+ });
1572
+ }
1573
+ async delete(a, b) {
1574
+ return __privateGet$4(this, _trace).call(this, "delete", async () => {
1575
+ if (Array.isArray(a)) {
1576
+ if (a.length === 0)
1577
+ return [];
1578
+ if (a.length > 100) {
1579
+ console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1580
+ }
1581
+ return Promise.all(a.map((id) => this.delete(id, b)));
1582
+ }
1583
+ if (isString(a)) {
1584
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
1585
+ }
1586
+ if (isObject(a) && isString(a.id)) {
1587
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id, b);
1588
+ }
1589
+ throw new Error("Invalid arguments for delete method");
1590
+ });
1591
+ }
1592
+ async deleteOrThrow(a, b) {
1593
+ return __privateGet$4(this, _trace).call(this, "delete", async () => {
1594
+ throw new Error("Not implemented");
1595
+ });
1311
1596
  }
1312
1597
  async search(query, options = {}) {
1313
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1314
- const { records } = await searchTable({
1315
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1316
- body: {
1317
- query,
1318
- fuzziness: options.fuzziness,
1319
- filter: options.filter
1320
- },
1321
- ...fetchProps
1598
+ return __privateGet$4(this, _trace).call(this, "search", async () => {
1599
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1600
+ const { records } = await searchTable({
1601
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1602
+ body: {
1603
+ query,
1604
+ fuzziness: options.fuzziness,
1605
+ prefix: options.prefix,
1606
+ highlight: options.highlight,
1607
+ filter: options.filter,
1608
+ boosters: options.boosters
1609
+ },
1610
+ ...fetchProps
1611
+ });
1612
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1613
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1322
1614
  });
1323
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1324
- return records.map((item) => initObject(this.db, schema, __privateGet$4(this, _table), item));
1325
1615
  }
1326
1616
  async query(query) {
1327
- const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1328
- if (cacheQuery)
1329
- return new Page(query, cacheQuery.meta, cacheQuery.records);
1330
- const data = query.getQueryOptions();
1331
- const filter = Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0;
1332
- const sort = data.sort !== void 0 ? buildSortFilter(data.sort) : void 0;
1333
- const isCursorPagination = isCursorPaginationOptions(data.pagination);
1334
- const body = {
1335
- filter: isCursorPagination ? void 0 : filter,
1336
- sort: isCursorPagination ? void 0 : sort,
1337
- page: data.pagination,
1338
- columns: data.columns
1339
- };
1340
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1341
- const { meta, records: objects } = await queryTable({
1342
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1343
- body,
1344
- ...fetchProps
1617
+ return __privateGet$4(this, _trace).call(this, "query", async () => {
1618
+ const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1619
+ if (cacheQuery)
1620
+ return new Page(query, cacheQuery.meta, cacheQuery.records);
1621
+ const data = query.getQueryOptions();
1622
+ const body = {
1623
+ filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1624
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1625
+ page: data.pagination,
1626
+ columns: data.columns
1627
+ };
1628
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1629
+ const { meta, records: objects } = await queryTable({
1630
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1631
+ body,
1632
+ ...fetchProps
1633
+ });
1634
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1635
+ const records = objects.map((record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record));
1636
+ await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1637
+ return new Page(query, meta, records);
1345
1638
  });
1346
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1347
- const records = objects.map((record) => initObject(this.db, schema, __privateGet$4(this, _table), record));
1348
- await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1349
- return new Page(query, meta, records);
1350
1639
  }
1351
1640
  }
1352
1641
  _table = new WeakMap();
1353
1642
  _getFetchProps = new WeakMap();
1643
+ _db = new WeakMap();
1354
1644
  _cache = new WeakMap();
1355
- _schema$1 = new WeakMap();
1645
+ _schemaTables$2 = new WeakMap();
1646
+ _trace = new WeakMap();
1356
1647
  _insertRecordWithoutId = new WeakSet();
1357
- insertRecordWithoutId_fn = async function(object) {
1648
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1358
1649
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1359
1650
  const record = transformObjectLinks(object);
1360
1651
  const response = await insertRecord({
@@ -1363,17 +1654,15 @@ insertRecordWithoutId_fn = async function(object) {
1363
1654
  dbBranchName: "{dbBranch}",
1364
1655
  tableName: __privateGet$4(this, _table)
1365
1656
  },
1657
+ queryParams: { columns },
1366
1658
  body: record,
1367
1659
  ...fetchProps
1368
1660
  });
1369
- const finalObject = await this.read(response.id);
1370
- if (!finalObject) {
1371
- throw new Error("The server failed to save the record");
1372
- }
1373
- return finalObject;
1661
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1662
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1374
1663
  };
1375
1664
  _insertRecordWithId = new WeakSet();
1376
- insertRecordWithId_fn = async function(recordId, object) {
1665
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
1377
1666
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1378
1667
  const record = transformObjectLinks(object);
1379
1668
  const response = await insertRecordWithID({
@@ -1384,87 +1673,63 @@ insertRecordWithId_fn = async function(recordId, object) {
1384
1673
  recordId
1385
1674
  },
1386
1675
  body: record,
1387
- queryParams: { createOnly: true },
1676
+ queryParams: { createOnly: true, columns },
1388
1677
  ...fetchProps
1389
1678
  });
1390
- const finalObject = await this.read(response.id);
1391
- if (!finalObject) {
1392
- throw new Error("The server failed to save the record");
1393
- }
1394
- return finalObject;
1679
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1680
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1395
1681
  };
1396
1682
  _bulkInsertTableRecords = new WeakSet();
1397
- bulkInsertTableRecords_fn = async function(objects) {
1683
+ bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
1398
1684
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1399
1685
  const records = objects.map((object) => transformObjectLinks(object));
1400
1686
  const response = await bulkInsertTableRecords({
1401
1687
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1688
+ queryParams: { columns },
1402
1689
  body: { records },
1403
1690
  ...fetchProps
1404
1691
  });
1405
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1406
- if (finalObjects.length !== objects.length) {
1407
- throw new Error("The server failed to save some records");
1692
+ if (!isResponseWithRecords(response)) {
1693
+ throw new Error("Request included columns but server didn't include them");
1408
1694
  }
1409
- return finalObjects;
1695
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1696
+ return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1410
1697
  };
1411
1698
  _updateRecordWithID = new WeakSet();
1412
- updateRecordWithID_fn = async function(recordId, object) {
1699
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1413
1700
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1414
1701
  const record = transformObjectLinks(object);
1415
1702
  const response = await updateRecordWithID({
1416
1703
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1704
+ queryParams: { columns },
1417
1705
  body: record,
1418
1706
  ...fetchProps
1419
1707
  });
1420
- const item = await this.read(response.id);
1421
- if (!item)
1422
- throw new Error("The server failed to save the record");
1423
- return item;
1708
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1709
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1424
1710
  };
1425
1711
  _upsertRecordWithID = new WeakSet();
1426
- upsertRecordWithID_fn = async function(recordId, object) {
1712
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1427
1713
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1428
1714
  const response = await upsertRecordWithID({
1429
1715
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1716
+ queryParams: { columns },
1430
1717
  body: object,
1431
1718
  ...fetchProps
1432
1719
  });
1433
- const item = await this.read(response.id);
1434
- if (!item)
1435
- throw new Error("The server failed to save the record");
1436
- return item;
1720
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1721
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1437
1722
  };
1438
1723
  _deleteRecord = new WeakSet();
1439
- deleteRecord_fn = async function(recordId) {
1724
+ deleteRecord_fn = async function(recordId, columns = ["*"]) {
1440
1725
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1441
- await deleteRecord({
1726
+ const response = await deleteRecord({
1442
1727
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1728
+ queryParams: { columns },
1443
1729
  ...fetchProps
1444
1730
  });
1445
- };
1446
- _invalidateCache = new WeakSet();
1447
- invalidateCache_fn = async function(recordId) {
1448
- await __privateGet$4(this, _cache).delete(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1449
- const cacheItems = await __privateGet$4(this, _cache).getAll();
1450
- const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1451
- for (const [key, value] of queries) {
1452
- const ids = getIds(value);
1453
- if (ids.includes(recordId))
1454
- await __privateGet$4(this, _cache).delete(key);
1455
- }
1456
- };
1457
- _setCacheRecord = new WeakSet();
1458
- setCacheRecord_fn = async function(record) {
1459
- if (!__privateGet$4(this, _cache).cacheRecords)
1460
- return;
1461
- await __privateGet$4(this, _cache).set(`rec_${__privateGet$4(this, _table)}:${record.id}`, record);
1462
- };
1463
- _getCacheRecord = new WeakSet();
1464
- getCacheRecord_fn = async function(recordId) {
1465
- if (!__privateGet$4(this, _cache).cacheRecords)
1466
- return null;
1467
- return __privateGet$4(this, _cache).get(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1731
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1732
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1468
1733
  };
1469
1734
  _setCacheQuery = new WeakSet();
1470
1735
  setCacheQuery_fn = async function(query, meta, records) {
@@ -1482,17 +1747,17 @@ getCacheQuery_fn = async function(query) {
1482
1747
  const hasExpired = result.date.getTime() + ttl < Date.now();
1483
1748
  return hasExpired ? null : result;
1484
1749
  };
1485
- _getSchema$1 = new WeakSet();
1486
- getSchema_fn$1 = async function() {
1487
- if (__privateGet$4(this, _schema$1))
1488
- return __privateGet$4(this, _schema$1);
1750
+ _getSchemaTables$1 = new WeakSet();
1751
+ getSchemaTables_fn$1 = async function() {
1752
+ if (__privateGet$4(this, _schemaTables$2))
1753
+ return __privateGet$4(this, _schemaTables$2);
1489
1754
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1490
1755
  const { schema } = await getBranchDetails({
1491
1756
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1492
1757
  ...fetchProps
1493
1758
  });
1494
- __privateSet$3(this, _schema$1, schema);
1495
- return schema;
1759
+ __privateSet$4(this, _schemaTables$2, schema.tables);
1760
+ return schema.tables;
1496
1761
  };
1497
1762
  const transformObjectLinks = (object) => {
1498
1763
  return Object.entries(object).reduce((acc, [key, value]) => {
@@ -1501,20 +1766,21 @@ const transformObjectLinks = (object) => {
1501
1766
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1502
1767
  }, {});
1503
1768
  };
1504
- const initObject = (db, schema, table, object) => {
1769
+ const initObject = (db, schemaTables, table, object) => {
1505
1770
  const result = {};
1506
- Object.assign(result, object);
1507
- const { columns } = schema.tables.find(({ name }) => name === table) ?? {};
1771
+ const { xata, ...rest } = object ?? {};
1772
+ Object.assign(result, rest);
1773
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
1508
1774
  if (!columns)
1509
1775
  console.error(`Table ${table} not found in schema`);
1510
1776
  for (const column of columns ?? []) {
1511
1777
  const value = result[column.name];
1512
1778
  switch (column.type) {
1513
1779
  case "datetime": {
1514
- const date = new Date(value);
1515
- if (isNaN(date.getTime())) {
1780
+ const date = value !== void 0 ? new Date(value) : void 0;
1781
+ if (date && isNaN(date.getTime())) {
1516
1782
  console.error(`Failed to parse date ${value} for field ${column.name}`);
1517
- } else {
1783
+ } else if (date) {
1518
1784
  result[column.name] = date;
1519
1785
  }
1520
1786
  break;
@@ -1524,35 +1790,39 @@ const initObject = (db, schema, table, object) => {
1524
1790
  if (!linkTable) {
1525
1791
  console.error(`Failed to parse link for field ${column.name}`);
1526
1792
  } else if (isObject(value)) {
1527
- result[column.name] = initObject(db, schema, linkTable, value);
1793
+ result[column.name] = initObject(db, schemaTables, linkTable, value);
1528
1794
  }
1529
1795
  break;
1530
1796
  }
1531
1797
  }
1532
1798
  }
1533
- result.read = function() {
1534
- return db[table].read(result["id"]);
1799
+ result.read = function(columns2) {
1800
+ return db[table].read(result["id"], columns2);
1535
1801
  };
1536
- result.update = function(data) {
1537
- return db[table].update(result["id"], data);
1802
+ result.update = function(data, columns2) {
1803
+ return db[table].update(result["id"], data, columns2);
1538
1804
  };
1539
1805
  result.delete = function() {
1540
1806
  return db[table].delete(result["id"]);
1541
1807
  };
1542
- for (const prop of ["read", "update", "delete"]) {
1808
+ result.getMetadata = function() {
1809
+ return xata;
1810
+ };
1811
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1543
1812
  Object.defineProperty(result, prop, { enumerable: false });
1544
1813
  }
1545
1814
  Object.freeze(result);
1546
1815
  return result;
1547
1816
  };
1548
- function getIds(value) {
1549
- if (Array.isArray(value)) {
1550
- return value.map((item) => getIds(item)).flat();
1551
- }
1552
- if (!isObject(value))
1553
- return [];
1554
- const nestedIds = Object.values(value).map((item) => getIds(item)).flat();
1555
- return isString(value.id) ? [value.id, ...nestedIds] : nestedIds;
1817
+ function isResponseWithRecords(value) {
1818
+ return isObject(value) && Array.isArray(value.records);
1819
+ }
1820
+ function extractId(value) {
1821
+ if (isString(value))
1822
+ return value;
1823
+ if (isObject(value) && isString(value.id))
1824
+ return value.id;
1825
+ return void 0;
1556
1826
  }
1557
1827
 
1558
1828
  var __accessCheck$3 = (obj, member, msg) => {
@@ -1568,7 +1838,7 @@ var __privateAdd$3 = (obj, member, value) => {
1568
1838
  throw TypeError("Cannot add the same private member more than once");
1569
1839
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1570
1840
  };
1571
- var __privateSet$2 = (obj, member, value, setter) => {
1841
+ var __privateSet$3 = (obj, member, value, setter) => {
1572
1842
  __accessCheck$3(obj, member, "write to private field");
1573
1843
  setter ? setter.call(obj, value) : member.set(obj, value);
1574
1844
  return value;
@@ -1577,9 +1847,8 @@ var _map;
1577
1847
  class SimpleCache {
1578
1848
  constructor(options = {}) {
1579
1849
  __privateAdd$3(this, _map, void 0);
1580
- __privateSet$2(this, _map, /* @__PURE__ */ new Map());
1850
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1581
1851
  this.capacity = options.max ?? 500;
1582
- this.cacheRecords = options.cacheRecords ?? true;
1583
1852
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1584
1853
  }
1585
1854
  async getAll() {
@@ -1605,18 +1874,25 @@ class SimpleCache {
1605
1874
  }
1606
1875
  _map = new WeakMap();
1607
1876
 
1608
- const gt = (value) => ({ $gt: value });
1609
- const ge = (value) => ({ $ge: value });
1610
- const gte = (value) => ({ $ge: value });
1611
- const lt = (value) => ({ $lt: value });
1612
- const lte = (value) => ({ $le: value });
1613
- const le = (value) => ({ $le: value });
1877
+ const greaterThan = (value) => ({ $gt: value });
1878
+ const gt = greaterThan;
1879
+ const greaterThanEquals = (value) => ({ $ge: value });
1880
+ const greaterEquals = greaterThanEquals;
1881
+ const gte = greaterThanEquals;
1882
+ const ge = greaterThanEquals;
1883
+ const lessThan = (value) => ({ $lt: value });
1884
+ const lt = lessThan;
1885
+ const lessThanEquals = (value) => ({ $le: value });
1886
+ const lessEquals = lessThanEquals;
1887
+ const lte = lessThanEquals;
1888
+ const le = lessThanEquals;
1614
1889
  const exists = (column) => ({ $exists: column });
1615
1890
  const notExists = (column) => ({ $notExists: column });
1616
1891
  const startsWith = (value) => ({ $startsWith: value });
1617
1892
  const endsWith = (value) => ({ $endsWith: value });
1618
1893
  const pattern = (value) => ({ $pattern: value });
1619
1894
  const is = (value) => ({ $is: value });
1895
+ const equals = is;
1620
1896
  const isNot = (value) => ({ $isNot: value });
1621
1897
  const contains = (value) => ({ $contains: value });
1622
1898
  const includes = (value) => ({ $includes: value });
@@ -1637,31 +1913,42 @@ var __privateAdd$2 = (obj, member, value) => {
1637
1913
  throw TypeError("Cannot add the same private member more than once");
1638
1914
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1639
1915
  };
1640
- var _tables;
1916
+ var __privateSet$2 = (obj, member, value, setter) => {
1917
+ __accessCheck$2(obj, member, "write to private field");
1918
+ setter ? setter.call(obj, value) : member.set(obj, value);
1919
+ return value;
1920
+ };
1921
+ var _tables, _schemaTables$1;
1641
1922
  class SchemaPlugin extends XataPlugin {
1642
- constructor(tableNames) {
1923
+ constructor(schemaTables) {
1643
1924
  super();
1644
- this.tableNames = tableNames;
1645
1925
  __privateAdd$2(this, _tables, {});
1926
+ __privateAdd$2(this, _schemaTables$1, void 0);
1927
+ __privateSet$2(this, _schemaTables$1, schemaTables);
1646
1928
  }
1647
1929
  build(pluginOptions) {
1648
- const db = new Proxy({}, {
1649
- get: (_target, table) => {
1650
- if (!isString(table))
1651
- throw new Error("Invalid table name");
1652
- if (__privateGet$2(this, _tables)[table] === void 0) {
1653
- __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table });
1930
+ const db = new Proxy(
1931
+ {},
1932
+ {
1933
+ get: (_target, table) => {
1934
+ if (!isString(table))
1935
+ throw new Error("Invalid table name");
1936
+ if (__privateGet$2(this, _tables)[table] === void 0) {
1937
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1938
+ }
1939
+ return __privateGet$2(this, _tables)[table];
1654
1940
  }
1655
- return __privateGet$2(this, _tables)[table];
1656
1941
  }
1657
- });
1658
- for (const table of this.tableNames ?? []) {
1659
- db[table] = new RestRepository({ db, pluginOptions, table });
1942
+ );
1943
+ const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
1944
+ for (const table of tableNames) {
1945
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1660
1946
  }
1661
1947
  return db;
1662
1948
  }
1663
1949
  }
1664
1950
  _tables = new WeakMap();
1951
+ _schemaTables$1 = new WeakMap();
1665
1952
 
1666
1953
  var __accessCheck$1 = (obj, member, msg) => {
1667
1954
  if (!member.has(obj))
@@ -1685,82 +1972,77 @@ var __privateMethod$1 = (obj, member, method) => {
1685
1972
  __accessCheck$1(obj, member, "access private method");
1686
1973
  return method;
1687
1974
  };
1688
- var _schema, _search, search_fn, _getSchema, getSchema_fn;
1975
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1689
1976
  class SearchPlugin extends XataPlugin {
1690
- constructor(db) {
1977
+ constructor(db, schemaTables) {
1691
1978
  super();
1692
1979
  this.db = db;
1693
1980
  __privateAdd$1(this, _search);
1694
- __privateAdd$1(this, _getSchema);
1695
- __privateAdd$1(this, _schema, void 0);
1981
+ __privateAdd$1(this, _getSchemaTables);
1982
+ __privateAdd$1(this, _schemaTables, void 0);
1983
+ __privateSet$1(this, _schemaTables, schemaTables);
1696
1984
  }
1697
1985
  build({ getFetchProps }) {
1698
1986
  return {
1699
1987
  all: async (query, options = {}) => {
1700
1988
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1701
- const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
1989
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1702
1990
  return records.map((record) => {
1703
1991
  const { table = "orphan" } = record.xata;
1704
- return { table, record: initObject(this.db, schema, table, record) };
1992
+ return { table, record: initObject(this.db, schemaTables, table, record) };
1705
1993
  });
1706
1994
  },
1707
1995
  byTable: async (query, options = {}) => {
1708
1996
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1709
- const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
1997
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1710
1998
  return records.reduce((acc, record) => {
1711
1999
  const { table = "orphan" } = record.xata;
1712
2000
  const items = acc[table] ?? [];
1713
- const item = initObject(this.db, schema, table, record);
2001
+ const item = initObject(this.db, schemaTables, table, record);
1714
2002
  return { ...acc, [table]: [...items, item] };
1715
2003
  }, {});
1716
2004
  }
1717
2005
  };
1718
2006
  }
1719
2007
  }
1720
- _schema = new WeakMap();
2008
+ _schemaTables = new WeakMap();
1721
2009
  _search = new WeakSet();
1722
2010
  search_fn = async function(query, options, getFetchProps) {
1723
2011
  const fetchProps = await getFetchProps();
1724
- const { tables, fuzziness } = options ?? {};
2012
+ const { tables, fuzziness, highlight, prefix } = options ?? {};
1725
2013
  const { records } = await searchBranch({
1726
2014
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1727
- body: { tables, query, fuzziness },
2015
+ body: { tables, query, fuzziness, prefix, highlight },
1728
2016
  ...fetchProps
1729
2017
  });
1730
2018
  return records;
1731
2019
  };
1732
- _getSchema = new WeakSet();
1733
- getSchema_fn = async function(getFetchProps) {
1734
- if (__privateGet$1(this, _schema))
1735
- return __privateGet$1(this, _schema);
2020
+ _getSchemaTables = new WeakSet();
2021
+ getSchemaTables_fn = async function(getFetchProps) {
2022
+ if (__privateGet$1(this, _schemaTables))
2023
+ return __privateGet$1(this, _schemaTables);
1736
2024
  const fetchProps = await getFetchProps();
1737
2025
  const { schema } = await getBranchDetails({
1738
2026
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1739
2027
  ...fetchProps
1740
2028
  });
1741
- __privateSet$1(this, _schema, schema);
1742
- return schema;
2029
+ __privateSet$1(this, _schemaTables, schema.tables);
2030
+ return schema.tables;
1743
2031
  };
1744
2032
 
1745
2033
  const isBranchStrategyBuilder = (strategy) => {
1746
2034
  return typeof strategy === "function";
1747
2035
  };
1748
2036
 
1749
- const envBranchNames = [
1750
- "XATA_BRANCH",
1751
- "VERCEL_GIT_COMMIT_REF",
1752
- "CF_PAGES_BRANCH",
1753
- "BRANCH"
1754
- ];
1755
2037
  async function getCurrentBranchName(options) {
1756
- const env = getBranchByEnvVariable();
1757
- if (env) {
1758
- const details = await getDatabaseBranch(env, options);
2038
+ const { branch, envBranch } = getEnvironment();
2039
+ if (branch) {
2040
+ const details = await getDatabaseBranch(branch, options);
1759
2041
  if (details)
1760
- return env;
1761
- console.warn(`Branch ${env} not found in Xata. Ignoring...`);
2042
+ return branch;
2043
+ console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
1762
2044
  }
1763
- const gitBranch = await getGitBranch();
2045
+ const gitBranch = envBranch || await getGitBranch();
1764
2046
  return resolveXataBranch(gitBranch, options);
1765
2047
  }
1766
2048
  async function getCurrentBranchDetails(options) {
@@ -1771,18 +2053,24 @@ async function resolveXataBranch(gitBranch, options) {
1771
2053
  const databaseURL = options?.databaseURL || getDatabaseURL();
1772
2054
  const apiKey = options?.apiKey || getAPIKey();
1773
2055
  if (!databaseURL)
1774
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
2056
+ throw new Error(
2057
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2058
+ );
1775
2059
  if (!apiKey)
1776
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
2060
+ throw new Error(
2061
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2062
+ );
1777
2063
  const [protocol, , host, , dbName] = databaseURL.split("/");
1778
2064
  const [workspace] = host.split(".");
2065
+ const { fallbackBranch } = getEnvironment();
1779
2066
  const { branch } = await resolveBranch({
1780
2067
  apiKey,
1781
2068
  apiUrl: databaseURL,
1782
2069
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1783
2070
  workspacesApiUrl: `${protocol}//${host}`,
1784
2071
  pathParams: { dbName, workspace },
1785
- queryParams: { gitBranch, fallbackBranch: getEnvVariable("XATA_FALLBACK_BRANCH") }
2072
+ queryParams: { gitBranch, fallbackBranch },
2073
+ trace: defaultTrace
1786
2074
  });
1787
2075
  return branch;
1788
2076
  }
@@ -1790,9 +2078,13 @@ async function getDatabaseBranch(branch, options) {
1790
2078
  const databaseURL = options?.databaseURL || getDatabaseURL();
1791
2079
  const apiKey = options?.apiKey || getAPIKey();
1792
2080
  if (!databaseURL)
1793
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
2081
+ throw new Error(
2082
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2083
+ );
1794
2084
  if (!apiKey)
1795
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
2085
+ throw new Error(
2086
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2087
+ );
1796
2088
  const [protocol, , host, , database] = databaseURL.split("/");
1797
2089
  const [workspace] = host.split(".");
1798
2090
  const dbBranchName = `${database}:${branch}`;
@@ -1802,10 +2094,8 @@ async function getDatabaseBranch(branch, options) {
1802
2094
  apiUrl: databaseURL,
1803
2095
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1804
2096
  workspacesApiUrl: `${protocol}//${host}`,
1805
- pathParams: {
1806
- dbBranchName,
1807
- workspace
1808
- }
2097
+ pathParams: { dbBranchName, workspace },
2098
+ trace: defaultTrace
1809
2099
  });
1810
2100
  } catch (err) {
1811
2101
  if (isObject(err) && err.status === 404)
@@ -1813,21 +2103,10 @@ async function getDatabaseBranch(branch, options) {
1813
2103
  throw err;
1814
2104
  }
1815
2105
  }
1816
- function getBranchByEnvVariable() {
1817
- for (const name of envBranchNames) {
1818
- const value = getEnvVariable(name);
1819
- if (value) {
1820
- return value;
1821
- }
1822
- }
1823
- try {
1824
- return XATA_BRANCH;
1825
- } catch (err) {
1826
- }
1827
- }
1828
2106
  function getDatabaseURL() {
1829
2107
  try {
1830
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
2108
+ const { databaseURL } = getEnvironment();
2109
+ return databaseURL;
1831
2110
  } catch (err) {
1832
2111
  return void 0;
1833
2112
  }
@@ -1856,20 +2135,23 @@ var __privateMethod = (obj, member, method) => {
1856
2135
  return method;
1857
2136
  };
1858
2137
  const buildClient = (plugins) => {
1859
- var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
2138
+ var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1860
2139
  return _a = class {
1861
- constructor(options = {}, tables) {
2140
+ constructor(options = {}, schemaTables) {
1862
2141
  __privateAdd(this, _parseOptions);
1863
2142
  __privateAdd(this, _getFetchProps);
1864
2143
  __privateAdd(this, _evaluateBranch);
1865
2144
  __privateAdd(this, _branch, void 0);
2145
+ __privateAdd(this, _options, void 0);
1866
2146
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
2147
+ __privateSet(this, _options, safeOptions);
1867
2148
  const pluginOptions = {
1868
2149
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1869
- cache: safeOptions.cache
2150
+ cache: safeOptions.cache,
2151
+ trace: safeOptions.trace
1870
2152
  };
1871
- const db = new SchemaPlugin(tables).build(pluginOptions);
1872
- const search = new SearchPlugin(db).build(pluginOptions);
2153
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2154
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1873
2155
  this.db = db;
1874
2156
  this.search = search;
1875
2157
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
@@ -1885,22 +2167,26 @@ const buildClient = (plugins) => {
1885
2167
  }
1886
2168
  }
1887
2169
  }
1888
- }, _branch = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
2170
+ async getConfig() {
2171
+ const databaseURL = __privateGet(this, _options).databaseURL;
2172
+ const branch = await __privateGet(this, _options).branch();
2173
+ return { databaseURL, branch };
2174
+ }
2175
+ }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
1889
2176
  const fetch = getFetchImplementation(options?.fetch);
1890
2177
  const databaseURL = options?.databaseURL || getDatabaseURL();
1891
2178
  const apiKey = options?.apiKey || getAPIKey();
1892
- const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
2179
+ const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
2180
+ const trace = options?.trace ?? defaultTrace;
1893
2181
  const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1894
- if (!databaseURL || !apiKey) {
1895
- throw new Error("Options databaseURL and apiKey are required");
2182
+ if (!apiKey) {
2183
+ throw new Error("Option apiKey is required");
1896
2184
  }
1897
- return { fetch, databaseURL, apiKey, branch, cache };
1898
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
1899
- fetch,
1900
- apiKey,
1901
- databaseURL,
1902
- branch
1903
- }) {
2185
+ if (!databaseURL) {
2186
+ throw new Error("Option databaseURL is required");
2187
+ }
2188
+ return { fetch, databaseURL, apiKey, branch, cache, trace };
2189
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace }) {
1904
2190
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
1905
2191
  if (!branchValue)
1906
2192
  throw new Error("Unable to resolve branch value");
@@ -1912,7 +2198,8 @@ const buildClient = (plugins) => {
1912
2198
  const hasBranch = params.dbBranchName ?? params.branch;
1913
2199
  const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branchValue}` : "");
1914
2200
  return databaseURL + newPath;
1915
- }
2201
+ },
2202
+ trace
1916
2203
  };
1917
2204
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1918
2205
  if (__privateGet(this, _branch))
@@ -1935,6 +2222,88 @@ const buildClient = (plugins) => {
1935
2222
  class BaseClient extends buildClient() {
1936
2223
  }
1937
2224
 
2225
+ const META = "__";
2226
+ const VALUE = "___";
2227
+ class Serializer {
2228
+ constructor() {
2229
+ this.classes = {};
2230
+ }
2231
+ add(clazz) {
2232
+ this.classes[clazz.name] = clazz;
2233
+ }
2234
+ toJSON(data) {
2235
+ function visit(obj) {
2236
+ if (Array.isArray(obj))
2237
+ return obj.map(visit);
2238
+ const type = typeof obj;
2239
+ if (type === "undefined")
2240
+ return { [META]: "undefined" };
2241
+ if (type === "bigint")
2242
+ return { [META]: "bigint", [VALUE]: obj.toString() };
2243
+ if (obj === null || type !== "object")
2244
+ return obj;
2245
+ const constructor = obj.constructor;
2246
+ const o = { [META]: constructor.name };
2247
+ for (const [key, value] of Object.entries(obj)) {
2248
+ o[key] = visit(value);
2249
+ }
2250
+ if (constructor === Date)
2251
+ o[VALUE] = obj.toISOString();
2252
+ if (constructor === Map)
2253
+ o[VALUE] = Object.fromEntries(obj);
2254
+ if (constructor === Set)
2255
+ o[VALUE] = [...obj];
2256
+ return o;
2257
+ }
2258
+ return JSON.stringify(visit(data));
2259
+ }
2260
+ fromJSON(json) {
2261
+ return JSON.parse(json, (key, value) => {
2262
+ if (value && typeof value === "object" && !Array.isArray(value)) {
2263
+ const { [META]: clazz, [VALUE]: val, ...rest } = value;
2264
+ const constructor = this.classes[clazz];
2265
+ if (constructor) {
2266
+ return Object.assign(Object.create(constructor.prototype), rest);
2267
+ }
2268
+ if (clazz === "Date")
2269
+ return new Date(val);
2270
+ if (clazz === "Set")
2271
+ return new Set(val);
2272
+ if (clazz === "Map")
2273
+ return new Map(Object.entries(val));
2274
+ if (clazz === "bigint")
2275
+ return BigInt(val);
2276
+ if (clazz === "undefined")
2277
+ return void 0;
2278
+ return rest;
2279
+ }
2280
+ return value;
2281
+ });
2282
+ }
2283
+ }
2284
+ const defaultSerializer = new Serializer();
2285
+ const serialize = (data) => {
2286
+ return defaultSerializer.toJSON(data);
2287
+ };
2288
+ const deserialize = (json) => {
2289
+ return defaultSerializer.fromJSON(json);
2290
+ };
2291
+
2292
+ function buildWorkerRunner(config) {
2293
+ return function xataWorker(name, _worker) {
2294
+ return async (...args) => {
2295
+ const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
2296
+ const result = await fetch(url, {
2297
+ method: "POST",
2298
+ headers: { "Content-Type": "application/json" },
2299
+ body: serialize({ args })
2300
+ });
2301
+ const text = await result.text();
2302
+ return deserialize(text);
2303
+ };
2304
+ };
2305
+ }
2306
+
1938
2307
  class XataError extends Error {
1939
2308
  constructor(message, status) {
1940
2309
  super(message);
@@ -1942,5 +2311,5 @@ class XataError extends Error {
1942
2311
  }
1943
2312
  }
1944
2313
 
1945
- export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, Repository, RestRepository, SchemaPlugin, SearchPlugin, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, buildClient, bulkInsertTableRecords, cancelWorkspaceMemberInvite, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, endsWith, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseURL, getGitBranchesMapping, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isIdentifiable, isNot, isXataRecord, le, lt, lte, notExists, operationsByTag, pattern, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberRole, upsertRecordWithID };
2314
+ export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, Serializer, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, buildClient, buildWorkerRunner, bulkInsertTableRecords, cancelWorkspaceMemberInvite, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, deserialize, endsWith, equals, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseMetadata, getDatabaseURL, getGitBranchesMapping, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, greaterEquals, greaterThan, greaterThanEquals, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isIdentifiable, isNot, isXataRecord, le, lessEquals, lessThan, lessThanEquals, lt, lte, notExists, operationsByTag, pattern, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, serialize, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID };
1946
2315
  //# sourceMappingURL=index.mjs.map