@xata.io/client 0.0.0-alpha.vfd6aaf3 → 0.0.0-alpha.vfdcf483

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,6 +37,9 @@ 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);
@@ -22,35 +49,83 @@ function toBase64(value) {
22
49
  }
23
50
  }
24
51
 
25
- function getEnvVariable(name) {
52
+ function getEnvironment() {
26
53
  try {
27
- if (isObject(process) && isString(process?.env?.[name])) {
28
- 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
+ };
29
62
  }
30
63
  } catch (err) {
31
64
  }
32
65
  try {
33
- if (isObject(Deno) && isString(Deno?.env?.get(name))) {
34
- 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
+ };
35
74
  }
36
75
  } catch (err) {
37
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
+ }
38
112
  }
39
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"] };
40
118
  try {
41
119
  if (typeof require === "function") {
42
- const req = require;
43
- return req("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
120
+ return require(nodeModule).execSync(fullCmd, execOptions).trim();
44
121
  }
122
+ const { execSync } = await import(nodeModule);
123
+ return execSync(fullCmd, execOptions).toString().trim();
45
124
  } catch (err) {
46
125
  }
47
126
  try {
48
127
  if (isObject(Deno)) {
49
- const process2 = Deno.run({
50
- cmd: ["git", "branch", "--show-current"],
51
- stdout: "piped",
52
- stderr: "piped"
53
- });
128
+ const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
54
129
  return new TextDecoder().decode(await process2.output()).trim();
55
130
  }
56
131
  } catch (err) {
@@ -59,7 +134,8 @@ async function getGitBranch() {
59
134
 
60
135
  function getAPIKey() {
61
136
  try {
62
- return getEnvVariable("XATA_API_KEY") ?? XATA_API_KEY;
137
+ const { apiKey } = getEnvironment();
138
+ return apiKey;
63
139
  } catch (err) {
64
140
  return void 0;
65
141
  }
@@ -69,12 +145,14 @@ function getFetchImplementation(userFetch) {
69
145
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
70
146
  const fetchImpl = userFetch ?? globalFetch;
71
147
  if (!fetchImpl) {
72
- 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
+ );
73
151
  }
74
152
  return fetchImpl;
75
153
  }
76
154
 
77
- const VERSION = "0.0.0-alpha.vfd6aaf3";
155
+ const VERSION = "0.0.0-alpha.vfdcf483";
78
156
 
79
157
  class ErrorWithCause extends Error {
80
158
  constructor(message, options) {
@@ -153,34 +231,62 @@ async function fetch$1({
153
231
  fetchImpl,
154
232
  apiKey,
155
233
  apiUrl,
156
- workspacesApiUrl
234
+ workspacesApiUrl,
235
+ trace
157
236
  }) {
158
- const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
159
- const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
160
- const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
161
- const response = await fetchImpl(url, {
162
- method: method.toUpperCase(),
163
- body: body ? JSON.stringify(body) : void 0,
164
- headers: {
165
- "Content-Type": "application/json",
166
- "User-Agent": `Xata client-ts/${VERSION}`,
167
- ...headers,
168
- ...hostHeader(fullUrl),
169
- Authorization: `Bearer ${apiKey}`
170
- }
171
- });
172
- if (response.status === 204) {
173
- return {};
174
- }
175
- const requestId = response.headers?.get("x-request-id") ?? void 0;
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) {
176
285
  try {
177
- const jsonResponse = await response.json();
178
- if (response.ok) {
179
- return jsonResponse;
180
- }
181
- throw new FetcherError(response.status, jsonResponse, requestId);
286
+ const { host, protocol } = new URL(url);
287
+ return { host, protocol };
182
288
  } catch (error) {
183
- throw new FetcherError(response.status, error, requestId);
289
+ return {};
184
290
  }
185
291
  }
186
292
 
@@ -239,6 +345,7 @@ const removeWorkspaceMember = (variables) => fetch$1({
239
345
  ...variables
240
346
  });
241
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 });
242
349
  const cancelWorkspaceMemberInvite = (variables) => fetch$1({
243
350
  url: "/workspaces/{workspaceId}/invites/{inviteId}",
244
351
  method: "delete",
@@ -274,6 +381,11 @@ const deleteDatabase = (variables) => fetch$1({
274
381
  method: "delete",
275
382
  ...variables
276
383
  });
384
+ const getDatabaseMetadata = (variables) => fetch$1({
385
+ url: "/dbs/{dbName}/metadata",
386
+ method: "get",
387
+ ...variables
388
+ });
277
389
  const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
278
390
  const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
279
391
  const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
@@ -287,11 +399,7 @@ const getBranchDetails = (variables) => fetch$1({
287
399
  method: "get",
288
400
  ...variables
289
401
  });
290
- const createBranch = (variables) => fetch$1({
291
- url: "/db/{dbBranchName}",
292
- method: "put",
293
- ...variables
294
- });
402
+ const createBranch = (variables) => fetch$1({ url: "/db/{dbBranchName}", method: "put", ...variables });
295
403
  const deleteBranch = (variables) => fetch$1({
296
404
  url: "/db/{dbBranchName}",
297
405
  method: "delete",
@@ -365,11 +473,7 @@ const updateColumn = (variables) => fetch$1({
365
473
  method: "patch",
366
474
  ...variables
367
475
  });
368
- const insertRecord = (variables) => fetch$1({
369
- url: "/db/{dbBranchName}/tables/{tableName}/data",
370
- method: "post",
371
- ...variables
372
- });
476
+ const insertRecord = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables });
373
477
  const insertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables });
374
478
  const updateRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables });
375
479
  const upsertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables });
