@xata.io/client 0.0.0-alpha.vf4789c2 → 0.0.0-alpha.vf5ce72f

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);
@@ -118,12 +145,14 @@ function getFetchImplementation(userFetch) {
118
145
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
119
146
  const fetchImpl = userFetch ?? globalFetch;
120
147
  if (!fetchImpl) {
121
- 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
+ );
122
151
  }
123
152
  return fetchImpl;
124
153
  }
125
154
 
126
- const VERSION = "0.0.0-alpha.vf4789c2";
155
+ const VERSION = "0.0.0-alpha.vf5ce72f";
127
156
 
128
157
  class ErrorWithCause extends Error {
129
158
  constructor(message, options) {
@@ -202,34 +231,62 @@ async function fetch$1({
202
231
  fetchImpl,
203
232
  apiKey,
204
233
  apiUrl,
205
- workspacesApiUrl
234
+ workspacesApiUrl,
235
+ trace
206
236
  }) {
207
- const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
208
- const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
209
- const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
210
- const response = await fetchImpl(url, {
211
- method: method.toUpperCase(),
212
- body: body ? JSON.stringify(body) : void 0,
213
- headers: {
214
- "Content-Type": "application/json",
215
- "User-Agent": `Xata client-ts/${VERSION}`,
216
- ...headers,
217
- ...hostHeader(fullUrl),
218
- Authorization: `Bearer ${apiKey}`
219
- }
220
- });
221
- if (response.status === 204) {
222
- return {};
223
- }
224
- 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) {
225
285
  try {
226
- const jsonResponse = await response.json();
227
- if (response.ok) {
228
- return jsonResponse;
229
- }
230
- throw new FetcherError(response.status, jsonResponse, requestId);
286
+ const { host, protocol } = new URL(url);
287
+ return { host, protocol };
231
288
  } catch (error) {
232
- throw new FetcherError(response.status, error, requestId);
289
+ return {};
233
290
  }
234
291
  }
235
292
 
@@ -324,6 +381,11 @@ const deleteDatabase = (variables) => fetch$1({
324
381
  method: "delete",
325
382
  ...variables
326
383
  });
384
+ const getDatabaseMetadata = (variables) => fetch$1({
385
+ url: "/dbs/{dbName}/metadata",
386
+ method: "get",
387
+ ...variables
388
+ });
327
389
  const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
328
390
  const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
329
391
  const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
@@ -337,11 +399,7 @@ const getBranchDetails = (variables) => fetch$1({
337
399
  method: "get",
338
400
  ...variables
339
401
  });
340
- const createBranch = (variables) => fetch$1({
341
- url: "/db/{dbBranchName}",
342
- method: "put",
343
- ...variables
344
- });
402
+ const createBranch = (variables) => fetch$1({ url: "/db/{dbBranchName}", method: "put", ...variables });
345
403
  const deleteBranch = (variables) => fetch$1({
346
404
  url: "/db/{dbBranchName}",
347
405
  method: "delete",
@@ -415,11 +473,7 @@ const updateColumn = (variables) => fetch$1({
415
473
  method: "patch",
416
474
  ...variables
417
475
  });
418
- const insertRecord = (variables) => fetch$1({
419
- url: "/db/{dbBranchName}/tables/{tableName}/data",
420
- method: "post",
421
- ...variables
422
- });
476
+ const insertRecord = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables });
423
477
  const insertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables });
424
478
  const updateRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables });
425
479
  const upsertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables });
@@ -470,6 +524,7 @@ const operationsByTag = {
470
524
  getDatabaseList,
471
525
  createDatabase,
472
526
  deleteDatabase,
527
+ getDatabaseMetadata,
473
528
  getGitBranchesMapping,
474
529
  addGitBranchesEntry,
475
530
  removeGitBranchesEntry,
@@ -562,7 +617,8 @@ class XataApiClient {
562
617
  __privateAdd$7(this, _extraProps, void 0);
563
618
  __privateAdd$7(this, _namespaces, {});
564
619
  const provider = options.host ?? "production";
565
- const apiKey = options?.apiKey ?? getAPIKey();
620
+ const apiKey = options.apiKey ?? getAPIKey();
621
+ const trace = options.trace ?? defaultTrace;
566
622
  if (!apiKey) {
567
623
  throw new Error("Could not resolve a valid apiKey");
568
624
  }
@@ -570,7 +626,8 @@ class XataApiClient {
570
626
  apiUrl: getHostUrl(provider, "main"),
571
627
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
572
628
  fetchImpl: getFetchImplementation(options.fetch),
573
- apiKey
629
+ apiKey,
630
+ trace
574
631
  });
575
632
  }
