@xata.io/client 0.8.3 → 0.8.4

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
@@ -12,15 +12,14 @@ function isString(value) {
12
12
  }
13
13
 
14
14
  function getEnvVariable(name) {
15
- var _a, _b;
16
15
  try {
17
- if (isObject(process) && isString((_a = process == null ? void 0 : process.env) == null ? void 0 : _a[name])) {
16
+ if (isObject(process) && isString(process?.env?.[name])) {
18
17
  return process.env[name];
19
18
  }
20
19
  } catch (err) {
21
20
  }
22
21
  try {
23
- if (isObject(Deno) && isString((_b = Deno == null ? void 0 : Deno.env) == null ? void 0 : _b.get(name))) {
22
+ if (isObject(Deno) && isString(Deno?.env?.get(name))) {
24
23
  return Deno.env.get(name);
25
24
  }
26
25
  } catch (err) {
@@ -44,99 +43,51 @@ async function getGitBranch() {
44
43
  }
45
44
  }
46
45
 
46
+ function getAPIKey() {
47
+ try {
48
+ return getEnvVariable("XATA_API_KEY") ?? XATA_API_KEY;
49
+ } catch (err) {
50
+ return void 0;
51
+ }
52
+ }
53
+
47
54
  function getFetchImplementation(userFetch) {
48
55
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
49
- const fetchImpl = userFetch != null ? userFetch : globalFetch;
56
+ const fetchImpl = userFetch ?? globalFetch;
50
57
  if (!fetchImpl) {
51
58
  throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
52
59
  }
53
60
  return fetchImpl;
54
61
  }
55
62
 
56
- const envBranchNames = [
57
- "XATA_BRANCH",
58
- "VERCEL_GIT_COMMIT_REF",
59
- "CF_PAGES_BRANCH",
60
- "BRANCH"
61
- ];
62
- const defaultBranch = "main";
63
- async function getCurrentBranchName(options) {
64
- const env = await getBranchByEnvVariable();
65
- if (env)
66
- return env;
67
- const branch = await getGitBranch();
68
- if (!branch)
69
- return defaultBranch;
70
- const details = await getDatabaseBranch(branch, options);
71
- if (details)
72
- return branch;
73
- return defaultBranch;
74
- }
75
- async function getCurrentBranchDetails(options) {
76
- const env = await getBranchByEnvVariable();
77
- if (env)
78
- return getDatabaseBranch(env, options);
79
- const branch = await getGitBranch();
80
- if (!branch)
81
- return getDatabaseBranch(defaultBranch, options);
82
- const details = await getDatabaseBranch(branch, options);
83
- if (details)
84
- return details;
85
- return getDatabaseBranch(defaultBranch, options);
86
- }
87
- async function getDatabaseBranch(branch, options) {
88
- const databaseURL = (options == null ? void 0 : options.databaseURL) || getDatabaseURL();
89
- const apiKey = (options == null ? void 0 : options.apiKey) || getAPIKey();
90
- if (!databaseURL)
91
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
92
- if (!apiKey)
93
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
94
- const [protocol, , host, , database] = databaseURL.split("/");
95
- const [workspace] = host.split(".");
96
- const dbBranchName = `${database}:${branch}`;
97
- try {
98
- return await getBranchDetails({
99
- apiKey,
100
- apiUrl: databaseURL,
101
- fetchImpl: getFetchImplementation(options == null ? void 0 : options.fetchImpl),
102
- workspacesApiUrl: `${protocol}//${host}`,
103
- pathParams: {
104
- dbBranchName,
105
- workspace
106
- }
107
- });
108
- } catch (err) {
109
- if (isObject(err) && err.status === 404)
110
- return null;
111
- throw err;
112
- }
113
- }
114
- function getBranchByEnvVariable() {
115
- for (const name of envBranchNames) {
116
- const value = getEnvVariable(name);
117
- if (value) {
118
- return value;
63
+ class FetcherError extends Error {
64
+ constructor(status, data) {
65
+ super(getMessage(data));
66
+ this.status = status;
67
+ this.errors = isBulkError(data) ? data.errors : void 0;
68
+ if (data instanceof Error) {
69
+ this.stack = data.stack;
70
+ this.cause = data.cause;
119
71
  }
120
72
  }
121
- try {
122
- return XATA_BRANCH;
123
- } catch (err) {
124
- }
125
73
  }
126
- function getDatabaseURL() {
127
- var _a;
128
- try {
129
- return (_a = getEnvVariable("XATA_DATABASE_URL")) != null ? _a : XATA_DATABASE_URL;
130
- } catch (err) {
131
- return void 0;
132
- }
74
+ function isBulkError(error) {
75
+ return isObject(error) && Array.isArray(error.errors);
133
76
  }
134
- function getAPIKey() {
135
- var _a;
136
- try {
137
- return (_a = getEnvVariable("XATA_API_KEY")) != null ? _a : XATA_API_KEY;
138
- } catch (err) {
139
- return void 0;
77
+ function isErrorWithMessage(error) {
78
+ return isObject(error) && isString(error.message);
79
+ }
80
+ function getMessage(data) {
81
+ if (data instanceof Error) {
82
+ return data.message;
83
+ } else if (isString(data)) {
84
+ return data;
85
+ } else if (isErrorWithMessage(data)) {
86
+ return data.message;
87
+ } else if (isBulkError(data)) {
88
+ return "Bulk operation failed";
89
+ } else {
90
+ return "Unexpected error";
140
91
  }
141
92
  }
142
93
 
@@ -151,16 +102,15 @@ function buildBaseUrl({
151
102
  apiUrl,
152
103
  pathParams
153
104
  }) {
154
- if (!(pathParams == null ? void 0 : pathParams.workspace))
105
+ if (!pathParams?.workspace)
155
106
  return `${apiUrl}${path}`;
156
107
  const url = typeof workspacesApiUrl === "string" ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
157
108
  return url.replace("{workspaceId}", pathParams.workspace);
158
109
  }
159
110
  function hostHeader(url) {
160
- var _a;
161
111
  const pattern = /.*:\/\/(?<host>[^/]+).*/;
162
- const { groups } = (_a = pattern.exec(url)) != null ? _a : {};
163
- return (groups == null ? void 0 : groups.host) ? { Host: groups.host } : {};
112
+ const { groups } = pattern.exec(url) ?? {};
113
+ return groups?.host ? { Host: groups.host } : {};
164
114
  }
165
115
  async function fetch$1({
166
116
  url: path,
@@ -195,33 +145,20 @@ async function fetch$1({
195
145
  if (response.ok) {
196
146
  return jsonResponse;
197
147
  }
198
- const { message = "Unknown error", errors } = jsonResponse;
199
- throw new FetcherError({ message, status: response.status, errors });
148
+ throw new FetcherError(response.status, jsonResponse);
200
149
  } catch (error) {
201
- const message = hasMessage(error) ? error.message : "Unknown network error";
202
- const parent = error instanceof Error ? error : void 0;
203
- throw new FetcherError({ message, status: response.status }, parent);
204
- }
205
- }
206
- const hasMessage = (error) => {
207
- return isObject(error) && isString(error.message);
208
- };
209
- class FetcherError extends Error {
210
- constructor(data, parent) {
211
- super(data.message);
212
- this.status = data.status;
213
- this.errors = data.errors;
214
- if (parent) {
215
- this.stack = parent.stack;
216
- this.cause = parent.cause;
217
- }
150
+ throw new FetcherError(response.status, error);
218
151
  }
219
152
  }
220
153
 
221
154
  const getUser = (variables) => fetch$1({ url: "/user", method: "get", ...variables });
222
155
  const updateUser = (variables) => fetch$1({ url: "/user", method: "put", ...variables });
223
156
  const deleteUser = (variables) => fetch$1({ url: "/user", method: "delete", ...variables });
224
- const getUserAPIKeys = (variables) => fetch$1({ url: "/user/keys", method: "get", ...variables });
157
+ const getUserAPIKeys = (variables) => fetch$1({
158
+ url: "/user/keys",
159
+ method: "get",
160
+ ...variables
161
+ });
225
162
  const createUserAPIKey = (variables) => fetch$1({
226
163
  url: "/user/keys/{keyName}",
227
164
  method: "post",
@@ -232,8 +169,16 @@ const deleteUserAPIKey = (variables) => fetch$1({
232
169
  method: "delete",
233
170
  ...variables
234
171
  });
235
- const createWorkspace = (variables) => fetch$1({ url: "/workspaces", method: "post", ...variables });
236
- const getWorkspacesList = (variables) => fetch$1({ url: "/workspaces", method: "get", ...variables });
172
+ const createWorkspace = (variables) => fetch$1({
173
+ url: "/workspaces",
174
+ method: "post",
175
+ ...variables
176
+ });
177
+ const getWorkspacesList = (variables) => fetch$1({
178
+ url: "/workspaces",
179
+ method: "get",
180
+ ...variables
181
+ });
237
182
  const getWorkspace = (variables) => fetch$1({
238
183
  url: "/workspaces/{workspaceId}",
239
184
  method: "get",
@@ -254,21 +199,13 @@ const getWorkspaceMembersList = (variables) => fetch$1({
254
199
  method: "get",
255
200
  ...variables
256
201
  });
257
- const updateWorkspaceMemberRole = (variables) => fetch$1({
258
- url: "/workspaces/{workspaceId}/members/{userId}",
259
- method: "put",
260
- ...variables
261
- });
202
+ const updateWorkspaceMemberRole = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/members/{userId}", method: "put", ...variables });
262
203
  const removeWorkspaceMember = (variables) => fetch$1({
263
204
  url: "/workspaces/{workspaceId}/members/{userId}",
264
205
  method: "delete",
265
206
  ...variables
266
207
  });
267
- const inviteWorkspaceMember = (variables) => fetch$1({
268
- url: "/workspaces/{workspaceId}/invites",
269
- method: "post",
270
- ...variables
271
- });
208
+ const inviteWorkspaceMember = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables });
272
209
  const cancelWorkspaceMemberInvite = (variables) => fetch$1({
273
210
  url: "/workspaces/{workspaceId}/invites/{inviteId}",
274
211
  method: "delete",
@@ -330,16 +267,8 @@ const getBranchMetadata = (variables) => fetch$1({
330
267
  ...variables
331
268
  });
332
269
  const getBranchMigrationHistory = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables });
333
- const executeBranchMigrationPlan = (variables) => fetch$1({
334
- url: "/db/{dbBranchName}/migrations/execute",
335
- method: "post",
336
- ...variables
337
- });
338
- const getBranchMigrationPlan = (variables) => fetch$1({
339
- url: "/db/{dbBranchName}/migrations/plan",
340
- method: "post",
341
- ...variables
342
- });
270
+ const executeBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables });
271
+ const getBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables });
343
272
  const getBranchStats = (variables) => fetch$1({
344
273
  url: "/db/{dbBranchName}/stats",
345
274
  method: "get",
@@ -413,11 +342,7 @@ const getRecord = (variables) => fetch$1({
413
342
  method: "get",
414
343
  ...variables
415
344
  });
416
- const bulkInsertTableRecords = (variables) => fetch$1({
417
- url: "/db/{dbBranchName}/tables/{tableName}/bulk",
418
- method: "post",
419
- ...variables
420
- });
345
+ const bulkInsertTableRecords = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/bulk", method: "post", ...variables });
421
346
  const queryTable = (variables) => fetch$1({
422
347
  url: "/db/{dbBranchName}/tables/{tableName}/query",
423
348
  method: "post",
@@ -527,12 +452,11 @@ var __privateSet$4 = (obj, member, value, setter) => {
527
452
  };
528
453
  var _extraProps, _namespaces;
529
454
  class XataApiClient {
530
- constructor(options) {
455
+ constructor(options = {}) {
531
456
  __privateAdd$6(this, _extraProps, void 0);
532
457
  __privateAdd$6(this, _namespaces, {});
533
- var _a, _b;
534
- const provider = (_a = options.host) != null ? _a : "production";
535
- const apiKey = (_b = options == null ? void 0 : options.apiKey) != null ? _b : getAPIKey();
458
+ const provider = options.host ?? "production";
459
+ const apiKey = options?.apiKey ?? getAPIKey();
536
460
  if (!apiKey) {
537
461
  throw new Error("Could not resolve a valid apiKey");
538
462
  }
@@ -1000,21 +924,20 @@ const _Query = class {
1000
924
  __privateAdd$4(this, _data, { filter: {} });
1001
925
  this.meta = { page: { cursor: "start", more: true } };
1002
926
  this.records = [];
1003
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r;
1004
927
  __privateSet$2(this, _table$1, table);
1005
928
  if (repository) {
1006
929
  __privateSet$2(this, _repository, repository);
1007
930
  } else {
1008
931
  __privateSet$2(this, _repository, this);
1009
932
  }
1010
- __privateGet$3(this, _data).filter = (_b = (_a = data.filter) != null ? _a : parent == null ? void 0 : parent.filter) != null ? _b : {};
1011
- __privateGet$3(this, _data).filter.$any = (_e = (_c = data.filter) == null ? void 0 : _c.$any) != null ? _e : (_d = parent == null ? void 0 : parent.filter) == null ? void 0 : _d.$any;
1012
- __privateGet$3(this, _data).filter.$all = (_h = (_f = data.filter) == null ? void 0 : _f.$all) != null ? _h : (_g = parent == null ? void 0 : parent.filter) == null ? void 0 : _g.$all;
1013
- __privateGet$3(this, _data).filter.$not = (_k = (_i = data.filter) == null ? void 0 : _i.$not) != null ? _k : (_j = parent == null ? void 0 : parent.filter) == null ? void 0 : _j.$not;
1014
- __privateGet$3(this, _data).filter.$none = (_n = (_l = data.filter) == null ? void 0 : _l.$none) != null ? _n : (_m = parent == null ? void 0 : parent.filter) == null ? void 0 : _m.$none;
1015
- __privateGet$3(this, _data).sort = (_o = data.sort) != null ? _o : parent == null ? void 0 : parent.sort;
1016
- __privateGet$3(this, _data).columns = (_q = (_p = data.columns) != null ? _p : parent == null ? void 0 : parent.columns) != null ? _q : ["*"];
1017
- __privateGet$3(this, _data).page = (_r = data.page) != null ? _r : parent == null ? void 0 : parent.page;
933
+ __privateGet$3(this, _data).filter = data.filter ?? parent?.filter ?? {};
934
+ __privateGet$3(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
935
+ __privateGet$3(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
936
+ __privateGet$3(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
937
+ __privateGet$3(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
938
+ __privateGet$3(this, _data).sort = data.sort ?? parent?.sort;
939
+ __privateGet$3(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
940
+ __privateGet$3(this, _data).page = data.page ?? parent?.page;
1018
941
  this.any = this.any.bind(this);
1019
942
  this.all = this.all.bind(this);
1020
943
  this.not = this.not.bind(this);
@@ -1028,47 +951,33 @@ const _Query = class {
1028
951
  return __privateGet$3(this, _data);
1029
952
  }
1030
953
  any(...queries) {
1031
- const $any = queries.map((query) => {
1032
- var _a;
1033
- return (_a = query.getQueryOptions().filter) != null ? _a : {};
1034
- });
954
+ const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
1035
955
  return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $any } }, __privateGet$3(this, _data));
1036
956
  }
1037
957
  all(...queries) {
1038
- const $all = queries.map((query) => {
1039
- var _a;
1040
- return (_a = query.getQueryOptions().filter) != null ? _a : {};
1041
- });
958
+ const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
1042
959
  return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $all } }, __privateGet$3(this, _data));
1043
960
  }
1044
961
  not(...queries) {
1045
- const $not = queries.map((query) => {
1046
- var _a;
1047
- return (_a = query.getQueryOptions().filter) != null ? _a : {};
1048
- });
962
+ const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
1049
963
  return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $not } }, __privateGet$3(this, _data));
1050
964
  }
1051
965
  none(...queries) {
1052
- const $none = queries.map((query) => {
1053
- var _a;
1054
- return (_a = query.getQueryOptions().filter) != null ? _a : {};
1055
- });
966
+ const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
1056
967
  return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $none } }, __privateGet$3(this, _data));
1057
968
  }
1058
969
  filter(a, b) {
1059
- var _a, _b;
1060
970
  if (arguments.length === 1) {
1061
971
  const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
1062
- const $all = compact([(_a = __privateGet$3(this, _data).filter) == null ? void 0 : _a.$all].flat().concat(constraints));
972
+ const $all = compact([__privateGet$3(this, _data).filter?.$all].flat().concat(constraints));
1063
973
  return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $all } }, __privateGet$3(this, _data));
1064
974
  } else {
1065
- const $all = compact([(_b = __privateGet$3(this, _data).filter) == null ? void 0 : _b.$all].flat().concat([{ [a]: b }]));
975
+ const $all = compact([__privateGet$3(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
1066
976
  return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { filter: { $all } }, __privateGet$3(this, _data));
1067
977
  }
1068
978
  }
1069
979
  sort(column, direction) {
1070
- var _a;
1071
- const originalSort = [(_a = __privateGet$3(this, _data).sort) != null ? _a : []].flat();
980
+ const originalSort = [__privateGet$3(this, _data).sort ?? []].flat();
1072
981
  const sort = [...originalSort, { column, direction }];
1073
982
  return new _Query(__privateGet$3(this, _repository), __privateGet$3(this, _table$1), { sort }, __privateGet$3(this, _data));
1074
983
  }
@@ -1131,11 +1040,10 @@ _repository = new WeakMap();
1131
1040
  _data = new WeakMap();
1132
1041
 
1133
1042
  function isIdentifiable(x) {
1134
- return isObject(x) && isString(x == null ? void 0 : x.id);
1043
+ return isObject(x) && isString(x?.id);
1135
1044
  }
1136
1045
  function isXataRecord(x) {
1137
- var _a;
1138
- return isIdentifiable(x) && typeof (x == null ? void 0 : x.xata) === "object" && typeof ((_a = x == null ? void 0 : x.xata) == null ? void 0 : _a.version) === "number";
1046
+ return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1139
1047
  }
1140
1048
 
1141
1049
  function isSortFilterString(value) {
@@ -1148,7 +1056,6 @@ function isSortFilterObject(filter) {
1148
1056
  return isObject(filter) && !isSortFilterBase(filter) && filter.column !== void 0;
1149
1057
  }
1150
1058
  function buildSortFilter(filter) {
1151
- var _a;
1152
1059
  if (isSortFilterString(filter)) {
1153
1060
  return { [filter]: "asc" };
1154
1061
  } else if (Array.isArray(filter)) {
@@ -1156,7 +1063,7 @@ function buildSortFilter(filter) {
1156
1063
  } else if (isSortFilterBase(filter)) {
1157
1064
  return filter;
1158
1065
  } else if (isSortFilterObject(filter)) {
1159
- return { [filter.column]: (_a = filter.direction) != null ? _a : "asc" };
1066
+ return { [filter.column]: filter.direction ?? "asc" };
1160
1067
  } else {
1161
1068
  throw new Error(`Invalid sort filter: ${filter}`);
1162
1069
  }
@@ -1184,7 +1091,7 @@ var __privateMethod$2 = (obj, member, method) => {
1184
1091
  __accessCheck$3(obj, member, "access private method");
1185
1092
  return method;
1186
1093
  };
1187
- var _table, _links, _getFetchProps, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _initObject, initObject_fn;
1094
+ var _table, _links, _getFetchProps, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn;
1188
1095
  class Repository extends Query {
1189
1096
  }
1190
1097
  class RestRepository extends Query {
@@ -1196,13 +1103,11 @@ class RestRepository extends Query {
1196
1103
  __privateAdd$3(this, _updateRecordWithID);
1197
1104
  __privateAdd$3(this, _upsertRecordWithID);
1198
1105
  __privateAdd$3(this, _deleteRecord);
1199
- __privateAdd$3(this, _initObject);
1200
1106
  __privateAdd$3(this, _table, void 0);
1201
1107
  __privateAdd$3(this, _links, void 0);
1202
1108
  __privateAdd$3(this, _getFetchProps, void 0);
1203
- var _a;
1204
1109
  __privateSet$1(this, _table, options.table);
1205
- __privateSet$1(this, _links, (_a = options.links) != null ? _a : {});
1110
+ __privateSet$1(this, _links, options.links ?? {});
1206
1111
  __privateSet$1(this, _getFetchProps, options.getFetchProps);
1207
1112
  this.db = options.db;
1208
1113
  }
@@ -1232,7 +1137,7 @@ class RestRepository extends Query {
1232
1137
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$2(this, _table), recordId },
1233
1138
  ...fetchProps
1234
1139
  });
1235
- return __privateMethod$2(this, _initObject, initObject_fn).call(this, __privateGet$2(this, _table), response);
1140
+ return initObject(this.db, __privateGet$2(this, _links), __privateGet$2(this, _table), response);
1236
1141
  } catch (e) {
1237
1142
  if (isObject(e) && e.status === 404) {
1238
1143
  return null;
@@ -1295,13 +1200,12 @@ class RestRepository extends Query {
1295
1200
  body: { tables: [__privateGet$2(this, _table)], query, fuzziness: options.fuzziness },
1296
1201
  ...fetchProps
1297
1202
  });
1298
- return records.map((item) => __privateMethod$2(this, _initObject, initObject_fn).call(this, __privateGet$2(this, _table), item));
1203
+ return records.map((item) => initObject(this.db, __privateGet$2(this, _links), __privateGet$2(this, _table), item));
1299
1204
  }
1300
1205
  async query(query) {
1301
- var _a;
1302
1206
  const data = query.getQueryOptions();
1303
1207
  const body = {
1304
- filter: Object.values((_a = data.filter) != null ? _a : {}).some(Boolean) ? data.filter : void 0,
1208
+ filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1305
1209
  sort: data.sort ? buildSortFilter(data.sort) : void 0,
1306
1210
  page: data.page,
1307
1211
  columns: data.columns
@@ -1312,7 +1216,7 @@ class RestRepository extends Query {
1312
1216
  body,
1313
1217
  ...fetchProps
1314
1218
  });
1315
- const records = objects.map((record) => __privateMethod$2(this, _initObject, initObject_fn).call(this, __privateGet$2(this, _table), record));
1219
+ const records = objects.map((record) => initObject(this.db, __privateGet$2(this, _links), __privateGet$2(this, _table), record));
1316
1220
  return new Page(query, meta, records);
1317
1221
  }
1318
1222
  }
@@ -1409,19 +1313,24 @@ deleteRecord_fn = async function(recordId) {
1409
1313
  ...fetchProps
1410
1314
  });
1411
1315
  };
1412
- _initObject = new WeakSet();
1413
- initObject_fn = function(table, object) {
1316
+ const transformObjectLinks = (object) => {
1317
+ return Object.entries(object).reduce((acc, [key, value]) => {
1318
+ if (key === "xata")
1319
+ return acc;
1320
+ return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1321
+ }, {});
1322
+ };
1323
+ const initObject = (db, links, table, object) => {
1414
1324
  const result = {};
1415
1325
  Object.assign(result, object);
1416
- const tableLinks = __privateGet$2(this, _links)[table] || [];
1326
+ const tableLinks = links[table] || [];
1417
1327
  for (const link of tableLinks) {
1418
1328
  const [field, linkTable] = link;
1419
1329
  const value = result[field];
1420
1330
  if (value && isObject(value)) {
1421
- result[field] = __privateMethod$2(this, _initObject, initObject_fn).call(this, linkTable, value);
1331
+ result[field] = initObject(db, links, linkTable, value);
1422
1332
  }
1423
1333
  }
1424
- const db = this.db;
1425
1334
  result.read = function() {
1426
1335
  return db[table].read(result["id"]);
1427
1336
  };
@@ -1437,13 +1346,6 @@ initObject_fn = function(table, object) {
1437
1346
  Object.freeze(result);
1438
1347
  return result;
1439
1348
  };
1440
- const transformObjectLinks = (object) => {
1441
- return Object.entries(object).reduce((acc, [key, value]) => {
1442
- if (key === "xata")
1443
- return acc;
1444
- return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1445
- }, {});
1446
- };
1447
1349
 
1448
1350
  const gt = (value) => ({ $gt: value });
1449
1351
  const ge = (value) => ({ $ge: value });
@@ -1516,8 +1418,10 @@ var __privateMethod$1 = (obj, member, method) => {
1516
1418
  };
1517
1419
  var _search, search_fn;
1518
1420
  class SearchPlugin extends XataPlugin {
1519
- constructor() {
1520
- super(...arguments);
1421
+ constructor(db, links) {
1422
+ super();
1423
+ this.db = db;
1424
+ this.links = links;
1521
1425
  __privateAdd$1(this, _search);
1522
1426
  }
1523
1427
  build({ getFetchProps }) {
@@ -1526,16 +1430,16 @@ class SearchPlugin extends XataPlugin {
1526
1430
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1527
1431
  return records.map((record) => {
1528
1432
  const { table = "orphan" } = record.xata;
1529
- return { table, record };
1433
+ return { table, record: initObject(this.db, this.links, table, record) };
1530
1434
  });
1531
1435
  },
1532
1436
  byTable: async (query, options = {}) => {
1533
1437
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1534
1438
  return records.reduce((acc, record) => {
1535
- var _a;
1536
1439
  const { table = "orphan" } = record.xata;
1537
- const items = (_a = acc[table]) != null ? _a : [];
1538
- return { ...acc, [table]: [...items, record] };
1440
+ const items = acc[table] ?? [];
1441
+ const item = initObject(this.db, this.links, table, record);
1442
+ return { ...acc, [table]: [...items, item] };
1539
1443
  }, {});
1540
1444
  }
1541
1445
  };
@@ -1544,7 +1448,7 @@ class SearchPlugin extends XataPlugin {
1544
1448
  _search = new WeakSet();
1545
1449
  search_fn = async function(query, options, getFetchProps) {
1546
1450
  const fetchProps = await getFetchProps();
1547
- const { tables, fuzziness } = options != null ? options : {};
1451
+ const { tables, fuzziness } = options ?? {};
1548
1452
  const { records } = await searchBranch({
1549
1453
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1550
1454
  body: { tables, query, fuzziness },
@@ -1557,6 +1461,84 @@ const isBranchStrategyBuilder = (strategy) => {
1557
1461
  return typeof strategy === "function";
1558
1462
  };
1559
1463
 
1464
+ const envBranchNames = [
1465
+ "XATA_BRANCH",
1466
+ "VERCEL_GIT_COMMIT_REF",
1467
+ "CF_PAGES_BRANCH",
1468
+ "BRANCH"
1469
+ ];
1470
+ const defaultBranch = "main";
1471
+ async function getCurrentBranchName(options) {
1472
+ const env = await getBranchByEnvVariable();
1473
+ if (env)
1474
+ return env;
1475
+ const branch = await getGitBranch();
1476
+ if (!branch)
1477
+ return defaultBranch;
1478
+ const details = await getDatabaseBranch(branch, options);
1479
+ if (details)
1480
+ return branch;
1481
+ return defaultBranch;
1482
+ }
1483
+ async function getCurrentBranchDetails(options) {
1484
+ const env = await getBranchByEnvVariable();
1485
+ if (env)
1486
+ return getDatabaseBranch(env, options);
1487
+ const branch = await getGitBranch();
1488
+ if (!branch)
1489
+ return getDatabaseBranch(defaultBranch, options);
1490
+ const details = await getDatabaseBranch(branch, options);
1491
+ if (details)
1492
+ return details;
1493
+ return getDatabaseBranch(defaultBranch, options);
1494
+ }
1495
+ async function getDatabaseBranch(branch, options) {
1496
+ const databaseURL = options?.databaseURL || getDatabaseURL();
1497
+ const apiKey = options?.apiKey || getAPIKey();
1498
+ if (!databaseURL)
1499
+ throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
1500
+ if (!apiKey)
1501
+ throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
1502
+ const [protocol, , host, , database] = databaseURL.split("/");
1503
+ const [workspace] = host.split(".");
1504
+ const dbBranchName = `${database}:${branch}`;
1505
+ try {
1506
+ return await getBranchDetails({
1507
+ apiKey,
1508
+ apiUrl: databaseURL,
1509
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
1510
+ workspacesApiUrl: `${protocol}//${host}`,
1511
+ pathParams: {
1512
+ dbBranchName,
1513
+ workspace
1514
+ }
1515
+ });
1516
+ } catch (err) {
1517
+ if (isObject(err) && err.status === 404)
1518
+ return null;
1519
+ throw err;
1520
+ }
1521
+ }
1522
+ function getBranchByEnvVariable() {
1523
+ for (const name of envBranchNames) {
1524
+ const value = getEnvVariable(name);
1525
+ if (value) {
1526
+ return value;
1527
+ }
1528
+ }
1529
+ try {
1530
+ return XATA_BRANCH;
1531
+ } catch (err) {
1532
+ }
1533
+ }
1534
+ function getDatabaseURL() {
1535
+ try {
1536
+ return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
1537
+ } catch (err) {
1538
+ return void 0;
1539
+ }
1540
+ }
1541
+
1560
1542
  var __accessCheck = (obj, member, msg) => {
1561
1543
  if (!member.has(obj))
1562
1544
  throw TypeError("Cannot " + msg);
@@ -1588,12 +1570,13 @@ const buildClient = (plugins) => {
1588
1570
  __privateAdd(this, _evaluateBranch);
1589
1571
  __privateAdd(this, _branch, void 0);
1590
1572
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
1591
- const namespaces = {
1592
- db: new SchemaPlugin(links),
1593
- search: new SearchPlugin(),
1594
- ...plugins
1595
- };
1596
- for (const [key, namespace] of Object.entries(namespaces)) {
1573
+ const db = new SchemaPlugin(links).build({ getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions) });
1574
+ const search = new SearchPlugin(db, links ?? {}).build({
1575
+ getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions)
1576
+ });
1577
+ this.db = db;
1578
+ this.search = search;
1579
+ for (const [key, namespace] of Object.entries(plugins ?? {})) {
1597
1580
  if (!namespace)
1598
1581
  continue;
1599
1582
  const result = namespace.build({ getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions) });
@@ -1607,10 +1590,10 @@ const buildClient = (plugins) => {
1607
1590
  }
1608
1591
  }
1609
1592
  }, _branch = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
1610
- const fetch = getFetchImplementation(options == null ? void 0 : options.fetch);
1611
- const databaseURL = (options == null ? void 0 : options.databaseURL) || getDatabaseURL();
1612
- const apiKey = (options == null ? void 0 : options.apiKey) || getAPIKey();
1613
- const branch = async () => (options == null ? void 0 : options.branch) ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options == null ? void 0 : options.fetch });
1593
+ const fetch = getFetchImplementation(options?.fetch);
1594
+ const databaseURL = options?.databaseURL || getDatabaseURL();
1595
+ const apiKey = options?.apiKey || getAPIKey();
1596
+ const branch = async () => options?.branch ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1614
1597
  if (!databaseURL || !apiKey) {
1615
1598
  throw new Error("Options databaseURL and apiKey are required");
1616
1599
  }
@@ -1629,8 +1612,7 @@ const buildClient = (plugins) => {
1629
1612
  apiKey,
1630
1613
  apiUrl: "",
1631
1614
  workspacesApiUrl: (path, params) => {
1632
- var _a2;
1633
- const hasBranch = (_a2 = params.dbBranchName) != null ? _a2 : params.branch;
1615
+ const hasBranch = params.dbBranchName ?? params.branch;
1634
1616
  const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branchValue}` : "");
1635
1617
  return databaseURL + newPath;
1636
1618
  }