@@ -411,6 +515,7 @@ const operationsByTag = {
411
515
  updateWorkspaceMemberRole,
412
516
  removeWorkspaceMember,
413
517
  inviteWorkspaceMember,
518
+ updateWorkspaceMemberInvite,
414
519
  cancelWorkspaceMemberInvite,
415
520
  resendWorkspaceMemberInvite,
416
521
  acceptWorkspaceMemberInvite
@@ -419,6 +524,7 @@ const operationsByTag = {
419
524
  getDatabaseList,
420
525
  createDatabase,
421
526
  deleteDatabase,
527
+ getDatabaseMetadata,
422
528
  getGitBranchesMapping,
423
529
  addGitBranchesEntry,
424
530
  removeGitBranchesEntry,
@@ -500,7 +606,7 @@ var __privateAdd$7 = (obj, member, value) => {
500
606
  throw TypeError("Cannot add the same private member more than once");
501
607
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
502
608
  };
503
- var __privateSet$6 = (obj, member, value, setter) => {
609
+ var __privateSet$7 = (obj, member, value, setter) => {
504
610
  __accessCheck$7(obj, member, "write to private field");
505
611
  setter ? setter.call(obj, value) : member.set(obj, value);
506
612
  return value;
@@ -511,15 +617,17 @@ class XataApiClient {
511
617
  __privateAdd$7(this, _extraProps, void 0);
512
618
  __privateAdd$7(this, _namespaces, {});
513
619
  const provider = options.host ?? "production";
514
- const apiKey = options?.apiKey ?? getAPIKey();
620
+ const apiKey = options.apiKey ?? getAPIKey();
621
+ const trace = options.trace ?? defaultTrace;
515
622
  if (!apiKey) {
516
623
  throw new Error("Could not resolve a valid apiKey");
517
624
  }
518
- __privateSet$6(this, _extraProps, {
625
+ __privateSet$7(this, _extraProps, {
519
626
  apiUrl: getHostUrl(provider, "main"),
520
627
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
521
628
  fetchImpl: getFetchImplementation(options.fetch),
522
- apiKey
629
+ apiKey,
630
+ trace
523
631
  });
524
632
  }
525
633
  get user() {
@@ -642,6 +750,13 @@ class WorkspaceApi {
642
750
  ...this.extraProps
643
751
  });
644
752
  }
753
+ updateWorkspaceMemberInvite(workspaceId, inviteId, role) {
754
+ return operationsByTag.workspaces.updateWorkspaceMemberInvite({
755
+ pathParams: { workspaceId, inviteId },
756
+ body: { role },
757
+ ...this.extraProps
758
+ });
759
+ }
645
760
  cancelWorkspaceMemberInvite(workspaceId, inviteId) {
646
761
  return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
647
762
  pathParams: { workspaceId, inviteId },
@@ -684,6 +799,12 @@ class DatabaseApi {
684
799
  ...this.extraProps
685
800
  });
686
801
  }
802
+ getDatabaseMetadata(workspace, dbName) {
803
+ return operationsByTag.database.getDatabaseMetadata({
804
+ pathParams: { workspace, dbName },
805
+ ...this.extraProps
806
+ });
807
+ }
687
808
  getGitBranchesMapping(workspace, dbName) {
688
809
  return operationsByTag.database.getGitBranchesMapping({
689
810
  pathParams: { workspace, dbName },
@@ -856,9 +977,10 @@ class RecordsApi {
856
977
  constructor(extraProps) {
857
978
  this.extraProps = extraProps;
858
979
  }
859
- insertRecord(workspace, database, branch, tableName, record) {
980
+ insertRecord(workspace, database, branch, tableName, record, options = {}) {
860
981
  return operationsByTag.records.insertRecord({
861
982
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
983
+ queryParams: options,
862
984
  body: record,
863
985
  ...this.extraProps
864
986
  });
@@ -887,21 +1009,24 @@ class RecordsApi {
887
1009
  ...this.extraProps
888
1010
  });
889
1011
  }
890
- deleteRecord(workspace, database, branch, tableName, recordId) {
1012
+ deleteRecord(workspace, database, branch, tableName, recordId, options = {}) {
891
1013
  return operationsByTag.records.deleteRecord({
892
1014
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1015
+ queryParams: options,
893
1016
  ...this.extraProps
894
1017
  });
895
1018
  }
896
1019
  getRecord(workspace, database, branch, tableName, recordId, options = {}) {
897
1020
  return operationsByTag.records.getRecord({
898
1021
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1022
+ queryParams: options,
899
1023
  ...this.extraProps
900
1024
  });
901
1025
  }
902
- bulkInsertTableRecords(workspace, database, branch, tableName, records) {
1026
+ bulkInsertTableRecords(workspace, database, branch, tableName, records, options = {}) {
903
1027
  return operationsByTag.records.bulkInsertTableRecords({
904
1028
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1029
+ queryParams: options,
905
1030
  body: { records },
906
1031
  ...this.extraProps
907
1032
  });
@@ -952,7 +1077,7 @@ var __privateAdd$6 = (obj, member, value) => {
952
1077
  throw TypeError("Cannot add the same private member more than once");
953
1078
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
954
1079
  };
955
- var __privateSet$5 = (obj, member, value, setter) => {
1080
+ var __privateSet$6 = (obj, member, value, setter) => {
956
1081
  __accessCheck$6(obj, member, "write to private field");
957
1082
  setter ? setter.call(obj, value) : member.set(obj, value);
958
1083
  return value;
@@ -961,7 +1086,7 @@ var _query, _page;
961
1086
  class Page {
962
1087
  constructor(query, meta, records = []) {
963
1088
  __privateAdd$6(this, _query, void 0);
964
- __privateSet$5(this, _query, query);
1089
+ __privateSet$6(this, _query, query);
965
1090
  this.meta = meta;
966
1091
  this.records = new RecordArray(this, records);
967
1092
  }
@@ -990,10 +1115,10 @@ function isCursorPaginationOptions(options) {
990
1115
  return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
991
1116
  }
992
1117
  const _RecordArray = class extends Array {
993
- constructor(page, overrideRecords) {
994
- super(..._RecordArray.parseConstructorParams(page, overrideRecords));
1118
+ constructor(...args) {
1119
+ super(..._RecordArray.parseConstructorParams(...args));
995
1120
  __privateAdd$6(this, _page, void 0);
996
- __privateSet$5(this, _page, page);
1121
+ __privateSet$6(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
997
1122
  }
998
1123
  static parseConstructorParams(...args) {
999
1124
  if (args.length === 1 && typeof args[0] === "number") {
@@ -1005,6 +1130,12 @@ const _RecordArray = class extends Array {
1005
1130
  }
1006
1131
  return new Array(...args);
1007
1132
  }
1133
+ toArray() {
1134
+ return new Array(...this);
1135
+ }
1136
+ map(callbackfn, thisArg) {
1137
+ return this.toArray().map(callbackfn, thisArg);
1138
+ }
1008
1139
  async nextPage(size, offset) {
1009
1140
  const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1010
1141
  return new _RecordArray(newPage);
@@ -1041,7 +1172,7 @@ var __privateAdd$5 = (obj, member, value) => {
1041
1172
  throw TypeError("Cannot add the same private member more than once");
1042
1173
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1043
1174
  };
1044
- var __privateSet$4 = (obj, member, value, setter) => {
1175
+ var __privateSet$5 = (obj, member, value, setter) => {
1045
1176
  __accessCheck$5(obj, member, "write to private field");
1046
1177
  setter ? setter.call(obj, value) : member.set(obj, value);
1047
1178
  return value;
@@ -1054,11 +1185,11 @@ const _Query = class {
1054
1185
  __privateAdd$5(this, _data, { filter: {} });
1055
1186
  this.meta = { page: { cursor: "start", more: true } };
1056
1187
  this.records = new RecordArray(this, []);
1057
- __privateSet$4(this, _table$1, table);
1188
+ __privateSet$5(this, _table$1, table);
1058
1189
  if (repository) {
1059
- __privateSet$4(this, _repository, repository);
1190
+ __privateSet$5(this, _repository, repository);
1060
1191
  } else {
1061
- __privateSet$4(this, _repository, this);
1192
+ __privateSet$5(this, _repository, this);
1062
1193
  }
1063
1194
  const parent = cleanParent(data, rawParent);
1064
1195
  __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
@@ -1113,13 +1244,18 @@ const _Query = class {
1113
1244
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1114
1245
  }
1115
1246
  }
1116
- sort(column, direction) {
1247
+ sort(column, direction = "asc") {
1117
1248
  const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
1118
1249
  const sort = [...originalSort, { column, direction }];
1119
1250
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
1120
1251
  }
1121
1252
  select(columns) {
1122
- 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
+ );
1123
1259
  }
1124
1260
  getPaginated(options = {}) {
1125
1261
  const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
@@ -1235,7 +1371,7 @@ var __privateAdd$4 = (obj, member, value) => {
1235
1371
  throw TypeError("Cannot add the same private member more than once");
1236
1372
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1237
1373
  };
1238
- var __privateSet$3 = (obj, member, value, setter) => {
1374
+ var __privateSet$4 = (obj, member, value, setter) => {
1239
1375
  __accessCheck$4(obj, member, "write to private field");
1240
1376
  setter ? setter.call(obj, value) : member.set(obj, value);
1241
1377
  return value;
@@ -1244,7 +1380,7 @@ var __privateMethod$2 = (obj, member, method) => {
1244
1380
  __accessCheck$4(obj, member, "access private method");
1245
1381
  return method;
1246
1382
  };
1247
- 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;
1383
+ 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;
1248
1384
  class Repository extends Query {
1249
1385
  }
1250
1386
  class RestRepository extends Query {
@@ -1256,210 +1392,211 @@ class RestRepository extends Query {
1256
1392
  __privateAdd$4(this, _updateRecordWithID);
1257
1393
  __privateAdd$4(this, _upsertRecordWithID);
1258
1394
  __privateAdd$4(this, _deleteRecord);
1259
- __privateAdd$4(this, _invalidateCache);
1260
- __privateAdd$4(this, _setCacheRecord);
1261
- __privateAdd$4(this, _getCacheRecord);
1262
1395
  __privateAdd$4(this, _setCacheQuery);
1263
1396
  __privateAdd$4(this, _getCacheQuery);
1264
- __privateAdd$4(this, _getSchema$1);
1397
+ __privateAdd$4(this, _getSchemaTables$1);
1265
1398
  __privateAdd$4(this, _table, void 0);
1266
1399
  __privateAdd$4(this, _getFetchProps, void 0);
1400
+ __privateAdd$4(this, _db, void 0);
1267
1401
  __privateAdd$4(this, _cache, void 0);
1268
- __privateAdd$4(this, _schema$1, void 0);
1269
- __privateSet$3(this, _table, options.table);
1270
- __privateSet$3(this, _getFetchProps, options.pluginOptions.getFetchProps);
1271
- this.db = options.db;
1272
- __privateSet$3(this, _cache, options.pluginOptions.cache);
1273
- }
1274
- async create(a, b) {
1275
- if (Array.isArray(a)) {
1276
- if (a.length === 0)
1277
- return [];
1278
- const [itemsWithoutIds, itemsWithIds, order] = a.reduce(([accWithoutIds, accWithIds, accOrder], item) => {
1279
- const condition = isString(item.id);
1280
- accOrder.push(condition);
1281
- if (condition) {
1282
- accWithIds.push(item);
1283
- } else {
1284
- accWithoutIds.push(item);
1402
+ __privateAdd$4(this, _schemaTables$2, void 0);
1403
+ __privateAdd$4(this, _trace, void 0);
1404
+ __privateSet$4(this, _table, options.table);
1405
+ __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1406
+ __privateSet$4(this, _db, options.db);
1407
+ __privateSet$4(this, _cache, options.pluginOptions.cache);
1408
+ __privateSet$4(this, _schemaTables$2, options.schemaTables);
1409
+ const trace = options.pluginOptions.trace ?? defaultTrace;
1410
+ __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
1411
+ return trace(name, fn, {
1412
+ ...options2,
1413
+ [TraceAttributes.TABLE]: __privateGet$4(this, _table),
1414
+ [TraceAttributes.VERSION]: VERSION
1415
+ });
1416
+ });
1417
+ }
1418
+ async create(a, b, c) {
1419
+ return __privateGet$4(this, _trace).call(this, "create", async () => {
1420
+ if (Array.isArray(a)) {
1421
+ if (a.length === 0)
1422
+ return [];
1423
+ const columns = isStringArray(b) ? b : void 0;
1424
+ return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
1425
+ }
1426
+ if (isString(a) && isObject(b)) {
1427
+ if (a === "")
1428
+ throw new Error("The id can't be empty");
1429
+ const columns = isStringArray(c) ? c : void 0;
1430
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns);
1431
+ }
1432
+ if (isObject(a) && isString(a.id)) {
1433
+ if (a.id === "")
1434
+ throw new Error("The id can't be empty");
1435
+ const columns = isStringArray(b) ? b : void 0;
1436
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1437
+ }
1438
+ if (isObject(a)) {
1439
+ const columns = isStringArray(b) ? b : void 0;
1440
+ return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
1441
+ }
1442
+ throw new Error("Invalid arguments for create method");
1443
+ });
1444
+ }
1445
+ async read(a, b) {
1446
+ return __privateGet$4(this, _trace).call(this, "read", async () => {
1447
+ const columns = isStringArray(b) ? b : ["*"];
1448
+ if (Array.isArray(a)) {
1449
+ if (a.length === 0)
1450
+ return [];
1451
+ const ids = a.map((item) => extractId(item));
1452
+ const finalObjects = await this.getAll({ filter: { id: { $any: compact(ids) } }, columns });
1453
+ const dictionary = finalObjects.reduce((acc, object) => {
1454
+ acc[object.id] = object;
1455
+ return acc;
1456
+ }, {});
1457
+ return ids.map((id2) => dictionary[id2 ?? ""] ?? null);
1458
+ }
1459
+ const id = extractId(a);
1460
+ if (id) {
1461
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1462
+ try {
1463
+ const response = await getRecord({
1464
+ pathParams: {
1465
+ workspace: "{workspaceId}",
1466
+ dbBranchName: "{dbBranch}",
1467
+ tableName: __privateGet$4(this, _table),
1468
+ recordId: id
1469
+ },
1470
+ queryParams: { columns },
1471
+ ...fetchProps
1472
+ });
1473
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1474
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1475
+ } catch (e) {
1476
+ if (isObject(e) && e.status === 404) {
1477
+ return null;
1478
+ }
1479
+ throw e;
1285
1480
  }
1286
- return [accWithoutIds, accWithIds, accOrder];
1287
- }, [[], [], []]);
1288
- const recordsWithoutId = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, itemsWithoutIds);
1289
- await Promise.all(recordsWithoutId.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1290
- if (itemsWithIds.length > 100) {
1291
- console.warn("Bulk create operation with id is not optimized in the Xata API yet, this request might be slow");
1292
1481
  }
1293
- const recordsWithId = await Promise.all(itemsWithIds.map((object) => this.create(object)));
1294
- return order.map((condition) => {
1295
- if (condition) {
1296
- return recordsWithId.shift();
1297
- } else {
1298
- return recordsWithoutId.shift();
1482
+ return null;
1483
+ });
1484
+ }
1485
+ async update(a, b, c) {
1486
+ return __privateGet$4(this, _trace).call(this, "update", async () => {
1487
+ if (Array.isArray(a)) {
1488
+ if (a.length === 0)
1489
+ return [];
1490
+ if (a.length > 100) {
1491
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1299
1492
  }
1300
- }).filter((record) => !!record);
1301
- }
1302
- if (isString(a) && isObject(b)) {
1303
- if (a === "")
1304
- throw new Error("The id can't be empty");
1305
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1306
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1307
- return record;
1308
- }
1309
- if (isObject(a) && isString(a.id)) {
1310
- if (a.id === "")
1311
- throw new Error("The id can't be empty");
1312
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1313
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1314
- return record;
1315
- }
1316
- if (isObject(a)) {
1317
- const record = await __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1318
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1319
- return record;
1320
- }
1321
- throw new Error("Invalid arguments for create method");
1322
- }
1323
- async read(a) {
1324
- if (Array.isArray(a)) {
1325
- if (a.length === 0)
1326
- return [];
1327
- const ids = a.map((item) => isString(item) ? item : item.id).filter((id2) => isString(id2));
1328
- return this.getAll({ filter: { id: { $any: ids } } });
1329
- }
1330
- const id = isString(a) ? a : a.id;
1331
- if (isString(id)) {
1332
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, id);
1333
- if (cacheRecord)
1334
- return cacheRecord;
1335
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1336
- try {
1337
- const response = await getRecord({
1338
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: id },
1339
- ...fetchProps
1340
- });
1341
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1342
- return initObject(this.db, schema, __privateGet$4(this, _table), response);
1343
- } catch (e) {
1344
- if (isObject(e) && e.status === 404) {
1345
- return null;
1493
+ const columns = isStringArray(b) ? b : ["*"];
1494
+ return Promise.all(a.map((object) => this.update(object, columns)));
1495
+ }
1496
+ if (isString(a) && isObject(b)) {
1497
+ const columns = isStringArray(c) ? c : void 0;
1498
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns);
1499
+ }
1500
+ if (isObject(a) && isString(a.id)) {
1501
+ const columns = isStringArray(b) ? b : void 0;
1502
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1503
+ }
1504
+ throw new Error("Invalid arguments for update method");
1505
+ });
1506
+ }
1507
+ async createOrUpdate(a, b, c) {
1508
+ return __privateGet$4(this, _trace).call(this, "createOrUpdate", async () => {
1509
+ if (Array.isArray(a)) {
1510
+ if (a.length === 0)
1511
+ return [];
1512
+ if (a.length > 100) {
1513
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1346
1514
  }
1347
- throw e;
1515
+ const columns = isStringArray(b) ? b : ["*"];
1516
+ return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
1348
1517
  }
1349
- }
1518
+ if (isString(a) && isObject(b)) {
1519
+ const columns = isStringArray(c) ? c : void 0;
1520
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns);
1521
+ }
1522
+ if (isObject(a) && isString(a.id)) {
1523
+ const columns = isStringArray(c) ? c : void 0;
1524
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1525
+ }
1526
+ throw new Error("Invalid arguments for createOrUpdate method");
1527
+ });
1350
1528
  }
1351
- async update(a, b) {
1352
- if (Array.isArray(a)) {
1353
- if (a.length === 0)
1354
- return [];
1355
- if (a.length > 100) {
1356
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1529
+ async delete(a, b) {
1530
+ return __privateGet$4(this, _trace).call(this, "delete", async () => {
1531
+ if (Array.isArray(a)) {
1532
+ if (a.length === 0)
1533
+ return [];
1534
+ if (a.length > 100) {
1535
+ console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1536
+ }
1537
+ return Promise.all(a.map((id) => this.delete(id, b)));
1357
1538
  }
1358
- return Promise.all(a.map((object) => this.update(object)));
1359
- }
1360
- if (isString(a) && isObject(b)) {
1361
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1362
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1363
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1364
- return record;
1365
- }
1366
- if (isObject(a) && isString(a.id)) {
1367
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1368
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1369
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1370
- return record;
1371
- }
1372
- throw new Error("Invalid arguments for update method");
1373
- }
1374
- async createOrUpdate(a, b) {
1375
- if (Array.isArray(a)) {
1376
- if (a.length === 0)
1377
- return [];
1378
- if (a.length > 100) {
1379
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1539
+ if (isString(a)) {
1540
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
1380
1541
  }
1381
- return Promise.all(a.map((object) => this.createOrUpdate(object)));
1382
- }
1383
- if (isString(a) && isObject(b)) {
1384
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1385
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1386
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1387
- return record;
1388
- }
1389
- if (isObject(a) && isString(a.id)) {
1390
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1391
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1392
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1393
- return record;
1394
- }
1395
- throw new Error("Invalid arguments for createOrUpdate method");
1396
- }
1397
- async delete(a) {
1398
- if (Array.isArray(a)) {
1399
- if (a.length === 0)
1400
- return;
1401
- if (a.length > 100) {
1402
- console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1542
+ if (isObject(a) && isString(a.id)) {
1543
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id, b);
1403
1544
  }
1404
- await Promise.all(a.map((id) => this.delete(id)));
1405
- return;
1406
- }
1407
- if (isString(a)) {
1408
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1409
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1410
- return;
1411
- }
1412
- if (isObject(a) && isString(a.id)) {
1413
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1414
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1415
- return;
1416
- }
1417
- throw new Error("Invalid arguments for delete method");
1545
+ throw new Error("Invalid arguments for delete method");
1546
+ });
1418
1547
  }
1419
1548
  async search(query, options = {}) {
1420
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1421
- const { records } = await searchTable({
1422
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1423
- body: {
1424
- query,
1425
- fuzziness: options.fuzziness,
1426
- highlight: options.highlight,
1427
- filter: options.filter
1428
- },
1429
- ...fetchProps
1549
+ return __privateGet$4(this, _trace).call(this, "search", async () => {
1550
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1551
+ const { records } = await searchTable({
1552
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1553
+ body: {
1554
+ query,
1555
+ fuzziness: options.fuzziness,
1556
+ prefix: options.prefix,
1557
+ highlight: options.highlight,
1558
+ filter: options.filter,
1559
+ boosters: options.boosters
1560
+ },
1561
+ ...fetchProps
1562
+ });
1563
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1564
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1430
1565
  });
1431
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1432
- return records.map((item) => initObject(this.db, schema, __privateGet$4(this, _table), item));
1433
1566
  }
1434
1567
  async query(query) {
1435
- const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1436
- if (cacheQuery)
1437
- return new Page(query, cacheQuery.meta, cacheQuery.records);
1438
- const data = query.getQueryOptions();
1439
- const body = {
1440
- filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1441
- sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1442
- page: data.pagination,
1443
- columns: data.columns
1444
- };
1445
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1446
- const { meta, records: objects } = await queryTable({
1447
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1448
- body,
1449
- ...fetchProps
1568
+ return __privateGet$4(this, _trace).call(this, "query", async () => {
1569
+ const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1570
+ if (cacheQuery)
1571
+ return new Page(query, cacheQuery.meta, cacheQuery.records);
1572
+ const data = query.getQueryOptions();
1573
+ const body = {
1574
+ filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1575
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1576
+ page: data.pagination,
1577
+ columns: data.columns
1578
+ };
1579
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1580
+ const { meta, records: objects } = await queryTable({
1581
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1582
+ body,
1583
+ ...fetchProps
1584
+ });
1585
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1586
+ const records = objects.map((record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record));
1587
+ await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1588
+ return new Page(query, meta, records);
1450
1589
  });
1451
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1452
- const records = objects.map((record) => initObject(this.db, schema, __privateGet$4(this, _table), record));
1453
- await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1454
- return new Page(query, meta, records);
1455
1590
  }
1456
1591
  }
1457
1592
  _table = new WeakMap();
1458
1593
  _getFetchProps = new WeakMap();
1594
+ _db = new WeakMap();
1459
1595
  _cache = new WeakMap();
1460
- _schema$1 = new WeakMap();
1596
+ _schemaTables$2 = new WeakMap();
1597
+ _trace = new WeakMap();
1461
1598
  _insertRecordWithoutId = new WeakSet();
1462
- insertRecordWithoutId_fn = async function(object) {
1599
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1463
1600
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1464
1601
  const record = transformObjectLinks(object);
1465
1602
  const response = await insertRecord({
@@ -1468,17 +1605,15 @@ insertRecordWithoutId_fn = async function(object) {
1468
1605
  dbBranchName: "{dbBranch}",
1469
1606
  tableName: __privateGet$4(this, _table)
1470
1607
  },
1608
+ queryParams: { columns },
1471
1609
  body: record,
1472
1610
  ...fetchProps
1473
1611
  });
1474
- const finalObject = await this.read(response.id);
1475
- if (!finalObject) {
1476
- throw new Error("The server failed to save the record");
1477
- }
1478
- return finalObject;
1612
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1613
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1479
1614
  };
1480
1615
  _insertRecordWithId = new WeakSet();
1481
- insertRecordWithId_fn = async function(recordId, object) {
1616
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
1482
1617
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1483
1618
  const record = transformObjectLinks(object);
1484
1619
  const response = await insertRecordWithID({
@@ -1489,88 +1624,78 @@ insertRecordWithId_fn = async function(recordId, object) {
1489
1624
  recordId
1490
1625
  },
1491
1626
  body: record,
1492
- queryParams: { createOnly: true },
1627
+ queryParams: { createOnly: true, columns },
1493
1628
  ...fetchProps
1494
1629
  });
1495
- const finalObject = await this.read(response.id);
1496
- if (!finalObject) {
1497
- throw new Error("The server failed to save the record");
1498
- }
1499
- return finalObject;
1630
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1631
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1500
1632
  };
1501
1633
  _bulkInsertTableRecords = new WeakSet();
1502
- bulkInsertTableRecords_fn = async function(objects) {
1634
+ bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
1503
1635
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1504
1636
  const records = objects.map((object) => transformObjectLinks(object));
1505
1637
  const response = await bulkInsertTableRecords({
1506
1638
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1639
+ queryParams: { columns },
1507
1640
  body: { records },
1508
1641
  ...fetchProps
1509
1642
  });
1510
- const finalObjects = await this.read(response.recordIDs);
1511
- if (finalObjects.length !== objects.length) {
1512
- throw new Error("The server failed to save some records");
1643
+ if (!isResponseWithRecords(response)) {
1644
+ throw new Error("Request included columns but server didn't include them");
1513
1645
  }
1514
- return finalObjects;
1646
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1647
+ return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1515
1648
  };
1516
1649
  _updateRecordWithID = new WeakSet();
1517
- updateRecordWithID_fn = async function(recordId, object) {
1650
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1518
1651
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1519
1652
  const record = transformObjectLinks(object);
1520
- const response = await updateRecordWithID({
1521
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1522
- body: record,
1523
- ...fetchProps
1524
- });
1525
- const item = await this.read(response.id);
1526
- if (!item)
1527
- throw new Error("The server failed to save the record");
1528
- return item;
1653
+ try {
1654
+ const response = await updateRecordWithID({
1655
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1656
+ queryParams: { columns },
1657
+ body: record,
1658
+ ...fetchProps
1659
+ });
1660
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1661
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1662
+ } catch (e) {
1663
+ if (isObject(e) && e.status === 404) {
1664
+ return null;
1665
+ }
1666
+ throw e;
1667
+ }
1529
1668
  };
1530
1669
  _upsertRecordWithID = new WeakSet();
1531
- upsertRecordWithID_fn = async function(recordId, object) {
1670
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1532
1671
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1533
1672
  const response = await upsertRecordWithID({
1534
1673
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1674
+ queryParams: { columns },
1535
1675
  body: object,
1536
1676
  ...fetchProps
1537
1677
  });
1538
- const item = await this.read(response.id);
1539
- if (!item)
1540
- throw new Error("The server failed to save the record");
1541
- return item;
1678
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1679
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1542
1680
  };
1543
1681
  _deleteRecord = new WeakSet();
1544
- deleteRecord_fn = async function(recordId) {
1682
+ deleteRecord_fn = async function(recordId, columns = ["*"]) {
1545
1683
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1546
- await deleteRecord({
1547
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1548
- ...fetchProps
1549
- });
1550
- };
1551
- _invalidateCache = new WeakSet();
1552
- invalidateCache_fn = async function(recordId) {
1553
- await __privateGet$4(this, _cache).delete(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1554
- const cacheItems = await __privateGet$4(this, _cache).getAll();
1555
- const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1556
- for (const [key, value] of queries) {
1557
- const ids = getIds(value);
1558
- if (ids.includes(recordId))
1559
- await __privateGet$4(this, _cache).delete(key);
1684
+ try {
1685
+ const response = await deleteRecord({
1686
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1687
+ queryParams: { columns },
1688
+ ...fetchProps
1689
+ });
1690
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1691
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1692
+ } catch (e) {
1693
+ if (isObject(e) && e.status === 404) {
1694
+ return null;
1695
+ }
1696
+ throw e;
1560
1697
  }
1561
1698
  };
1562
- _setCacheRecord = new WeakSet();
1563
- setCacheRecord_fn = async function(record) {
1564
- if (!__privateGet$4(this, _cache).cacheRecords)
1565
- return;
1566
- await __privateGet$4(this, _cache).set(`rec_${__privateGet$4(this, _table)}:${record.id}`, record);
1567
- };
1568
- _getCacheRecord = new WeakSet();
1569
- getCacheRecord_fn = async function(recordId) {
1570
- if (!__privateGet$4(this, _cache).cacheRecords)
1571
- return null;
1572
- return __privateGet$4(this, _cache).get(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1573
- };
1574
1699
  _setCacheQuery = new WeakSet();
1575
1700
  setCacheQuery_fn = async function(query, meta, records) {
1576
1701
  await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
@@ -1587,17 +1712,17 @@ getCacheQuery_fn = async function(query) {
1587
1712
  const hasExpired = result.date.getTime() + ttl < Date.now();
1588
1713
  return hasExpired ? null : result;
1589
1714
  };
1590
- _getSchema$1 = new WeakSet();
1591
- getSchema_fn$1 = async function() {
1592
- if (__privateGet$4(this, _schema$1))
1593
- return __privateGet$4(this, _schema$1);
1715
+ _getSchemaTables$1 = new WeakSet();
1716
+ getSchemaTables_fn$1 = async function() {
1717
+ if (__privateGet$4(this, _schemaTables$2))
1718
+ return __privateGet$4(this, _schemaTables$2);
1594
1719
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1595
1720
  const { schema } = await getBranchDetails({
1596
1721
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1597
1722
  ...fetchProps
1598
1723
  });
1599
- __privateSet$3(this, _schema$1, schema);
1600
- return schema;
1724
+ __privateSet$4(this, _schemaTables$2, schema.tables);
1725
+ return schema.tables;
1601
1726
  };
1602
1727
  const transformObjectLinks = (object) => {
1603
1728
  return Object.entries(object).reduce((acc, [key, value]) => {
@@ -1606,11 +1731,11 @@ const transformObjectLinks = (object) => {
1606
1731
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1607
1732
  }, {});
1608
1733
  };
1609
- const initObject = (db, schema, table, object) => {
1734
+ const initObject = (db, schemaTables, table, object) => {
1610
1735
  const result = {};
1611
1736
  const { xata, ...rest } = object ?? {};
1612
1737
  Object.assign(result, rest);
1613
- const { columns } = schema.tables.find(({ name }) => name === table) ?? {};
1738
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
1614
1739
  if (!columns)
1615
1740
  console.error(`Table ${table} not found in schema`);
1616
1741
  for (const column of columns ?? []) {
@@ -1630,17 +1755,17 @@ const initObject = (db, schema, table, object) => {
1630
1755
  if (!linkTable) {
1631
1756
  console.error(`Failed to parse link for field ${column.name}`);
1632
1757
  } else if (isObject(value)) {
1633
- result[column.name] = initObject(db, schema, linkTable, value);
1758
+ result[column.name] = initObject(db, schemaTables, linkTable, value);
1634
1759
  }
1635
1760
  break;
1636
1761
  }
1637
1762
  }
1638
1763
  }
1639
- result.read = function() {
1640
- return db[table].read(result["id"]);
1764
+ result.read = function(columns2) {
1765
+ return db[table].read(result["id"], columns2);
1641
1766
  };
1642
- result.update = function(data) {
1643
- return db[table].update(result["id"], data);
1767
+ result.update = function(data, columns2) {
1768
+ return db[table].update(result["id"], data, columns2);
1644
1769
  };
1645
1770
  result.delete = function() {
1646
1771
  return db[table].delete(result["id"]);
@@ -1654,14 +1779,15 @@ const initObject = (db, schema, table, object) => {
1654
1779
  Object.freeze(result);
1655
1780
  return result;
1656
1781
  };
1657
- function getIds(value) {
1658
- if (Array.isArray(value)) {
1659
- return value.map((item) => getIds(item)).flat();
1660
- }
1661
- if (!isObject(value))
1662
- return [];
1663
- const nestedIds = Object.values(value).map((item) => getIds(item)).flat();
1664
- return isString(value.id) ? [value.id, ...nestedIds] : nestedIds;
1782
+ function isResponseWithRecords(value) {
1783
+ return isObject(value) && Array.isArray(value.records);
1784
+ }
1785
+ function extractId(value) {
1786
+ if (isString(value))
1787
+ return value;
1788
+ if (isObject(value) && isString(value.id))
1789
+ return value.id;
1790
+ return void 0;
1665
1791
  }
1666
1792
 
1667
1793
  var __accessCheck$3 = (obj, member, msg) => {
@@ -1677,7 +1803,7 @@ var __privateAdd$3 = (obj, member, value) => {
1677
1803
  throw TypeError("Cannot add the same private member more than once");
1678
1804
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1679
1805
  };
1680
- var __privateSet$2 = (obj, member, value, setter) => {
1806
+ var __privateSet$3 = (obj, member, value, setter) => {
1681
1807
  __accessCheck$3(obj, member, "write to private field");
1682
1808
  setter ? setter.call(obj, value) : member.set(obj, value);
1683
1809
  return value;
@@ -1686,9 +1812,8 @@ var _map;
1686
1812
  class SimpleCache {
1687
1813
  constructor(options = {}) {
1688
1814
  __privateAdd$3(this, _map, void 0);
1689
- __privateSet$2(this, _map, /* @__PURE__ */ new Map());
1815
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1690
1816
  this.capacity = options.max ?? 500;
1691
- this.cacheRecords = options.cacheRecords ?? true;
1692
1817
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1693
1818
  }
1694
1819
  async getAll() {
@@ -1714,18 +1839,25 @@ class SimpleCache {
1714
1839
  }
1715
1840
  _map = new WeakMap();
1716
1841
 
1717
- const gt = (value) => ({ $gt: value });
1718
- const ge = (value) => ({ $ge: value });
1719
- const gte = (value) => ({ $ge: value });
1720
- const lt = (value) => ({ $lt: value });
1721
- const lte = (value) => ({ $le: value });
1722
- const le = (value) => ({ $le: value });
1842
+ const greaterThan = (value) => ({ $gt: value });
1843
+ const gt = greaterThan;
1844
+ const greaterThanEquals = (value) => ({ $ge: value });
1845
+ const greaterEquals = greaterThanEquals;
1846
+ const gte = greaterThanEquals;
1847
+ const ge = greaterThanEquals;
1848
+ const lessThan = (value) => ({ $lt: value });
1849
+ const lt = lessThan;
1850
+ const lessThanEquals = (value) => ({ $le: value });
1851
+ const lessEquals = lessThanEquals;
1852
+ const lte = lessThanEquals;
1853
+ const le = lessThanEquals;
1723
1854
  const exists = (column) => ({ $exists: column });
1724
1855
  const notExists = (column) => ({ $notExists: column });
1725
1856
  const startsWith = (value) => ({ $startsWith: value });
1726
1857
  const endsWith = (value) => ({ $endsWith: value });
1727
1858
  const pattern = (value) => ({ $pattern: value });
1728
1859
  const is = (value) => ({ $is: value });
1860
+ const equals = is;
1729
1861
  const isNot = (value) => ({ $isNot: value });
1730
1862
  const contains = (value) => ({ $contains: value });
1731
1863
  const includes = (value) => ({ $includes: value });
@@ -1746,31 +1878,42 @@ var __privateAdd$2 = (obj, member, value) => {
1746
1878
  throw TypeError("Cannot add the same private member more than once");
1747
1879
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1748
1880
  };
1749
- var _tables;
1881
+ var __privateSet$2 = (obj, member, value, setter) => {
1882
+ __accessCheck$2(obj, member, "write to private field");
1883
+ setter ? setter.call(obj, value) : member.set(obj, value);
1884
+ return value;
1885
+ };
1886
+ var _tables, _schemaTables$1;
1750
1887
  class SchemaPlugin extends XataPlugin {
1751
- constructor(tableNames) {
1888
+ constructor(schemaTables) {
1752
1889
  super();
1753
- this.tableNames = tableNames;
1754
1890
  __privateAdd$2(this, _tables, {});
1891
+ __privateAdd$2(this, _schemaTables$1, void 0);
1892
+ __privateSet$2(this, _schemaTables$1, schemaTables);
1755
1893
  }
1756
1894
  build(pluginOptions) {
1757
- const db = new Proxy({}, {
1758
- get: (_target, table) => {
1759
- if (!isString(table))
1760
- throw new Error("Invalid table name");
1761
- if (__privateGet$2(this, _tables)[table] === void 0) {
1762
- __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table });
1895
+ const db = new Proxy(
1896
+ {},
1897
+ {
1898
+ get: (_target, table) => {
1899
+ if (!isString(table))
1900
+ throw new Error("Invalid table name");
1901
+ if (__privateGet$2(this, _tables)[table] === void 0) {
1902
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1903
+ }
1904
+ return __privateGet$2(this, _tables)[table];
1763
1905
  }
1764
- return __privateGet$2(this, _tables)[table];
1765
1906
  }
1766
- });
1767
- for (const table of this.tableNames ?? []) {
1768
- db[table] = new RestRepository({ db, pluginOptions, table });
1907
+ );
1908
+ const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
1909
+ for (const table of tableNames) {
1910
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1769
1911
  }
1770
1912
  return db;
1771
1913
  }
1772
1914
  }
1773
1915
  _tables = new WeakMap();
1916
+ _schemaTables$1 = new WeakMap();
1774
1917
 
1775
1918
  var __accessCheck$1 = (obj, member, msg) => {
1776
1919
  if (!member.has(obj))
@@ -1794,82 +1937,77 @@ var __privateMethod$1 = (obj, member, method) => {
1794
1937
  __accessCheck$1(obj, member, "access private method");
1795
1938
  return method;
1796
1939
  };
1797
- var _schema, _search, search_fn, _getSchema, getSchema_fn;
1940
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1798
1941
  class SearchPlugin extends XataPlugin {
1799
- constructor(db) {
1942
+ constructor(db, schemaTables) {
1800
1943
  super();
1801
1944
  this.db = db;
1802
1945
  __privateAdd$1(this, _search);
1803
- __privateAdd$1(this, _getSchema);
1804
- __privateAdd$1(this, _schema, void 0);
1946
+ __privateAdd$1(this, _getSchemaTables);
1947
+ __privateAdd$1(this, _schemaTables, void 0);
1948
+ __privateSet$1(this, _schemaTables, schemaTables);
1805
1949
  }
1806
1950
  build({ getFetchProps }) {
1807
1951
  return {
1808
1952
  all: async (query, options = {}) => {
1809
1953
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1810
- const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
1954
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1811
1955
  return records.map((record) => {
1812
1956
  const { table = "orphan" } = record.xata;
1813
- return { table, record: initObject(this.db, schema, table, record) };
1957
+ return { table, record: initObject(this.db, schemaTables, table, record) };
1814
1958
  });
1815
1959
  },
1816
1960
  byTable: async (query, options = {}) => {
1817
1961
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1818
- const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
1962
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1819
1963
  return records.reduce((acc, record) => {
1820
1964
  const { table = "orphan" } = record.xata;
1821
1965
  const items = acc[table] ?? [];
1822
- const item = initObject(this.db, schema, table, record);
1966
+ const item = initObject(this.db, schemaTables, table, record);
1823
1967
  return { ...acc, [table]: [...items, item] };
1824
1968
  }, {});
1825
1969
  }
1826
1970
  };
1827
1971
  }
1828
1972
  }
1829
- _schema = new WeakMap();
1973
+ _schemaTables = new WeakMap();
1830
1974
  _search = new WeakSet();
1831
1975
  search_fn = async function(query, options, getFetchProps) {
1832
1976
  const fetchProps = await getFetchProps();
1833
- const { tables, fuzziness, highlight } = options ?? {};
1977
+ const { tables, fuzziness, highlight, prefix } = options ?? {};
1834
1978
  const { records } = await searchBranch({
1835
1979
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1836
- body: { tables, query, fuzziness, highlight },
1980
+ body: { tables, query, fuzziness, prefix, highlight },
1837
1981
  ...fetchProps
1838
1982
  });
1839
1983
  return records;
1840
1984
  };
1841
- _getSchema = new WeakSet();
1842
- getSchema_fn = async function(getFetchProps) {
1843
- if (__privateGet$1(this, _schema))
1844
- return __privateGet$1(this, _schema);
1985
+ _getSchemaTables = new WeakSet();
1986
+ getSchemaTables_fn = async function(getFetchProps) {
1987
+ if (__privateGet$1(this, _schemaTables))
1988
+ return __privateGet$1(this, _schemaTables);
1845
1989
  const fetchProps = await getFetchProps();
1846
1990
  const { schema } = await getBranchDetails({
1847
1991
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1848
1992
  ...fetchProps
1849
1993
  });
1850
- __privateSet$1(this, _schema, schema);
1851
- return schema;
1994
+ __privateSet$1(this, _schemaTables, schema.tables);
1995
+ return schema.tables;
1852
1996
  };
1853
1997
 
1854
1998
  const isBranchStrategyBuilder = (strategy) => {
1855
1999
  return typeof strategy === "function";
1856
2000
  };
1857
2001
 
1858
- const envBranchNames = [
1859
- "XATA_BRANCH",
1860
- "VERCEL_GIT_COMMIT_REF",
1861
- "CF_PAGES_BRANCH",
1862
- "BRANCH"
1863
- ];
1864
2002
  async function getCurrentBranchName(options) {
1865
- const env = getBranchByEnvVariable();
1866
- if (env) {
1867
- const details = await getDatabaseBranch(env, options);
2003
+ const { branch, envBranch } = getEnvironment();
2004
+ if (branch) {
2005
+ const details = await getDatabaseBranch(branch, options);
1868
2006
  if (details)
1869
- return env;
1870
- console.warn(`Branch ${env} not found in Xata. Ignoring...`);
2007
+ return branch;
2008
+ console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
1871
2009
  }
1872
- const gitBranch = await getGitBranch();
2010
+ const gitBranch = envBranch || await getGitBranch();
1873
2011
  return resolveXataBranch(gitBranch, options);
1874
2012
  }
1875
2013
  async function getCurrentBranchDetails(options) {
@@ -1880,18 +2018,24 @@ async function resolveXataBranch(gitBranch, options) {
1880
2018
  const databaseURL = options?.databaseURL || getDatabaseURL();
1881
2019
  const apiKey = options?.apiKey || getAPIKey();
1882
2020
  if (!databaseURL)
1883
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
2021
+ throw new Error(
2022
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2023
+ );
1884
2024
  if (!apiKey)
1885
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
2025
+ throw new Error(
2026
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2027
+ );
1886
2028
  const [protocol, , host, , dbName] = databaseURL.split("/");
1887
2029
  const [workspace] = host.split(".");
2030
+ const { fallbackBranch } = getEnvironment();
1888
2031
  const { branch } = await resolveBranch({
1889
2032
  apiKey,
1890
2033
  apiUrl: databaseURL,
1891
2034
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1892
2035
  workspacesApiUrl: `${protocol}//${host}`,
1893
2036
  pathParams: { dbName, workspace },
1894
- queryParams: { gitBranch, fallbackBranch: getEnvVariable("XATA_FALLBACK_BRANCH") }
2037
+ queryParams: { gitBranch, fallbackBranch },
2038
+ trace: defaultTrace
1895
2039
  });
1896
2040
  return branch;
1897
2041
  }
@@ -1899,9 +2043,13 @@ async function getDatabaseBranch(branch, options) {
1899
2043
  const databaseURL = options?.databaseURL || getDatabaseURL();
1900
2044
  const apiKey = options?.apiKey || getAPIKey();
1901
2045
  if (!databaseURL)
1902
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
2046
+ throw new Error(
2047
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2048
+ );
1903
2049
  if (!apiKey)
1904
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
2050
+ throw new Error(
2051
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2052
+ );
1905
2053
  const [protocol, , host, , database] = databaseURL.split("/");
1906
2054
  const [workspace] = host.split(".");
1907
2055
  const dbBranchName = `${database}:${branch}`;
@@ -1911,7 +2059,8 @@ async function getDatabaseBranch(branch, options) {
1911
2059
  apiUrl: databaseURL,
1912
2060
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1913
2061
  workspacesApiUrl: `${protocol}//${host}`,
1914
- pathParams: { dbBranchName, workspace }
2062
+ pathParams: { dbBranchName, workspace },
2063
+ trace: defaultTrace
1915
2064
  });
1916
2065
  } catch (err) {
1917
2066
  if (isObject(err) && err.status === 404)
@@ -1919,21 +2068,10 @@ async function getDatabaseBranch(branch, options) {
1919
2068
  throw err;
1920
2069
  }
1921
2070
  }
1922
- function getBranchByEnvVariable() {
1923
- for (const name of envBranchNames) {
1924
- const value = getEnvVariable(name);
1925
- if (value) {
1926
- return value;
1927
- }
1928
- }
1929
- try {
1930
- return XATA_BRANCH;
1931
- } catch (err) {
1932
- }
1933
- }
1934
2071
  function getDatabaseURL() {
1935
2072
  try {
1936
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
2073
+ const { databaseURL } = getEnvironment();
2074
+ return databaseURL;
1937
2075
  } catch (err) {
1938
2076
  return void 0;
1939
2077
  }
@@ -1962,20 +2100,23 @@ var __privateMethod = (obj, member, method) => {
1962
2100
  return method;
1963
2101
  };
1964
2102
  const buildClient = (plugins) => {
1965
- var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
2103
+ var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1966
2104
  return _a = class {
1967
- constructor(options = {}, tables) {
2105
+ constructor(options = {}, schemaTables) {
1968
2106
  __privateAdd(this, _parseOptions);
1969
2107
  __privateAdd(this, _getFetchProps);
1970
2108
  __privateAdd(this, _evaluateBranch);
1971
2109
  __privateAdd(this, _branch, void 0);
2110
+ __privateAdd(this, _options, void 0);
1972
2111
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
2112
+ __privateSet(this, _options, safeOptions);
1973
2113
  const pluginOptions = {
1974
2114
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1975
- cache: safeOptions.cache
2115
+ cache: safeOptions.cache,
2116
+ trace: safeOptions.trace
1976
2117
  };
1977
- const db = new SchemaPlugin(tables).build(pluginOptions);
1978
- const search = new SearchPlugin(db).build(pluginOptions);
2118
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2119
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1979
2120
  this.db = db;
1980
2121
  this.search = search;
1981
2122
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
@@ -1991,22 +2132,26 @@ const buildClient = (plugins) => {
1991
2132
  }
1992
2133
  }
1993
2134
  }
1994
- }, _branch = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
2135
+ async getConfig() {
2136
+ const databaseURL = __privateGet(this, _options).databaseURL;
2137
+ const branch = await __privateGet(this, _options).branch();
2138
+ return { databaseURL, branch };
2139
+ }
2140
+ }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
1995
2141
  const fetch = getFetchImplementation(options?.fetch);
1996
2142
  const databaseURL = options?.databaseURL || getDatabaseURL();
1997
2143
  const apiKey = options?.apiKey || getAPIKey();
1998
- const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
2144
+ const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
2145
+ const trace = options?.trace ?? defaultTrace;
1999
2146
  const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
2000
- if (!databaseURL || !apiKey) {
2001
- throw new Error("Options databaseURL and apiKey are required");
2147
+ if (!apiKey) {
2148
+ throw new Error("Option apiKey is required");
2002
2149
  }
2003
- return { fetch, databaseURL, apiKey, branch, cache };
2004
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
2005
- fetch,
2006
- apiKey,
2007
- databaseURL,
2008
- branch
2009
- }) {
2150
+ if (!databaseURL) {
2151
+ throw new Error("Option databaseURL is required");
2152
+ }
2153
+ return { fetch, databaseURL, apiKey, branch, cache, trace };
2154
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace }) {
2010
2155
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
2011
2156
  if (!branchValue)
2012
2157
  throw new Error("Unable to resolve branch value");
@@ -2018,7 +2163,8 @@ const buildClient = (plugins) => {
2018
2163
  const hasBranch = params.dbBranchName ?? params.branch;
2019
2164
  const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branchValue}` : "");
2020
2165
  return databaseURL + newPath;
2021
- }
2166
+ },
2167
+ trace
2022
2168
  };
2023
2169
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
2024
2170
  if (__privateGet(this, _branch))
@@ -2041,6 +2187,88 @@ const buildClient = (plugins) => {
2041
2187
  class BaseClient extends buildClient() {
2042
2188
  }
2043
2189
 
2190
+ const META = "__";
2191
+ const VALUE = "___";
2192
+ class Serializer {
2193
+ constructor() {
2194
+ this.classes = {};
2195
+ }
2196
+ add(clazz) {
2197
+ this.classes[clazz.name] = clazz;
2198
+ }
2199
+ toJSON(data) {
2200
+ function visit(obj) {
2201
+ if (Array.isArray(obj))
2202
+ return obj.map(visit);
2203
+ const type = typeof obj;
2204
+ if (type === "undefined")
2205
+ return { [META]: "undefined" };
2206
+ if (type === "bigint")
2207
+ return { [META]: "bigint", [VALUE]: obj.toString() };
2208
+ if (obj === null || type !== "object")
2209
+ return obj;
2210
+ const constructor = obj.constructor;
2211
+ const o = { [META]: constructor.name };
2212
+ for (const [key, value] of Object.entries(obj)) {
2213
+ o[key] = visit(value);
2214
+ }
2215
+ if (constructor === Date)
2216
+ o[VALUE] = obj.toISOString();
2217
+ if (constructor === Map)
2218
+ o[VALUE] = Object.fromEntries(obj);
2219
+ if (constructor === Set)
2220
+ o[VALUE] = [...obj];
2221
+ return o;
2222
+ }
2223
+ return JSON.stringify(visit(data));
2224
+ }
2225
+ fromJSON(json) {
2226
+ return JSON.parse(json, (key, value) => {
2227
+ if (value && typeof value === "object" && !Array.isArray(value)) {
2228
+ const { [META]: clazz, [VALUE]: val, ...rest } = value;
2229
+ const constructor = this.classes[clazz];
2230
+ if (constructor) {
2231
+ return Object.assign(Object.create(constructor.prototype), rest);
2232
+ }
2233
+ if (clazz === "Date")
2234
+ return new Date(val);
2235
+ if (clazz === "Set")
2236
+ return new Set(val);
2237
+ if (clazz === "Map")
2238
+ return new Map(Object.entries(val));
2239
+ if (clazz === "bigint")
2240
+ return BigInt(val);
2241
+ if (clazz === "undefined")
2242
+ return void 0;
2243
+ return rest;
2244
+ }
2245
+ return value;
2246
+ });
2247
+ }
2248
+ }
2249
+ const defaultSerializer = new Serializer();
2250
+ const serialize = (data) => {
2251
+ return defaultSerializer.toJSON(data);
2252
+ };
2253
+ const deserialize = (json) => {
2254
+ return defaultSerializer.fromJSON(json);
2255
+ };
2256
+
2257
+ function buildWorkerRunner(config) {
2258
+ return function xataWorker(name, _worker) {
2259
+ return async (...args) => {
2260
+ const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
2261
+ const result = await fetch(url, {
2262
+ method: "POST",
2263
+ headers: { "Content-Type": "application/json" },
2264
+ body: serialize({ args })
2265
+ });
2266
+ const text = await result.text();
2267
+ return deserialize(text);
2268
+ };
2269
+ };
2270
+ }
2271
+
2044
2272
  class XataError extends Error {
2045
2273
  constructor(message, status) {
2046
2274
  super(message);
@@ -2048,5 +2276,5 @@ class XataError extends Error {
2048
2276
  }
2049
2277
  }
2050
2278
 
2051
- export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, 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 };
2279
+ 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 };
2052
2280
  //# sourceMappingURL=index.mjs.map