576
633
  get user() {
@@ -742,6 +799,12 @@ class DatabaseApi {
742
799
  ...this.extraProps
743
800
  });
744
801
  }
802
+ getDatabaseMetadata(workspace, dbName) {
803
+ return operationsByTag.database.getDatabaseMetadata({
804
+ pathParams: { workspace, dbName },
805
+ ...this.extraProps
806
+ });
807
+ }
745
808
  getGitBranchesMapping(workspace, dbName) {
746
809
  return operationsByTag.database.getGitBranchesMapping({
747
810
  pathParams: { workspace, dbName },
@@ -914,9 +977,10 @@ class RecordsApi {
914
977
  constructor(extraProps) {
915
978
  this.extraProps = extraProps;
916
979
  }
917
- insertRecord(workspace, database, branch, tableName, record) {
980
+ insertRecord(workspace, database, branch, tableName, record, options = {}) {
918
981
  return operationsByTag.records.insertRecord({
919
982
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
983
+ queryParams: options,
920
984
  body: record,
921
985
  ...this.extraProps
922
986
  });
@@ -945,21 +1009,24 @@ class RecordsApi {
945
1009
  ...this.extraProps
946
1010
  });
947
1011
  }
948
- deleteRecord(workspace, database, branch, tableName, recordId) {
1012
+ deleteRecord(workspace, database, branch, tableName, recordId, options = {}) {
949
1013
  return operationsByTag.records.deleteRecord({
950
1014
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1015
+ queryParams: options,
951
1016
  ...this.extraProps
952
1017
  });
953
1018
  }
954
1019
  getRecord(workspace, database, branch, tableName, recordId, options = {}) {
955
1020
  return operationsByTag.records.getRecord({
956
1021
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1022
+ queryParams: options,
957
1023
  ...this.extraProps
958
1024
  });
959
1025
  }
960
- bulkInsertTableRecords(workspace, database, branch, tableName, records) {
1026
+ bulkInsertTableRecords(workspace, database, branch, tableName, records, options = {}) {
961
1027
  return operationsByTag.records.bulkInsertTableRecords({
962
1028
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1029
+ queryParams: options,
963
1030
  body: { records },
964
1031
  ...this.extraProps
965
1032
  });
@@ -1177,13 +1244,18 @@ const _Query = class {
1177
1244
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1178
1245
  }
1179
1246
  }
1180
- sort(column, direction) {
1247
+ sort(column, direction = "asc") {
1181
1248
  const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
1182
1249
  const sort = [...originalSort, { column, direction }];
1183
1250
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
1184
1251
  }
1185
1252
  select(columns) {
1186
- 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
+ );
1187
1259
  }
1188
1260
  getPaginated(options = {}) {
1189
1261
  const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
@@ -1308,7 +1380,7 @@ var __privateMethod$2 = (obj, member, method) => {
1308
1380
  __accessCheck$4(obj, member, "access private method");
1309
1381
  return method;
1310
1382
  };
1311
- 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;
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;
1312
1384
  class Repository extends Query {
1313
1385
  }
1314
1386
  class RestRepository extends Query {
@@ -1320,191 +1392,211 @@ class RestRepository extends Query {
1320
1392
  __privateAdd$4(this, _updateRecordWithID);
1321
1393
  __privateAdd$4(this, _upsertRecordWithID);
1322
1394
  __privateAdd$4(this, _deleteRecord);
1323
- __privateAdd$4(this, _invalidateCache);
1324
- __privateAdd$4(this, _setCacheRecord);
1325
- __privateAdd$4(this, _getCacheRecord);
1326
1395
  __privateAdd$4(this, _setCacheQuery);
1327
1396
  __privateAdd$4(this, _getCacheQuery);
1328
1397
  __privateAdd$4(this, _getSchemaTables$1);
1329
1398
  __privateAdd$4(this, _table, void 0);
1330
1399
  __privateAdd$4(this, _getFetchProps, void 0);
1400
+ __privateAdd$4(this, _db, void 0);
1331
1401
  __privateAdd$4(this, _cache, void 0);
1332
1402
  __privateAdd$4(this, _schemaTables$2, void 0);
1403
+ __privateAdd$4(this, _trace, void 0);
1333
1404
  __privateSet$4(this, _table, options.table);
1334
1405
  __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1335
- this.db = options.db;
1406
+ __privateSet$4(this, _db, options.db);
1336
1407
  __privateSet$4(this, _cache, options.pluginOptions.cache);
1337
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
+ });
1338
1417
  }
1339
- async create(a, b) {
1340
- if (Array.isArray(a)) {
1341
- if (a.length === 0)
1342
- return [];
1343
- const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1344
- await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1345
- return records;
1346
- }
1347
- if (isString(a) && isObject(b)) {
1348
- if (a === "")
1349
- throw new Error("The id can't be empty");
1350
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1351
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1352
- return record;
1353
- }
1354
- if (isObject(a) && isString(a.id)) {
1355
- if (a.id === "")
1356
- throw new Error("The id can't be empty");
1357
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1358
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1359
- return record;
1360
- }
1361
- if (isObject(a)) {
1362
- const record = await __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1363
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1364
- return record;
1365
- }
1366
- throw new Error("Invalid arguments for create method");
1367
- }
1368
- async read(a) {
1369
- if (Array.isArray(a)) {
1370
- if (a.length === 0)
1371
- return [];
1372
- const ids = a.map((item) => isString(item) ? item : item.id).filter((id2) => isString(id2));
1373
- return this.getAll({ filter: { id: { $any: ids } } });
1374
- }
1375
- const id = isString(a) ? a : a.id;
1376
- if (isString(id)) {
1377
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, id);
1378
- if (cacheRecord)
1379
- return cacheRecord;
1380
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1381
- try {
1382
- const response = await getRecord({
1383
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: id },
1384
- ...fetchProps
1385
- });
1386
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1387
- return initObject(this.db, schemaTables, __privateGet$4(this, _table), response);
1388
- } catch (e) {
1389
- if (isObject(e) && e.status === 404) {
1390
- return null;
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;
1391
1480
  }
1392
- throw e;
1393
1481
  }
1394
- }
1482
+ return null;
1483
+ });
1395
1484
  }
1396
- async update(a, b) {
1397
- if (Array.isArray(a)) {
1398
- if (a.length === 0)
1399
- return [];
1400
- if (a.length > 100) {
1401
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
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");
1492
+ }
1493
+ const columns = isStringArray(b) ? b : ["*"];
1494
+ return Promise.all(a.map((object) => this.update(object, columns)));
1402
1495
  }
1403
- return Promise.all(a.map((object) => this.update(object)));
1404
- }
1405
- if (isString(a) && isObject(b)) {
1406
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1407
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1408
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1409
- return record;
1410
- }
1411
- if (isObject(a) && isString(a.id)) {
1412
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1413
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1414
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1415
- return record;
1416
- }
1417
- throw new Error("Invalid arguments for update method");
1418
- }
1419
- async createOrUpdate(a, b) {
1420
- if (Array.isArray(a)) {
1421
- if (a.length === 0)
1422
- return [];
1423
- if (a.length > 100) {
1424
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
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);
1425
1499
  }
1426
- return Promise.all(a.map((object) => this.createOrUpdate(object)));
1427
- }
1428
- if (isString(a) && isObject(b)) {
1429
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1430
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1431
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1432
- return record;
1433
- }
1434
- if (isObject(a) && isString(a.id)) {
1435
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1436
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1437
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1438
- return record;
1439
- }
1440
- throw new Error("Invalid arguments for createOrUpdate method");
1441
- }
1442
- async delete(a) {
1443
- if (Array.isArray(a)) {
1444
- if (a.length === 0)
1445
- return;
1446
- if (a.length > 100) {
1447
- console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
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);
1448
1503
  }
1449
- await Promise.all(a.map((id) => this.delete(id)));
1450
- return;
1451
- }
1452
- if (isString(a)) {
1453
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1454
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1455
- return;
1456
- }
1457
- if (isObject(a) && isString(a.id)) {
1458
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1459
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1460
- return;
1461
- }
1462
- throw new Error("Invalid arguments for delete method");
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");
1514
+ }
1515
+ const columns = isStringArray(b) ? b : ["*"];
1516
+ return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
1517
+ }
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
+ });
1528
+ }
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)));
1538
+ }
1539
+ if (isString(a)) {
1540
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
1541
+ }
1542
+ if (isObject(a) && isString(a.id)) {
1543
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id, b);
1544
+ }
1545
+ throw new Error("Invalid arguments for delete method");
1546
+ });
1463
1547
  }
