@xata.io/client 0.0.0-alpha.vf7b5320 → 0.0.0-alpha.vf957886

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
@@ -7,8 +7,11 @@ function compact(arr) {
7
7
  function isObject(value) {
8
8
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
9
9
  }
10
+ function isDefined(value) {
11
+ return value !== null && value !== void 0;
12
+ }
10
13
  function isString(value) {
11
- return value !== void 0 && value !== null && typeof value === "string";
14
+ return isDefined(value) && typeof value === "string";
12
15
  }
13
16
  function toBase64(value) {
14
17
  try {
@@ -70,7 +73,12 @@ function getFetchImplementation(userFetch) {
70
73
  return fetchImpl;
71
74
  }
72
75
 
73
- class FetcherError extends Error {
76
+ class ErrorWithCause extends Error {
77
+ constructor(message, options) {
78
+ super(message, options);
79
+ }
80
+ }
81
+ class FetcherError extends ErrorWithCause {
74
82
  constructor(status, data) {
75
83
  super(getMessage(data));
76
84
  this.status = status;
@@ -366,6 +374,11 @@ const queryTable = (variables) => fetch$1({
366
374
  method: "post",
367
375
  ...variables
368
376
  });
377
+ const searchTable = (variables) => fetch$1({
378
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
379
+ method: "post",
380
+ ...variables
381
+ });
369
382
  const searchBranch = (variables) => fetch$1({
370
383
  url: "/db/{dbBranchName}/search",
371
384
  method: "post",
@@ -429,6 +442,7 @@ const operationsByTag = {
429
442
  getRecord,
430
443
  bulkInsertTableRecords,
431
444
  queryTable,
445
+ searchTable,
432
446
  searchBranch
433
447
  }
434
448
  };
@@ -699,10 +713,10 @@ class BranchApi {
699
713
  ...this.extraProps
700
714
  });
701
715
  }
702
- createBranch(workspace, database, branch, from = "", options = {}) {
716
+ createBranch(workspace, database, branch, from, options = {}) {
703
717
  return operationsByTag.branch.createBranch({
704
718
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
705
- queryParams: { from },
719
+ queryParams: isString(from) ? { from } : void 0,
706
720
  body: options,
707
721
  ...this.extraProps
708
722
  });
@@ -884,6 +898,13 @@ class RecordsApi {
884
898
  ...this.extraProps
885
899
  });
886
900
  }
901
+ searchTable(workspace, database, branch, tableName, query) {
902
+ return operationsByTag.records.searchTable({
903
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
904
+ body: query,
905
+ ...this.extraProps
906
+ });
907
+ }
887
908
  searchBranch(workspace, database, branch, query) {
888
909
  return operationsByTag.records.searchBranch({
889
910
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -950,6 +971,9 @@ const PAGINATION_MAX_SIZE = 200;
950
971
  const PAGINATION_DEFAULT_SIZE = 200;
951
972
  const PAGINATION_MAX_OFFSET = 800;
952
973
  const PAGINATION_DEFAULT_OFFSET = 0;
974
+ function isCursorPaginationOptions(options) {
975
+ return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
976
+ }
953
977
 
954
978
  var __accessCheck$5 = (obj, member, msg) => {
955
979
  if (!member.has(obj))
@@ -971,7 +995,7 @@ var __privateSet$4 = (obj, member, value, setter) => {
971
995
  };
972
996
  var _table$1, _repository, _data;
973
997
  const _Query = class {
974
- constructor(repository, table, data, parent) {
998
+ constructor(repository, table, data, rawParent) {
975
999
  __privateAdd$5(this, _table$1, void 0);
976
1000
  __privateAdd$5(this, _repository, void 0);
977
1001
  __privateAdd$5(this, _data, { filter: {} });
@@ -983,6 +1007,7 @@ const _Query = class {
983
1007
  } else {
984
1008
  __privateSet$4(this, _repository, this);
985
1009
  }
1010
+ const parent = cleanParent(data, rawParent);
986
1011
  __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
987
1012
  __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
988
1013
  __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
@@ -1048,34 +1073,36 @@ const _Query = class {
1048
1073
  return __privateGet$5(this, _repository).query(query);
1049
1074
  }
1050
1075
  async *[Symbol.asyncIterator]() {
1051
- for await (const [record] of this.getIterator(1)) {
1076
+ for await (const [record] of this.getIterator({ batchSize: 1 })) {
1052
1077
  yield record;
1053
1078
  }
1054
1079
  }
1055
- async *getIterator(chunk, options = {}) {
1056
- let offset = 0;
1057
- let end = false;
1058
- while (!end) {
1059
- const { records, meta } = await this.getPaginated({ ...options, pagination: { size: chunk, offset } });
1060
- yield records;
1061
- offset += chunk;
1062
- end = !meta.page.more;
1080
+ async *getIterator(options = {}) {
1081
+ const { batchSize = 1 } = options;
1082
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
1083
+ let more = page.hasNextPage();
1084
+ yield page.records;
1085
+ while (more) {
1086
+ page = await page.nextPage();
1087
+ more = page.hasNextPage();
1088
+ yield page.records;
1063
1089
  }
1064
1090
  }
1065
1091
  async getMany(options = {}) {
1066
1092
  const { records } = await this.getPaginated(options);
1067
1093
  return records;
1068
1094
  }
1069
- async getAll(chunk = PAGINATION_MAX_SIZE, options = {}) {
1095
+ async getAll(options = {}) {
1096
+ const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
1070
1097
  const results = [];
1071
- for await (const page of this.getIterator(chunk, options)) {
1098
+ for await (const page of this.getIterator({ ...rest, batchSize })) {
1072
1099
  results.push(...page);
1073
1100
  }
1074
1101
  return results;
1075
1102
  }
1076
1103
  async getFirst(options = {}) {
1077
1104
  const records = await this.getMany({ ...options, pagination: { size: 1 } });
1078
- return records[0] || null;
1105
+ return records[0] ?? null;
1079
1106
  }
1080
1107
  cache(ttl) {
1081
1108
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
@@ -1100,6 +1127,12 @@ let Query = _Query;
1100
1127
  _table$1 = new WeakMap();
1101
1128
  _repository = new WeakMap();
1102
1129
  _data = new WeakMap();
1130
+ function cleanParent(data, parent) {
1131
+ if (isCursorPaginationOptions(data.pagination)) {
1132
+ return { ...parent, sorting: void 0, filter: void 0 };
1133
+ }
1134
+ return parent;
1135
+ }
1103
1136
 
1104
1137
  function isIdentifiable(x) {
1105
1138
  return isObject(x) && isString(x?.id);
@@ -1290,9 +1323,13 @@ class RestRepository extends Query {
1290
1323
  }
1291
1324
  async search(query, options = {}) {
1292
1325
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1293
- const { records } = await searchBranch({
1294
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1295
- body: { tables: [__privateGet$4(this, _table)], query, fuzziness: options.fuzziness },
1326
+ const { records } = await searchTable({
1327
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1328
+ body: {
1329
+ query,
1330
+ fuzziness: options.fuzziness,
1331
+ filter: options.filter
1332
+ },
1296
1333
  ...fetchProps
1297
1334
  });
1298
1335
  const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
@@ -1305,7 +1342,7 @@ class RestRepository extends Query {
1305
1342
  const data = query.getQueryOptions();
1306
1343
  const body = {
1307
1344
  filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1308
- sort: data.sort ? buildSortFilter(data.sort) : void 0,
1345
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1309
1346
  page: data.pagination,
1310
1347
  columns: data.columns
1311
1348
  };
@@ -1449,8 +1486,8 @@ getCacheQuery_fn = async function(query) {
1449
1486
  if (!result)
1450
1487
  return null;
1451
1488
  const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1452
- if (!ttl || ttl < 0)
1453
- return result;
1489
+ if (ttl < 0)
1490
+ return null;
1454
1491
  const hasExpired = result.date.getTime() + ttl < Date.now();
1455
1492
  return hasExpired ? null : result;
1456
1493
  };
@@ -1495,7 +1532,7 @@ const initObject = (db, schema, table, object) => {
1495
1532
  const linkTable = column.link?.table;
1496
1533
  if (!linkTable) {
1497
1534
  console.error(`Failed to parse link for field ${column.name}`);
1498
- } else if (value && isObject(value)) {
1535
+ } else if (isObject(value)) {
1499
1536
  result[column.name] = initObject(db, schema, linkTable, value);
1500
1537
  }
1501
1538
  break;
@@ -1621,7 +1658,7 @@ class SchemaPlugin extends XataPlugin {
1621
1658
  get: (_target, table) => {
1622
1659
  if (!isString(table))
1623
1660
  throw new Error("Invalid table name");
1624
- if (!__privateGet$2(this, _tables)[table]) {
1661
+ if (__privateGet$2(this, _tables)[table] === void 0) {
1625
1662
  __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table });
1626
1663
  }
1627
1664
  return __privateGet$2(this, _tables)[table];
@@ -1724,30 +1761,39 @@ const envBranchNames = [
1724
1761
  "CF_PAGES_BRANCH",
1725
1762
  "BRANCH"
1726
1763
  ];
1727
- const defaultBranch = "main";
1728
1764
  async function getCurrentBranchName(options) {
1729
- const env = await getBranchByEnvVariable();
1730
- if (env)
1731
- return env;
1732
- const branch = await getGitBranch();
1733
- if (!branch)
1734
- return defaultBranch;
1735
- const details = await getDatabaseBranch(branch, options);
1736
- if (details)
1737
- return branch;
1738
- return defaultBranch;
1765
+ const env = getBranchByEnvVariable();
1766
+ if (env) {
1767
+ const details = await getDatabaseBranch(env, options);
1768
+ if (details)
1769
+ return env;
1770
+ console.warn(`Branch ${env} not found in Xata. Ignoring...`);
1771
+ }
1772
+ const gitBranch = await getGitBranch();
1773
+ return resolveXataBranch(gitBranch, options);
1739
1774
  }
1740
1775
  async function getCurrentBranchDetails(options) {
1741
- const env = await getBranchByEnvVariable();
1742
- if (env)
1743
- return getDatabaseBranch(env, options);
1744
- const branch = await getGitBranch();
1745
- if (!branch)
1746
- return getDatabaseBranch(defaultBranch, options);
1747
- const details = await getDatabaseBranch(branch, options);
1748
- if (details)
1749
- return details;
1750
- return getDatabaseBranch(defaultBranch, options);
1776
+ const branch = await getCurrentBranchName(options);
1777
+ return getDatabaseBranch(branch, options);
1778
+ }
1779
+ async function resolveXataBranch(gitBranch, options) {
1780
+ const databaseURL = options?.databaseURL || getDatabaseURL();
1781
+ const apiKey = options?.apiKey || getAPIKey();
1782
+ if (!databaseURL)
1783
+ throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
1784
+ if (!apiKey)
1785
+ throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
1786
+ const [protocol, , host, , dbName] = databaseURL.split("/");
1787
+ const [workspace] = host.split(".");
1788
+ const { branch } = await resolveBranch({
1789
+ apiKey,
1790
+ apiUrl: databaseURL,
1791
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
1792
+ workspacesApiUrl: `${protocol}//${host}`,
1793
+ pathParams: { dbName, workspace },
1794
+ queryParams: { gitBranch, fallbackBranch: getEnvVariable("XATA_FALLBACK_BRANCH") }
1795
+ });
1796
+ return branch;
1751
1797
  }
1752
1798
  async function getDatabaseBranch(branch, options) {
1753
1799
  const databaseURL = options?.databaseURL || getDatabaseURL();
@@ -1836,7 +1882,7 @@ const buildClient = (plugins) => {
1836
1882
  this.db = db;
1837
1883
  this.search = search;
1838
1884
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
1839
- if (!namespace)
1885
+ if (namespace === void 0)
1840
1886
  continue;
1841
1887
  const result = namespace.build(pluginOptions);
1842
1888
  if (result instanceof Promise) {
@@ -1853,7 +1899,7 @@ const buildClient = (plugins) => {
1853
1899
  const databaseURL = options?.databaseURL || getDatabaseURL();
1854
1900
  const apiKey = options?.apiKey || getAPIKey();
1855
1901
  const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
1856
- const branch = async () => options?.branch ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1902
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1857
1903
  if (!databaseURL || !apiKey) {
1858
1904
  throw new Error("Options databaseURL and apiKey are required");
1859
1905
  }
@@ -1880,7 +1926,7 @@ const buildClient = (plugins) => {
1880
1926
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1881
1927
  if (__privateGet(this, _branch))
1882
1928
  return __privateGet(this, _branch);
1883
- if (!param)
1929
+ if (param === void 0)
1884
1930
  return void 0;
1885
1931
  const strategies = Array.isArray(param) ? [...param] : [param];
1886
1932
  const evaluateBranch = async (strategy) => {
@@ -1905,5 +1951,5 @@ class XataError extends Error {
1905
1951
  }
1906
1952
  }
1907
1953
 
1908
- export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, Repository, RestRepository, SchemaPlugin, SearchPlugin, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, buildClient, bulkInsertTableRecords, cancelWorkspaceMemberInvite, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, endsWith, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseURL, getGitBranchesMapping, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isIdentifiable, isNot, isXataRecord, le, lt, lte, notExists, operationsByTag, pattern, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberRole, upsertRecordWithID };
1954
+ export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, Repository, RestRepository, SchemaPlugin, SearchPlugin, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, buildClient, bulkInsertTableRecords, cancelWorkspaceMemberInvite, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, endsWith, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseURL, getGitBranchesMapping, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isIdentifiable, isNot, isXataRecord, le, lt, lte, notExists, operationsByTag, pattern, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberRole, upsertRecordWithID };
1909
1955
  //# sourceMappingURL=index.mjs.map