@xata.io/client 0.0.0-alpha.vfaca77b → 0.0.0-alpha.vfb22b4f

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -2,6 +2,24 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
+ function _interopNamespace(e) {
6
+ if (e && e.__esModule) return e;
7
+ var n = Object.create(null);
8
+ if (e) {
9
+ Object.keys(e).forEach(function (k) {
10
+ if (k !== 'default') {
11
+ var d = Object.getOwnPropertyDescriptor(e, k);
12
+ Object.defineProperty(n, k, d.get ? d : {
13
+ enumerable: true,
14
+ get: function () { return e[k]; }
15
+ });
16
+ }
17
+ });
18
+ }
19
+ n["default"] = e;
20
+ return Object.freeze(n);
21
+ }
22
+
5
23
  function notEmpty(value) {
6
24
  return value !== null && value !== void 0;
7
25
  }
@@ -21,39 +39,86 @@ function toBase64(value) {
21
39
  try {
22
40
  return btoa(value);
23
41
  } catch (err) {
24
- return Buffer.from(value).toString("base64");
42
+ const buf = Buffer;
43
+ return buf.from(value).toString("base64");
25
44
  }
26
45
  }
27
46
 
28
- function getEnvVariable(name) {
47
+ function getEnvironment() {
29
48
  try {
30
- if (isObject(process) && isString(process?.env?.[name])) {
31
- return process.env[name];
49
+ if (isObject(process) && isObject(process.env)) {
50
+ return {
51
+ apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
52
+ databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
53
+ branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
54
+ envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
55
+ fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
56
+ };
32
57
  }
33
58
  } catch (err) {
34
59
  }
35
60
  try {
36
- if (isObject(Deno) && isString(Deno?.env?.get(name))) {
37
- return Deno.env.get(name);
61
+ if (isObject(Deno) && isObject(Deno.env)) {
62
+ return {
63
+ apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
64
+ databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
65
+ branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
66
+ envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
67
+ fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
68
+ };
38
69
  }
39
70
  } catch (err) {
40
71
  }
72
+ return {
73
+ apiKey: getGlobalApiKey(),
74
+ databaseURL: getGlobalDatabaseURL(),
75
+ branch: getGlobalBranch(),
76
+ envBranch: void 0,
77
+ fallbackBranch: getGlobalFallbackBranch()
78
+ };
79
+ }
80
+ function getGlobalApiKey() {
81
+ try {
82
+ return XATA_API_KEY;
83
+ } catch (err) {
84
+ return void 0;
85
+ }
86
+ }
87
+ function getGlobalDatabaseURL() {
88
+ try {
89
+ return XATA_DATABASE_URL;
90
+ } catch (err) {
91
+ return void 0;
92
+ }
93
+ }
94
+ function getGlobalBranch() {
95
+ try {
96
+ return XATA_BRANCH;
97
+ } catch (err) {
98
+ return void 0;
99
+ }
100
+ }
101
+ function getGlobalFallbackBranch() {
102
+ try {
103
+ return XATA_FALLBACK_BRANCH;
104
+ } catch (err) {
105
+ return void 0;
106
+ }
41
107
  }
42
108
  async function getGitBranch() {
109
+ const cmd = ["git", "branch", "--show-current"];
110
+ const nodeModule = ["child", "process"].join("_");
43
111
  try {
44
112
  if (typeof require === "function") {
45
- const req = require;
46
- return req("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
113
+ return require(nodeModule).execSync(cmd.join(" "), { encoding: "utf-8" }).trim();
47
114
  }
115
+ const { execSync } = await (function (t) { return Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require(t)); }); })(nodeModule);
116
+ return execSync(cmd.join(" "), { encoding: "utf-8" }).toString().trim();
48
117
  } catch (err) {
49
118
  }
50
119
  try {
51
120
  if (isObject(Deno)) {
52
- const process2 = Deno.run({
53
- cmd: ["git", "branch", "--show-current"],
54
- stdout: "piped",
55
- stderr: "piped"
56
- });
121
+ const process2 = Deno.run({ cmd, stdout: "piped", stderr: "piped" });
57
122
  return new TextDecoder().decode(await process2.output()).trim();
58
123
  }
59
124
  } catch (err) {
@@ -62,7 +127,8 @@ async function getGitBranch() {
62
127
 
63
128
  function getAPIKey() {
64
129
  try {
65
- return getEnvVariable("XATA_API_KEY") ?? XATA_API_KEY;
130
+ const { apiKey } = getEnvironment();
131
+ return apiKey;
66
132
  } catch (err) {
67
133
  return void 0;
68
134
  }
@@ -77,21 +143,28 @@ function getFetchImplementation(userFetch) {
77
143
  return fetchImpl;
78
144
  }
79
145
 
146
+ const VERSION = "0.0.0-alpha.vfb22b4f";
147
+
80
148
  class ErrorWithCause extends Error {
81
149
  constructor(message, options) {
82
150
  super(message, options);
83
151
  }
84
152
  }
85
153
  class FetcherError extends ErrorWithCause {
86
- constructor(status, data) {
154
+ constructor(status, data, requestId) {
87
155
  super(getMessage(data));
88
156
  this.status = status;
89
157
  this.errors = isBulkError(data) ? data.errors : void 0;
158
+ this.requestId = requestId;
90
159
  if (data instanceof Error) {
91
160
  this.stack = data.stack;
92
161
  this.cause = data.cause;
93
162
  }
94
163
  }
164
+ toString() {
165
+ const error = super.toString();
166
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
167
+ }
95
168
  }
96
169
  function isBulkError(error) {
97
170
  return isObject(error) && Array.isArray(error.errors);
@@ -114,7 +187,12 @@ function getMessage(data) {
114
187
  }
115
188
 
116
189
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
117
- const query = new URLSearchParams(queryParams).toString();
190
+ const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
191
+ if (value === void 0 || value === null)
192
+ return acc;
193
+ return { ...acc, [key]: value };
194
+ }, {});
195
+ const query = new URLSearchParams(cleanQueryParams).toString();
118
196
  const queryString = query.length > 0 ? `?${query}` : "";
119
197
  return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
120
198
  };
@@ -154,6 +232,7 @@ async function fetch$1({
154
232
  body: body ? JSON.stringify(body) : void 0,
155
233
  headers: {
156
234
  "Content-Type": "application/json",
235
+ "User-Agent": `Xata client-ts/${VERSION}`,
157
236
  ...headers,
158
237
  ...hostHeader(fullUrl),
159
238
  Authorization: `Bearer ${apiKey}`
@@ -162,14 +241,15 @@ async function fetch$1({
162
241
  if (response.status === 204) {
163
242
  return {};
164
243
  }
244
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
165
245
  try {
166
246
  const jsonResponse = await response.json();
167
247
  if (response.ok) {
168
248
  return jsonResponse;
169
249
  }
170
- throw new FetcherError(response.status, jsonResponse);
250
+ throw new FetcherError(response.status, jsonResponse, requestId);
171
251
  } catch (error) {
172
- throw new FetcherError(response.status, error);
252
+ throw new FetcherError(response.status, error, requestId);
173
253
  }
174
254
  }
175
255
 
@@ -489,7 +569,7 @@ var __privateAdd$7 = (obj, member, value) => {
489
569
  throw TypeError("Cannot add the same private member more than once");
490
570
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
491
571
  };
492
- var __privateSet$6 = (obj, member, value, setter) => {
572
+ var __privateSet$7 = (obj, member, value, setter) => {
493
573
  __accessCheck$7(obj, member, "write to private field");
494
574
  setter ? setter.call(obj, value) : member.set(obj, value);
495
575
  return value;
@@ -504,7 +584,7 @@ class XataApiClient {
504
584
  if (!apiKey) {
505
585
  throw new Error("Could not resolve a valid apiKey");
506
586
  }
507
- __privateSet$6(this, _extraProps, {
587
+ __privateSet$7(this, _extraProps, {
508
588
  apiUrl: getHostUrl(provider, "main"),
509
589
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
510
590
  fetchImpl: getFetchImplementation(options.fetch),
@@ -693,10 +773,10 @@ class DatabaseApi {
693
773
  ...this.extraProps
694
774
  });
695
775
  }
696
- resolveBranch(workspace, dbName, gitBranch) {
776
+ resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
697
777
  return operationsByTag.database.resolveBranch({
698
778
  pathParams: { workspace, dbName },
699
- queryParams: { gitBranch },
779
+ queryParams: { gitBranch, fallbackBranch },
700
780
  ...this.extraProps
701
781
  });
702
782
  }
@@ -941,18 +1021,18 @@ var __privateAdd$6 = (obj, member, value) => {
941
1021
  throw TypeError("Cannot add the same private member more than once");
942
1022
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
943
1023
  };
944
- var __privateSet$5 = (obj, member, value, setter) => {
1024
+ var __privateSet$6 = (obj, member, value, setter) => {
945
1025
  __accessCheck$6(obj, member, "write to private field");
946
1026
  setter ? setter.call(obj, value) : member.set(obj, value);
947
1027
  return value;
948
1028
  };
949
- var _query;
1029
+ var _query, _page;
950
1030
  class Page {
951
1031
  constructor(query, meta, records = []) {
952
1032
  __privateAdd$6(this, _query, void 0);
953
- __privateSet$5(this, _query, query);
1033
+ __privateSet$6(this, _query, query);
954
1034
  this.meta = meta;
955
- this.records = records;
1035
+ this.records = new RecordArray(this, records);
956
1036
  }
957
1037
  async nextPage(size, offset) {
958
1038
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
@@ -972,12 +1052,56 @@ class Page {
972
1052
  }
973
1053
  _query = new WeakMap();
974
1054
  const PAGINATION_MAX_SIZE = 200;
975
- const PAGINATION_DEFAULT_SIZE = 200;
1055
+ const PAGINATION_DEFAULT_SIZE = 20;
976
1056
  const PAGINATION_MAX_OFFSET = 800;
977
1057
  const PAGINATION_DEFAULT_OFFSET = 0;
978
1058
  function isCursorPaginationOptions(options) {
979
1059
  return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
980
1060
  }
1061
+ const _RecordArray = class extends Array {
1062
+ constructor(...args) {
1063
+ super(..._RecordArray.parseConstructorParams(...args));
1064
+ __privateAdd$6(this, _page, void 0);
1065
+ __privateSet$6(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
1066
+ }
1067
+ static parseConstructorParams(...args) {
1068
+ if (args.length === 1 && typeof args[0] === "number") {
1069
+ return new Array(args[0]);
1070
+ }
1071
+ if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
1072
+ const result = args[1] ?? args[0].records ?? [];
1073
+ return new Array(...result);
1074
+ }
1075
+ return new Array(...args);
1076
+ }
1077
+ toArray() {
1078
+ return new Array(...this);
1079
+ }
1080
+ map(callbackfn, thisArg) {
1081
+ return this.toArray().map(callbackfn, thisArg);
1082
+ }
1083
+ async nextPage(size, offset) {
1084
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1085
+ return new _RecordArray(newPage);
1086
+ }
1087
+ async previousPage(size, offset) {
1088
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1089
+ return new _RecordArray(newPage);
1090
+ }
1091
+ async firstPage(size, offset) {
1092
+ const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1093
+ return new _RecordArray(newPage);
1094
+ }
1095
+ async lastPage(size, offset) {
1096
+ const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1097
+ return new _RecordArray(newPage);
1098
+ }
1099
+ hasNextPage() {
1100
+ return __privateGet$6(this, _page).meta.page.more;
1101
+ }
1102
+ };
1103
+ let RecordArray = _RecordArray;
1104
+ _page = new WeakMap();
981
1105
 
982
1106
  var __accessCheck$5 = (obj, member, msg) => {
983
1107
  if (!member.has(obj))
@@ -992,7 +1116,7 @@ var __privateAdd$5 = (obj, member, value) => {
992
1116
  throw TypeError("Cannot add the same private member more than once");
993
1117
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
994
1118
  };
995
- var __privateSet$4 = (obj, member, value, setter) => {
1119
+ var __privateSet$5 = (obj, member, value, setter) => {
996
1120
  __accessCheck$5(obj, member, "write to private field");
997
1121
  setter ? setter.call(obj, value) : member.set(obj, value);
998
1122
  return value;
@@ -1004,12 +1128,12 @@ const _Query = class {
1004
1128
  __privateAdd$5(this, _repository, void 0);
1005
1129
  __privateAdd$5(this, _data, { filter: {} });
1006
1130
  this.meta = { page: { cursor: "start", more: true } };
1007
- this.records = [];
1008
- __privateSet$4(this, _table$1, table);
1131
+ this.records = new RecordArray(this, []);
1132
+ __privateSet$5(this, _table$1, table);
1009
1133
  if (repository) {
1010
- __privateSet$4(this, _repository, repository);
1134
+ __privateSet$5(this, _repository, repository);
1011
1135
  } else {
1012
- __privateSet$4(this, _repository, this);
1136
+ __privateSet$5(this, _repository, this);
1013
1137
  }
1014
1138
  const parent = cleanParent(data, rawParent);
1015
1139
  __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
@@ -1093,8 +1217,11 @@ const _Query = class {
1093
1217
  }
1094
1218
  }
1095
1219
  async getMany(options = {}) {
1096
- const { records } = await this.getPaginated(options);
1097
- return records;
1220
+ const page = await this.getPaginated(options);
1221
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1222
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1223
+ }
1224
+ return page.records;
1098
1225
  }
1099
1226
  async getAll(options = {}) {
1100
1227
  const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
@@ -1183,7 +1310,7 @@ var __privateAdd$4 = (obj, member, value) => {
1183
1310
  throw TypeError("Cannot add the same private member more than once");
1184
1311
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1185
1312
  };
1186
- var __privateSet$3 = (obj, member, value, setter) => {
1313
+ var __privateSet$4 = (obj, member, value, setter) => {
1187
1314
  __accessCheck$4(obj, member, "write to private field");
1188
1315
  setter ? setter.call(obj, value) : member.set(obj, value);
1189
1316
  return value;
@@ -1192,7 +1319,7 @@ var __privateMethod$2 = (obj, member, method) => {
1192
1319
  __accessCheck$4(obj, member, "access private method");
1193
1320
  return method;
1194
1321
  };
1195
- 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;
1322
+ var _table, _getFetchProps, _cache, _schemaTables$2, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _invalidateCache, invalidateCache_fn, _setCacheRecord, setCacheRecord_fn, _getCacheRecord, getCacheRecord_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaTables$1, getSchemaTables_fn$1;
1196
1323
  class Repository extends Query {
1197
1324
  }
1198
1325
  class RestRepository extends Query {
@@ -1209,15 +1336,16 @@ class RestRepository extends Query {
1209
1336
  __privateAdd$4(this, _getCacheRecord);
1210
1337
  __privateAdd$4(this, _setCacheQuery);
1211
1338
  __privateAdd$4(this, _getCacheQuery);
1212
- __privateAdd$4(this, _getSchema$1);
1339
+ __privateAdd$4(this, _getSchemaTables$1);
1213
1340
  __privateAdd$4(this, _table, void 0);
1214
1341
  __privateAdd$4(this, _getFetchProps, void 0);
1215
1342
  __privateAdd$4(this, _cache, void 0);
1216
- __privateAdd$4(this, _schema$1, void 0);
1217
- __privateSet$3(this, _table, options.table);
1218
- __privateSet$3(this, _getFetchProps, options.pluginOptions.getFetchProps);
1343
+ __privateAdd$4(this, _schemaTables$2, void 0);
1344
+ __privateSet$4(this, _table, options.table);
1345
+ __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1219
1346
  this.db = options.db;
1220
- __privateSet$3(this, _cache, options.pluginOptions.cache);
1347
+ __privateSet$4(this, _cache, options.pluginOptions.cache);
1348
+ __privateSet$4(this, _schemaTables$2, options.schemaTables);
1221
1349
  }
1222
1350
  async create(a, b) {
1223
1351
  if (Array.isArray(a)) {
@@ -1252,20 +1380,22 @@ class RestRepository extends Query {
1252
1380
  if (Array.isArray(a)) {
1253
1381
  if (a.length === 0)
1254
1382
  return [];
1255
- return this.getAll({ filter: { id: { $any: a } } });
1383
+ const ids = a.map((item) => isString(item) ? item : item.id).filter((id2) => isString(id2));
1384
+ return this.getAll({ filter: { id: { $any: ids } } });
1256
1385
  }
1257
- if (isString(a)) {
1258
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, a);
1386
+ const id = isString(a) ? a : a.id;
1387
+ if (isString(id)) {
1388
+ const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, id);
1259
1389
  if (cacheRecord)
1260
1390
  return cacheRecord;
1261
1391
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1262
1392
  try {
1263
1393
  const response = await getRecord({
1264
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: a },
1394
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: id },
1265
1395
  ...fetchProps
1266
1396
  });
1267
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1268
- return initObject(this.db, schema, __privateGet$4(this, _table), response);
1397
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1398
+ return initObject(this.db, schemaTables, __privateGet$4(this, _table), response);
1269
1399
  } catch (e) {
1270
1400
  if (isObject(e) && e.status === 404) {
1271
1401
  return null;
@@ -1354,8 +1484,8 @@ class RestRepository extends Query {
1354
1484
  },
1355
1485
  ...fetchProps
1356
1486
  });
1357
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1358
- return records.map((item) => initObject(this.db, schema, __privateGet$4(this, _table), item));
1487
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1488
+ return records.map((item) => initObject(this.db, schemaTables, __privateGet$4(this, _table), item));
1359
1489
  }
1360
1490
  async query(query) {
1361
1491
  const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
@@ -1374,8 +1504,8 @@ class RestRepository extends Query {
1374
1504
  body,
1375
1505
  ...fetchProps
1376
1506
  });
1377
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1378
- const records = objects.map((record) => initObject(this.db, schema, __privateGet$4(this, _table), record));
1507
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1508
+ const records = objects.map((record) => initObject(this.db, schemaTables, __privateGet$4(this, _table), record));
1379
1509
  await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1380
1510
  return new Page(query, meta, records);
1381
1511
  }
@@ -1383,7 +1513,7 @@ class RestRepository extends Query {
1383
1513
  _table = new WeakMap();
1384
1514
  _getFetchProps = new WeakMap();
1385
1515
  _cache = new WeakMap();
1386
- _schema$1 = new WeakMap();
1516
+ _schemaTables$2 = new WeakMap();
1387
1517
  _insertRecordWithoutId = new WeakSet();
1388
1518
  insertRecordWithoutId_fn = async function(object) {
1389
1519
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
@@ -1428,16 +1558,20 @@ _bulkInsertTableRecords = new WeakSet();
1428
1558
  bulkInsertTableRecords_fn = async function(objects) {
1429
1559
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1430
1560
  const records = objects.map((object) => transformObjectLinks(object));
1431
- const response = await bulkInsertTableRecords({
1561
+ const { recordIDs } = await bulkInsertTableRecords({
1432
1562
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1433
1563
  body: { records },
1434
1564
  ...fetchProps
1435
1565
  });
1436
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1566
+ const finalObjects = await this.read(recordIDs);
1437
1567
  if (finalObjects.length !== objects.length) {
1438
1568
  throw new Error("The server failed to save some records");
1439
1569
  }
1440
- return finalObjects;
1570
+ const dictionary = finalObjects.reduce((acc, object) => {
1571
+ acc[object.id] = object;
1572
+ return acc;
1573
+ }, {});
1574
+ return recordIDs.map((id) => dictionary[id]);
1441
1575
  };
1442
1576
  _updateRecordWithID = new WeakSet();
1443
1577
  updateRecordWithID_fn = async function(recordId, object) {
@@ -1513,17 +1647,17 @@ getCacheQuery_fn = async function(query) {
1513
1647
  const hasExpired = result.date.getTime() + ttl < Date.now();
1514
1648
  return hasExpired ? null : result;
1515
1649
  };
1516
- _getSchema$1 = new WeakSet();
1517
- getSchema_fn$1 = async function() {
1518
- if (__privateGet$4(this, _schema$1))
1519
- return __privateGet$4(this, _schema$1);
1650
+ _getSchemaTables$1 = new WeakSet();
1651
+ getSchemaTables_fn$1 = async function() {
1652
+ if (__privateGet$4(this, _schemaTables$2))
1653
+ return __privateGet$4(this, _schemaTables$2);
1520
1654
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1521
1655
  const { schema } = await getBranchDetails({
1522
1656
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1523
1657
  ...fetchProps
1524
1658
  });
1525
- __privateSet$3(this, _schema$1, schema);
1526
- return schema;
1659
+ __privateSet$4(this, _schemaTables$2, schema.tables);
1660
+ return schema.tables;
1527
1661
  };
1528
1662
  const transformObjectLinks = (object) => {
1529
1663
  return Object.entries(object).reduce((acc, [key, value]) => {
@@ -1532,11 +1666,11 @@ const transformObjectLinks = (object) => {
1532
1666
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1533
1667
  }, {});
1534
1668
  };
1535
- const initObject = (db, schema, table, object) => {
1669
+ const initObject = (db, schemaTables, table, object) => {
1536
1670
  const result = {};
1537
1671
  const { xata, ...rest } = object ?? {};
1538
1672
  Object.assign(result, rest);
1539
- const { columns } = schema.tables.find(({ name }) => name === table) ?? {};
1673
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
1540
1674
  if (!columns)
1541
1675
  console.error(`Table ${table} not found in schema`);
1542
1676
  for (const column of columns ?? []) {
@@ -1556,7 +1690,7 @@ const initObject = (db, schema, table, object) => {
1556
1690
  if (!linkTable) {
1557
1691
  console.error(`Failed to parse link for field ${column.name}`);
1558
1692
  } else if (isObject(value)) {
1559
- result[column.name] = initObject(db, schema, linkTable, value);
1693
+ result[column.name] = initObject(db, schemaTables, linkTable, value);
1560
1694
  }
1561
1695
  break;
1562
1696
  }
@@ -1603,7 +1737,7 @@ var __privateAdd$3 = (obj, member, value) => {
1603
1737
  throw TypeError("Cannot add the same private member more than once");
1604
1738
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1605
1739
  };
1606
- var __privateSet$2 = (obj, member, value, setter) => {
1740
+ var __privateSet$3 = (obj, member, value, setter) => {
1607
1741
  __accessCheck$3(obj, member, "write to private field");
1608
1742
  setter ? setter.call(obj, value) : member.set(obj, value);
1609
1743
  return value;
@@ -1612,7 +1746,7 @@ var _map;
1612
1746
  class SimpleCache {
1613
1747
  constructor(options = {}) {
1614
1748
  __privateAdd$3(this, _map, void 0);
1615
- __privateSet$2(this, _map, /* @__PURE__ */ new Map());
1749
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1616
1750
  this.capacity = options.max ?? 500;
1617
1751
  this.cacheRecords = options.cacheRecords ?? true;
1618
1752
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
@@ -1672,12 +1806,18 @@ var __privateAdd$2 = (obj, member, value) => {
1672
1806
  throw TypeError("Cannot add the same private member more than once");
1673
1807
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1674
1808
  };
1675
- var _tables;
1809
+ var __privateSet$2 = (obj, member, value, setter) => {
1810
+ __accessCheck$2(obj, member, "write to private field");
1811
+ setter ? setter.call(obj, value) : member.set(obj, value);
1812
+ return value;
1813
+ };
1814
+ var _tables, _schemaTables$1;
1676
1815
  class SchemaPlugin extends XataPlugin {
1677
- constructor(tableNames) {
1816
+ constructor(schemaTables) {
1678
1817
  super();
1679
- this.tableNames = tableNames;
1680
1818
  __privateAdd$2(this, _tables, {});
1819
+ __privateAdd$2(this, _schemaTables$1, void 0);
1820
+ __privateSet$2(this, _schemaTables$1, schemaTables);
1681
1821
  }
1682
1822
  build(pluginOptions) {
1683
1823
  const db = new Proxy({}, {
@@ -1690,13 +1830,15 @@ class SchemaPlugin extends XataPlugin {
1690
1830
  return __privateGet$2(this, _tables)[table];
1691
1831
  }
1692
1832
  });
1693
- for (const table of this.tableNames ?? []) {
1694
- db[table] = new RestRepository({ db, pluginOptions, table });
1833
+ const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
1834
+ for (const table of tableNames) {
1835
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1695
1836
  }
1696
1837
  return db;
1697
1838
  }
1698
1839
  }
1699
1840
  _tables = new WeakMap();
1841
+ _schemaTables$1 = new WeakMap();
1700
1842
 
1701
1843
  var __accessCheck$1 = (obj, member, msg) => {
1702
1844
  if (!member.has(obj))
@@ -1720,39 +1862,40 @@ var __privateMethod$1 = (obj, member, method) => {
1720
1862
  __accessCheck$1(obj, member, "access private method");
1721
1863
  return method;
1722
1864
  };
1723
- var _schema, _search, search_fn, _getSchema, getSchema_fn;
1865
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1724
1866
  class SearchPlugin extends XataPlugin {
1725
- constructor(db) {
1867
+ constructor(db, schemaTables) {
1726
1868
  super();
1727
1869
  this.db = db;
1728
1870
  __privateAdd$1(this, _search);
1729
- __privateAdd$1(this, _getSchema);
1730
- __privateAdd$1(this, _schema, void 0);
1871
+ __privateAdd$1(this, _getSchemaTables);
1872
+ __privateAdd$1(this, _schemaTables, void 0);
1873
+ __privateSet$1(this, _schemaTables, schemaTables);
1731
1874
  }
1732
1875
  build({ getFetchProps }) {
1733
1876
  return {
1734
1877
  all: async (query, options = {}) => {
1735
1878
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1736
- const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
1879
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1737
1880
  return records.map((record) => {
1738
1881
  const { table = "orphan" } = record.xata;
1739
- return { table, record: initObject(this.db, schema, table, record) };
1882
+ return { table, record: initObject(this.db, schemaTables, table, record) };
1740
1883
  });
1741
1884
  },
1742
1885
  byTable: async (query, options = {}) => {
1743
1886
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1744
- const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
1887
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1745
1888
  return records.reduce((acc, record) => {
1746
1889
  const { table = "orphan" } = record.xata;
1747
1890
  const items = acc[table] ?? [];
1748
- const item = initObject(this.db, schema, table, record);
1891
+ const item = initObject(this.db, schemaTables, table, record);
1749
1892
  return { ...acc, [table]: [...items, item] };
1750
1893
  }, {});
1751
1894
  }
1752
1895
  };
1753
1896
  }
1754
1897
  }
1755
- _schema = new WeakMap();
1898
+ _schemaTables = new WeakMap();
1756
1899
  _search = new WeakSet();
1757
1900
  search_fn = async function(query, options, getFetchProps) {
1758
1901
  const fetchProps = await getFetchProps();
@@ -1764,38 +1907,32 @@ search_fn = async function(query, options, getFetchProps) {
1764
1907
  });
1765
1908
  return records;
1766
1909
  };
1767
- _getSchema = new WeakSet();
1768
- getSchema_fn = async function(getFetchProps) {
1769
- if (__privateGet$1(this, _schema))
1770
- return __privateGet$1(this, _schema);
1910
+ _getSchemaTables = new WeakSet();
1911
+ getSchemaTables_fn = async function(getFetchProps) {
1912
+ if (__privateGet$1(this, _schemaTables))
1913
+ return __privateGet$1(this, _schemaTables);
1771
1914
  const fetchProps = await getFetchProps();
1772
1915
  const { schema } = await getBranchDetails({
1773
1916
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1774
1917
  ...fetchProps
1775
1918
  });
1776
- __privateSet$1(this, _schema, schema);
1777
- return schema;
1919
+ __privateSet$1(this, _schemaTables, schema.tables);
1920
+ return schema.tables;
1778
1921
  };
1779
1922
 
1780
1923
  const isBranchStrategyBuilder = (strategy) => {
1781
1924
  return typeof strategy === "function";
1782
1925
  };
1783
1926
 
1784
- const envBranchNames = [
1785
- "XATA_BRANCH",
1786
- "VERCEL_GIT_COMMIT_REF",
1787
- "CF_PAGES_BRANCH",
1788
- "BRANCH"
1789
- ];
1790
1927
  async function getCurrentBranchName(options) {
1791
- const env = getBranchByEnvVariable();
1792
- if (env) {
1793
- const details = await getDatabaseBranch(env, options);
1928
+ const { branch, envBranch } = getEnvironment();
1929
+ if (branch) {
1930
+ const details = await getDatabaseBranch(branch, options);
1794
1931
  if (details)
1795
- return env;
1796
- console.warn(`Branch ${env} not found in Xata. Ignoring...`);
1932
+ return branch;
1933
+ console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
1797
1934
  }
1798
- const gitBranch = await getGitBranch();
1935
+ const gitBranch = envBranch || await getGitBranch();
1799
1936
  return resolveXataBranch(gitBranch, options);
1800
1937
  }
1801
1938
  async function getCurrentBranchDetails(options) {
@@ -1811,13 +1948,14 @@ async function resolveXataBranch(gitBranch, options) {
1811
1948
  throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
1812
1949
  const [protocol, , host, , dbName] = databaseURL.split("/");
1813
1950
  const [workspace] = host.split(".");
1951
+ const { fallbackBranch } = getEnvironment();
1814
1952
  const { branch } = await resolveBranch({
1815
1953
  apiKey,
1816
1954
  apiUrl: databaseURL,
1817
1955
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1818
1956
  workspacesApiUrl: `${protocol}//${host}`,
1819
1957
  pathParams: { dbName, workspace },
1820
- queryParams: { gitBranch, fallbackBranch: getEnvVariable("XATA_FALLBACK_BRANCH") }
1958
+ queryParams: { gitBranch, fallbackBranch }
1821
1959
  });
1822
1960
  return branch;
1823
1961
  }
@@ -1837,10 +1975,7 @@ async function getDatabaseBranch(branch, options) {
1837
1975
  apiUrl: databaseURL,
1838
1976
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1839
1977
  workspacesApiUrl: `${protocol}//${host}`,
1840
- pathParams: {
1841
- dbBranchName,
1842
- workspace
1843
- }
1978
+ pathParams: { dbBranchName, workspace }
1844
1979
  });
1845
1980
  } catch (err) {
1846
1981
  if (isObject(err) && err.status === 404)
@@ -1848,21 +1983,10 @@ async function getDatabaseBranch(branch, options) {
1848
1983
  throw err;
1849
1984
  }
1850
1985
  }
1851
- function getBranchByEnvVariable() {
1852
- for (const name of envBranchNames) {
1853
- const value = getEnvVariable(name);
1854
- if (value) {
1855
- return value;
1856
- }
1857
- }
1858
- try {
1859
- return XATA_BRANCH;
1860
- } catch (err) {
1861
- }
1862
- }
1863
1986
  function getDatabaseURL() {
1864
1987
  try {
1865
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
1988
+ const { databaseURL } = getEnvironment();
1989
+ return databaseURL;
1866
1990
  } catch (err) {
1867
1991
  return void 0;
1868
1992
  }
@@ -1893,7 +2017,7 @@ var __privateMethod = (obj, member, method) => {
1893
2017
  const buildClient = (plugins) => {
1894
2018
  var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1895
2019
  return _a = class {
1896
- constructor(options = {}, tables) {
2020
+ constructor(options = {}, schemaTables) {
1897
2021
  __privateAdd(this, _parseOptions);
1898
2022
  __privateAdd(this, _getFetchProps);
1899
2023
  __privateAdd(this, _evaluateBranch);
@@ -1903,8 +2027,8 @@ const buildClient = (plugins) => {
1903
2027
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1904
2028
  cache: safeOptions.cache
1905
2029
  };
1906
- const db = new SchemaPlugin(tables).build(pluginOptions);
1907
- const search = new SearchPlugin(db).build(pluginOptions);
2030
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2031
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1908
2032
  this.db = db;
1909
2033
  this.search = search;
1910
2034
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
@@ -1985,6 +2109,7 @@ exports.PAGINATION_MAX_OFFSET = PAGINATION_MAX_OFFSET;
1985
2109
  exports.PAGINATION_MAX_SIZE = PAGINATION_MAX_SIZE;
1986
2110
  exports.Page = Page;
1987
2111
  exports.Query = Query;
2112
+ exports.RecordArray = RecordArray;
1988
2113
  exports.Repository = Repository;
1989
2114
  exports.RestRepository = RestRepository;
1990
2115
  exports.SchemaPlugin = SchemaPlugin;