1464
1548
  async search(query, options = {}) {
1465
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1466
- const { records } = await searchTable({
1467
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1468
- body: {
1469
- query,
1470
- fuzziness: options.fuzziness,
1471
- highlight: options.highlight,
1472
- filter: options.filter
1473
- },
1474
- ...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));
1475
1565
  });
1476
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1477
- return records.map((item) => initObject(this.db, schemaTables, __privateGet$4(this, _table), item));
1478
1566
  }
1479
1567
  async query(query) {
1480
- const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1481
- if (cacheQuery)
1482
- return new Page(query, cacheQuery.meta, cacheQuery.records);
1483
- const data = query.getQueryOptions();
1484
- const body = {
1485
- filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1486
- sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1487
- page: data.pagination,
1488
- columns: data.columns
1489
- };
1490
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1491
- const { meta, records: objects } = await queryTable({
1492
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1493
- body,
1494
- ...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);
1495
1589
  });
1496
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1497
- const records = objects.map((record) => initObject(this.db, schemaTables, __privateGet$4(this, _table), record));
1498
- await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1499
- return new Page(query, meta, records);
1500
1590
  }
1501
1591
  }
1502
1592
  _table = new WeakMap();
1503
1593
  _getFetchProps = new WeakMap();
1594
+ _db = new WeakMap();
1504
1595
  _cache = new WeakMap();
1505
1596
  _schemaTables$2 = new WeakMap();
1597
+ _trace = new WeakMap();
1506
1598
  _insertRecordWithoutId = new WeakSet();
1507
- insertRecordWithoutId_fn = async function(object) {
1599
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1508
1600
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1509
1601
  const record = transformObjectLinks(object);
1510
1602
  const response = await insertRecord({
@@ -1513,17 +1605,15 @@ insertRecordWithoutId_fn = async function(object) {
1513
1605
  dbBranchName: "{dbBranch}",
1514
1606
  tableName: __privateGet$4(this, _table)
1515
1607
  },
1608
+ queryParams: { columns },
1516
1609
  body: record,
1517
1610
  ...fetchProps
1518
1611
  });
1519
- const finalObject = await this.read(response.id);
1520
- if (!finalObject) {
1521
- throw new Error("The server failed to save the record");
1522
- }
1523
- 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);
1524
1614
  };
1525
1615
  _insertRecordWithId = new WeakSet();
1526
- insertRecordWithId_fn = async function(recordId, object) {
1616
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
1527
1617
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1528
1618
  const record = transformObjectLinks(object);
1529
1619
  const response = await insertRecordWithID({
@@ -1534,92 +1624,78 @@ insertRecordWithId_fn = async function(recordId, object) {
1534
1624
  recordId
1535
1625
  },
1536
1626
  body: record,
1537
- queryParams: { createOnly: true },
1627
+ queryParams: { createOnly: true, columns },
1538
1628
  ...fetchProps
1539
1629
  });
1540
- const finalObject = await this.read(response.id);
1541
- if (!finalObject) {
1542
- throw new Error("The server failed to save the record");
1543
- }
1544
- 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);
1545
1632
  };
1546
1633
  _bulkInsertTableRecords = new WeakSet();
1547
- bulkInsertTableRecords_fn = async function(objects) {
1634
+ bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
1548
1635
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1549
1636
  const records = objects.map((object) => transformObjectLinks(object));
1550
- const { recordIDs } = await bulkInsertTableRecords({
1637
+ const response = await bulkInsertTableRecords({
1551
1638
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1639
+ queryParams: { columns },
1552
1640
  body: { records },
1553
1641
  ...fetchProps
1554
1642
  });
1555
- const finalObjects = await this.read(recordIDs);
1556
- if (finalObjects.length !== objects.length) {
1557
- 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");
1558
1645
  }
1559
- const dictionary = finalObjects.reduce((acc, object) => {
1560
- acc[object.id] = object;
1561
- return acc;
1562
- }, {});
1563
- return recordIDs.map((id) => dictionary[id]);
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));
1564
1648
  };
1565
1649
  _updateRecordWithID = new WeakSet();
1566
- updateRecordWithID_fn = async function(recordId, object) {
1650
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1567
1651
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1568
1652
  const record = transformObjectLinks(object);
1569
- const response = await updateRecordWithID({
1570
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1571
- body: record,
1572
- ...fetchProps
1573
- });
1574
- const item = await this.read(response.id);
1575
- if (!item)
1576
- throw new Error("The server failed to save the record");
1577
- 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
+ }
1578
1668
  };
1579
1669
  _upsertRecordWithID = new WeakSet();
1580
- upsertRecordWithID_fn = async function(recordId, object) {
1670
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1581
1671
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1582
1672
  const response = await upsertRecordWithID({
1583
1673
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1674
+ queryParams: { columns },
1584
1675
  body: object,
1585
1676
  ...fetchProps
1586
1677
  });
1587
- const item = await this.read(response.id);
1588
- if (!item)
1589
- throw new Error("The server failed to save the record");
1590
- 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);
1591
1680
  };
1592
1681
  _deleteRecord = new WeakSet();
1593
- deleteRecord_fn = async function(recordId) {
1682
+ deleteRecord_fn = async function(recordId, columns = ["*"]) {
1594
1683
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1595
- await deleteRecord({
1596
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1597
- ...fetchProps
1598
- });
1599
- };
1600
- _invalidateCache = new WeakSet();
1601
- invalidateCache_fn = async function(recordId) {
1602
- await __privateGet$4(this, _cache).delete(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1603
- const cacheItems = await __privateGet$4(this, _cache).getAll();
1604
- const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1605
- for (const [key, value] of queries) {
1606
- const ids = getIds(value);
1607
- if (ids.includes(recordId))
1608
- 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;
1609
1697
  }
1610
1698
  };
1611
- _setCacheRecord = new WeakSet();
1612
- setCacheRecord_fn = async function(record) {
1613
- if (!__privateGet$4(this, _cache).cacheRecords)
1614
- return;
1615
- await __privateGet$4(this, _cache).set(`rec_${__privateGet$4(this, _table)}:${record.id}`, record);
1616
- };
1617
- _getCacheRecord = new WeakSet();
1618
- getCacheRecord_fn = async function(recordId) {
1619
- if (!__privateGet$4(this, _cache).cacheRecords)
1620
- return null;
1621
- return __privateGet$4(this, _cache).get(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1622
- };
1623
1699
  _setCacheQuery = new WeakSet();
1624
1700
  setCacheQuery_fn = async function(query, meta, records) {
1625
1701
  await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
@@ -1685,11 +1761,11 @@ const initObject = (db, schemaTables, table, object) => {
1685
1761
  }
1686
1762
  }
1687
1763
  }
1688
- result.read = function() {
1689
- return db[table].read(result["id"]);
1764
+ result.read = function(columns2) {
1765
+ return db[table].read(result["id"], columns2);
1690
1766
  };
1691
- result.update = function(data) {
1692
- return db[table].update(result["id"], data);
1767
+ result.update = function(data, columns2) {
1768
+ return db[table].update(result["id"], data, columns2);
1693
1769
  };
1694
1770
  result.delete = function() {
1695
1771
  return db[table].delete(result["id"]);
@@ -1703,14 +1779,15 @@ const initObject = (db, schemaTables, table, object) => {
1703
1779
  Object.freeze(result);
1704
1780
  return result;
1705
1781
  };
1706
- function getIds(value) {
1707
- if (Array.isArray(value)) {
1708
- return value.map((item) => getIds(item)).flat();
1709
- }
1710
- if (!isObject(value))
1711
- return [];
1712
- const nestedIds = Object.values(value).map((item) => getIds(item)).flat();
1713
- 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;
1714
1791
  }
1715
1792
 
1716
1793
  var __accessCheck$3 = (obj, member, msg) => {
@@ -1737,7 +1814,6 @@ class SimpleCache {
1737
1814
  __privateAdd$3(this, _map, void 0);
1738
1815
  __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1739
1816
  this.capacity = options.max ?? 500;
1740
- this.cacheRecords = options.cacheRecords ?? true;
1741
1817
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1742
1818
  }
1743
1819
  async getAll() {
@@ -1763,18 +1839,25 @@ class SimpleCache {
1763
1839
  }
1764
1840
  _map = new WeakMap();
1765
1841
 
1766
- const gt = (value) => ({ $gt: value });
1767
- const ge = (value) => ({ $ge: value });
1768
- const gte = (value) => ({ $ge: value });
1769
- const lt = (value) => ({ $lt: value });
1770
- const lte = (value) => ({ $le: value });
1771
- 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;
1772
1854
  const exists = (column) => ({ $exists: column });
1773
1855
  const notExists = (column) => ({ $notExists: column });
1774
1856
  const startsWith = (value) => ({ $startsWith: value });
1775
1857
  const endsWith = (value) => ({ $endsWith: value });
1776
1858
  const pattern = (value) => ({ $pattern: value });
1777
1859
  const is = (value) => ({ $is: value });
1860
+ const equals = is;
1778
1861
  const isNot = (value) => ({ $isNot: value });
1779
1862
  const contains = (value) => ({ $contains: value });
1780
1863
  const includes = (value) => ({ $includes: value });
@@ -1809,16 +1892,19 @@ class SchemaPlugin extends XataPlugin {
1809
1892
  __privateSet$2(this, _schemaTables$1, schemaTables);
1810
1893
  }
1811
1894
  build(pluginOptions) {
1812
- const db = new Proxy({}, {
1813
- get: (_target, table) => {
1814
- if (!isString(table))
1815
- throw new Error("Invalid table name");
1816
- if (__privateGet$2(this, _tables)[table] === void 0) {
1817
- __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
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];
1818
1905
  }
1819
- return __privateGet$2(this, _tables)[table];
1820
1906
  }
1821
- });
1907
+ );
1822
1908
  const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
1823
1909
  for (const table of tableNames) {
1824
1910
  db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
@@ -1888,10 +1974,10 @@ _schemaTables = new WeakMap();
1888
1974
  _search = new WeakSet();
1889
1975
  search_fn = async function(query, options, getFetchProps) {
1890
1976
  const fetchProps = await getFetchProps();
1891
- const { tables, fuzziness, highlight } = options ?? {};
1977
+ const { tables, fuzziness, highlight, prefix } = options ?? {};
1892
1978
  const { records } = await searchBranch({
1893
1979
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1894
- body: { tables, query, fuzziness, highlight },
1980
+ body: { tables, query, fuzziness, prefix, highlight },
1895
1981
  ...fetchProps
1896
1982
  });
1897
1983
  return records;
@@ -1932,9 +2018,13 @@ async function resolveXataBranch(gitBranch, options) {
1932
2018
  const databaseURL = options?.databaseURL || getDatabaseURL();
1933
2019
  const apiKey = options?.apiKey || getAPIKey();
1934
2020
  if (!databaseURL)
1935
- 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
+ );
1936
2024
  if (!apiKey)
1937
- 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
+ );
1938
2028
  const [protocol, , host, , dbName] = databaseURL.split("/");
1939
2029
  const [workspace] = host.split(".");
1940
2030
  const { fallbackBranch } = getEnvironment();
@@ -1944,7 +2034,8 @@ async function resolveXataBranch(gitBranch, options) {
1944
2034
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1945
2035
  workspacesApiUrl: `${protocol}//${host}`,
1946
2036
  pathParams: { dbName, workspace },
1947
- queryParams: { gitBranch, fallbackBranch }
2037
+ queryParams: { gitBranch, fallbackBranch },
2038
+ trace: defaultTrace
1948
2039
  });
1949
2040
  return branch;
1950
2041
  }
@@ -1952,9 +2043,13 @@ async function getDatabaseBranch(branch, options) {
1952
2043
  const databaseURL = options?.databaseURL || getDatabaseURL();
1953
2044
  const apiKey = options?.apiKey || getAPIKey();
1954
2045
  if (!databaseURL)
1955
- 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
+ );
1956
2049
  if (!apiKey)
1957
- 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
+ );
1958
2053
  const [protocol, , host, , database] = databaseURL.split("/");
1959
2054
  const [workspace] = host.split(".");
1960
2055
  const dbBranchName = `${database}:${branch}`;
@@ -1964,7 +2059,8 @@ async function getDatabaseBranch(branch, options) {
1964
2059
  apiUrl: databaseURL,
1965
2060
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1966
2061
  workspacesApiUrl: `${protocol}//${host}`,
1967
- pathParams: { dbBranchName, workspace }
2062
+ pathParams: { dbBranchName, workspace },
2063
+ trace: defaultTrace
1968
2064
  });
1969
2065
  } catch (err) {
1970
2066
  if (isObject(err) && err.status === 404)
@@ -2004,17 +2100,20 @@ var __privateMethod = (obj, member, method) => {
2004
2100
  return method;
2005
2101
  };
2006
2102
  const buildClient = (plugins) => {
2007
- 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;
2008
2104
  return _a = class {
2009
2105
  constructor(options = {}, schemaTables) {
2010
2106
  __privateAdd(this, _parseOptions);
2011
2107
  __privateAdd(this, _getFetchProps);
2012
2108
  __privateAdd(this, _evaluateBranch);
2013
2109
  __privateAdd(this, _branch, void 0);
2110
+ __privateAdd(this, _options, void 0);
2014
2111
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
2112
+ __privateSet(this, _options, safeOptions);
2015
2113
  const pluginOptions = {
2016
2114
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
2017
- cache: safeOptions.cache
2115
+ cache: safeOptions.cache,
2116
+ trace: safeOptions.trace
2018
2117
  };
2019
2118
  const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2020
2119
  const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
@@ -2033,22 +2132,26 @@ const buildClient = (plugins) => {
2033
2132
  }
2034
2133
  }
2035
2134
  }
2036
- }, _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) {
2037
2141
  const fetch = getFetchImplementation(options?.fetch);
2038
2142
  const databaseURL = options?.databaseURL || getDatabaseURL();
2039
2143
  const apiKey = options?.apiKey || getAPIKey();
2040
- 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;
2041
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 });
2042
- if (!databaseURL || !apiKey) {
2043
- throw new Error("Options databaseURL and apiKey are required");
2147
+ if (!apiKey) {
2148
+ throw new Error("Option apiKey is required");
2044
2149
  }
2045
- return { fetch, databaseURL, apiKey, branch, cache };
2046
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
2047
- fetch,
2048
- apiKey,
2049
- databaseURL,
2050
- branch
2051
- }) {
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 }) {
2052
2155
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
2053
2156
  if (!branchValue)
2054
2157
  throw new Error("Unable to resolve branch value");
@@ -2060,7 +2163,8 @@ const buildClient = (plugins) => {
2060
2163
  const hasBranch = params.dbBranchName ?? params.branch;
2061
2164
  const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branchValue}` : "");
2062
2165
  return databaseURL + newPath;
2063
- }
2166
+ },
2167
+ trace
2064
2168
  };
2065
2169
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
2066
2170
  if (__privateGet(this, _branch))
@@ -2083,6 +2187,88 @@ const buildClient = (plugins) => {
2083
2187
  class BaseClient extends buildClient() {
2084
2188
  }
2085
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
+
2086
2272
  class XataError extends Error {
2087
2273
  constructor(message, status) {
2088
2274
  super(message);
@@ -2090,5 +2276,5 @@ class XataError extends Error {
2090
2276
  }
2091
2277
  }
2092
2278
 
2093
- 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, updateWorkspaceMemberInvite, 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 };
2094
2280
  //# sourceMappingURL=index.mjs.map