@xata.io/client 0.0.0-alpha.vf4b92f1 → 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
  }
@@ -7,43 +31,101 @@ function compact(arr) {
7
31
  function isObject(value) {
8
32
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
9
33
  }
34
+ function isDefined(value) {
35
+ return value !== null && value !== void 0;
36
+ }
10
37
  function isString(value) {
11
- return value !== void 0 && value !== null && typeof value === "string";
38
+ return isDefined(value) && typeof value === "string";
39
+ }
40
+ function isStringArray(value) {
41
+ return isDefined(value) && Array.isArray(value) && value.every(isString);
12
42
  }
13
43
  function toBase64(value) {
14
44
  try {
15
45
  return btoa(value);
16
46
  } catch (err) {
17
- return Buffer.from(value).toString("base64");
47
+ const buf = Buffer;
48
+ return buf.from(value).toString("base64");
18
49
  }
19
50
  }
20
51
 
21
- function getEnvVariable(name) {
52
+ function getEnvironment() {
22
53
  try {
23
- if (isObject(process) && isString(process?.env?.[name])) {
24
- return process.env[name];
54
+ if (isObject(process) && isObject(process.env)) {
55
+ return {
56
+ apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
57
+ databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
58
+ branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
59
+ envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
60
+ fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
61
+ };
25
62
  }
26
63
  } catch (err) {
27
64
  }
28
65
  try {
29
- if (isObject(Deno) && isString(Deno?.env?.get(name))) {
30
- return Deno.env.get(name);
66
+ if (isObject(Deno) && isObject(Deno.env)) {
67
+ return {
68
+ apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
69
+ databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
70
+ branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
71
+ envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
72
+ fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
73
+ };
31
74
  }
32
75
  } catch (err) {
33
76
  }
77
+ return {
78
+ apiKey: getGlobalApiKey(),
79
+ databaseURL: getGlobalDatabaseURL(),
80
+ branch: getGlobalBranch(),
81
+ envBranch: void 0,
82
+ fallbackBranch: getGlobalFallbackBranch()
83
+ };
84
+ }
85
+ function getGlobalApiKey() {
86
+ try {
87
+ return XATA_API_KEY;
88
+ } catch (err) {
89
+ return void 0;
90
+ }
91
+ }
92
+ function getGlobalDatabaseURL() {
93
+ try {
94
+ return XATA_DATABASE_URL;
95
+ } catch (err) {
96
+ return void 0;
97
+ }
98
+ }
99
+ function getGlobalBranch() {
100
+ try {
101
+ return XATA_BRANCH;
102
+ } catch (err) {
103
+ return void 0;
104
+ }
105
+ }
106
+ function getGlobalFallbackBranch() {
107
+ try {
108
+ return XATA_FALLBACK_BRANCH;
109
+ } catch (err) {
110
+ return void 0;
111
+ }
34
112
  }
35
113
  async function getGitBranch() {
114
+ const cmd = ["git", "branch", "--show-current"];
115
+ const fullCmd = cmd.join(" ");
116
+ const nodeModule = ["child", "process"].join("_");
117
+ const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
36
118
  try {
37
- return require("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
119
+ if (typeof require === "function") {
120
+ return require(nodeModule).execSync(fullCmd, execOptions).trim();
121
+ }
122
+ const { execSync } = await import(nodeModule);
123
+ return execSync(fullCmd, execOptions).toString().trim();
38
124
  } catch (err) {
39
125
  }
40
126
  try {
41
127
  if (isObject(Deno)) {
42
- const process2 = Deno.run({
43
- cmd: ["git", "branch", "--show-current"],
44
- stdout: "piped",
45
- stderr: "piped"
46
- });
128
+ const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
47
129
  return new TextDecoder().decode(await process2.output()).trim();
48
130
  }
49
131
  } catch (err) {
@@ -52,7 +134,8 @@ async function getGitBranch() {
52
134
 
53
135
  function getAPIKey() {
54
136
  try {
55
- return getEnvVariable("XATA_API_KEY") ?? XATA_API_KEY;
137
+ const { apiKey } = getEnvironment();
138
+ return apiKey;
56
139
  } catch (err) {
57
140
  return void 0;
58
141
  }
@@ -62,21 +145,35 @@ function getFetchImplementation(userFetch) {
62
145
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
63
146
  const fetchImpl = userFetch ?? globalFetch;
64
147
  if (!fetchImpl) {
65
- 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
+ );
66
151
  }
67
152
  return fetchImpl;
68
153
  }
69
154
 
70
- class FetcherError extends Error {
71
- constructor(status, data) {
155
+ const VERSION = "0.0.0-alpha.vf5ce72f";
156
+
157
+ class ErrorWithCause extends Error {
158
+ constructor(message, options) {
159
+ super(message, options);
160
+ }
161
+ }
162
+ class FetcherError extends ErrorWithCause {
163
+ constructor(status, data, requestId) {
72
164
  super(getMessage(data));
73
165
  this.status = status;
74
166
  this.errors = isBulkError(data) ? data.errors : void 0;
167
+ this.requestId = requestId;
75
168
  if (data instanceof Error) {
76
169
  this.stack = data.stack;
77
170
  this.cause = data.cause;
78
171
  }
79
172
  }
173
+ toString() {
174
+ const error = super.toString();
175
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
176
+ }
80
177
  }
81
178
  function isBulkError(error) {
82
179
  return isObject(error) && Array.isArray(error.errors);
@@ -99,7 +196,12 @@ function getMessage(data) {
99
196
  }
100
197
 
101
198
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
102
- const query = new URLSearchParams(queryParams).toString();
199
+ const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
200
+ if (value === void 0 || value === null)
201
+ return acc;
202
+ return { ...acc, [key]: value };
203
+ }, {});
204
+ const query = new URLSearchParams(cleanQueryParams).toString();
103
205
  const queryString = query.length > 0 ? `?${query}` : "";
104
206
  return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
105
207
  };
@@ -129,32 +231,62 @@ async function fetch$1({
129
231
  fetchImpl,
130
232
  apiKey,
131
233
  apiUrl,
132
- workspacesApiUrl
234
+ workspacesApiUrl,
235
+ trace
133
236
  }) {
134
- const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
135
- const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
136
- const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
137
- const response = await fetchImpl(url, {
138
- method: method.toUpperCase(),
139
- body: body ? JSON.stringify(body) : void 0,
140
- headers: {
141
- "Content-Type": "application/json",
142
- ...headers,
143
- ...hostHeader(fullUrl),
144
- Authorization: `Bearer ${apiKey}`
145
- }
146
- });
147
- if (response.status === 204) {
148
- return {};
149
- }
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) {
150
285
  try {
151
- const jsonResponse = await response.json();
152
- if (response.ok) {
153
- return jsonResponse;
154
- }
155
- throw new FetcherError(response.status, jsonResponse);
286
+ const { host, protocol } = new URL(url);
287
+ return { host, protocol };
156
288
  } catch (error) {
157
- throw new FetcherError(response.status, error);
289
+ return {};
158
290
  }
159
291
  }
160
292
 
@@ -213,6 +345,7 @@ const removeWorkspaceMember = (variables) => fetch$1({
213
345
  ...variables
214
346
  });
215
347
  const inviteWorkspaceMember = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables });
348
+ const updateWorkspaceMemberInvite = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables });
216
349
  const cancelWorkspaceMemberInvite = (variables) => fetch$1({
217
350
  url: "/workspaces/{workspaceId}/invites/{inviteId}",
218
351
  method: "delete",
@@ -248,16 +381,25 @@ const deleteDatabase = (variables) => fetch$1({
248
381
  method: "delete",
249
382
  ...variables
250
383
  });
251
- const getBranchDetails = (variables) => fetch$1({
252
- url: "/db/{dbBranchName}",
384
+ const getDatabaseMetadata = (variables) => fetch$1({
385
+ url: "/dbs/{dbName}/metadata",
386
+ method: "get",
387
+ ...variables
388
+ });
389
+ const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
390
+ const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
391
+ const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
392
+ const resolveBranch = (variables) => fetch$1({
393
+ url: "/dbs/{dbName}/resolveBranch",
253
394
  method: "get",
254
395
  ...variables
255
396
  });
256
- const createBranch = (variables) => fetch$1({
397
+ const getBranchDetails = (variables) => fetch$1({
257
398
  url: "/db/{dbBranchName}",
258
- method: "put",
399
+ method: "get",
259
400
  ...variables
260
401
  });
402
+ const createBranch = (variables) => fetch$1({ url: "/db/{dbBranchName}", method: "put", ...variables });
261
403
  const deleteBranch = (variables) => fetch$1({
262
404
  url: "/db/{dbBranchName}",
263
405
  method: "delete",
@@ -331,11 +473,7 @@ const updateColumn = (variables) => fetch$1({
331
473
  method: "patch",
332
474
  ...variables
333
475
  });
334
- const insertRecord = (variables) => fetch$1({
335
- url: "/db/{dbBranchName}/tables/{tableName}/data",
336
- method: "post",
337
- ...variables
338
- });
476
+ const insertRecord = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables });
339
477
  const insertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables });
340
478
  const updateRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables });
341
479
  const upsertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables });
@@ -355,6 +493,11 @@ const queryTable = (variables) => fetch$1({
355
493
  method: "post",
356
494
  ...variables
357
495
  });
496
+ const searchTable = (variables) => fetch$1({
497
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
498
+ method: "post",
499
+ ...variables
500
+ });
358
501
  const searchBranch = (variables) => fetch$1({
359
502
  url: "/db/{dbBranchName}/search",
360
503
  method: "post",
@@ -372,11 +515,21 @@ const operationsByTag = {
372
515
  updateWorkspaceMemberRole,
373
516
  removeWorkspaceMember,
374
517
  inviteWorkspaceMember,
518
+ updateWorkspaceMemberInvite,
375
519
  cancelWorkspaceMemberInvite,
376
520
  resendWorkspaceMemberInvite,
377
521
  acceptWorkspaceMemberInvite
378
522
  },
379
- database: { getDatabaseList, createDatabase, deleteDatabase },
523
+ database: {
524
+ getDatabaseList,
525
+ createDatabase,
526
+ deleteDatabase,
527
+ getDatabaseMetadata,
528
+ getGitBranchesMapping,
529
+ addGitBranchesEntry,
530
+ removeGitBranchesEntry,
531
+ resolveBranch
532
+ },
380
533
  branch: {
381
534
  getBranchList,
382
535
  getBranchDetails,
@@ -410,6 +563,7 @@ const operationsByTag = {
410
563
  getRecord,
411
564
  bulkInsertTableRecords,
412
565
  queryTable,
566
+ searchTable,
413
567
  searchBranch
414
568
  }
415
569
  };
@@ -443,7 +597,7 @@ var __accessCheck$7 = (obj, member, msg) => {
443
597
  if (!member.has(obj))
444
598
  throw TypeError("Cannot " + msg);
445
599
  };
446
- var __privateGet$6 = (obj, member, getter) => {
600
+ var __privateGet$7 = (obj, member, getter) => {
447
601
  __accessCheck$7(obj, member, "read from private field");
448
602
  return getter ? getter.call(obj) : member.get(obj);
449
603
  };
@@ -452,7 +606,7 @@ var __privateAdd$7 = (obj, member, value) => {
452
606
  throw TypeError("Cannot add the same private member more than once");
453
607
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
454
608
  };
455
- var __privateSet$5 = (obj, member, value, setter) => {
609
+ var __privateSet$7 = (obj, member, value, setter) => {
456
610
  __accessCheck$7(obj, member, "write to private field");
457
611
  setter ? setter.call(obj, value) : member.set(obj, value);
458
612
  return value;
@@ -463,46 +617,48 @@ class XataApiClient {
463
617
  __privateAdd$7(this, _extraProps, void 0);
464
618
  __privateAdd$7(this, _namespaces, {});
465
619
  const provider = options.host ?? "production";
466
- const apiKey = options?.apiKey ?? getAPIKey();
620
+ const apiKey = options.apiKey ?? getAPIKey();
621
+ const trace = options.trace ?? defaultTrace;
467
622
  if (!apiKey) {
468
623
  throw new Error("Could not resolve a valid apiKey");
469
624
  }
470
- __privateSet$5(this, _extraProps, {
625
+ __privateSet$7(this, _extraProps, {
471
626
  apiUrl: getHostUrl(provider, "main"),
472
627
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
473
628
  fetchImpl: getFetchImplementation(options.fetch),
474
- apiKey
629
+ apiKey,
630
+ trace
475
631
  });
476
632
  }
477
633
  get user() {
478
- if (!__privateGet$6(this, _namespaces).user)
479
- __privateGet$6(this, _namespaces).user = new UserApi(__privateGet$6(this, _extraProps));
480
- return __privateGet$6(this, _namespaces).user;
634
+ if (!__privateGet$7(this, _namespaces).user)
635
+ __privateGet$7(this, _namespaces).user = new UserApi(__privateGet$7(this, _extraProps));
636
+ return __privateGet$7(this, _namespaces).user;
481
637
  }
482
638
  get workspaces() {
483
- if (!__privateGet$6(this, _namespaces).workspaces)
484
- __privateGet$6(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$6(this, _extraProps));
485
- return __privateGet$6(this, _namespaces).workspaces;
639
+ if (!__privateGet$7(this, _namespaces).workspaces)
640
+ __privateGet$7(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$7(this, _extraProps));
641
+ return __privateGet$7(this, _namespaces).workspaces;
486
642
  }
487
643
  get databases() {
488
- if (!__privateGet$6(this, _namespaces).databases)
489
- __privateGet$6(this, _namespaces).databases = new DatabaseApi(__privateGet$6(this, _extraProps));
490
- return __privateGet$6(this, _namespaces).databases;
644
+ if (!__privateGet$7(this, _namespaces).databases)
645
+ __privateGet$7(this, _namespaces).databases = new DatabaseApi(__privateGet$7(this, _extraProps));
646
+ return __privateGet$7(this, _namespaces).databases;
491
647
  }
492
648
  get branches() {
493
- if (!__privateGet$6(this, _namespaces).branches)
494
- __privateGet$6(this, _namespaces).branches = new BranchApi(__privateGet$6(this, _extraProps));
495
- return __privateGet$6(this, _namespaces).branches;
649
+ if (!__privateGet$7(this, _namespaces).branches)
650
+ __privateGet$7(this, _namespaces).branches = new BranchApi(__privateGet$7(this, _extraProps));
651
+ return __privateGet$7(this, _namespaces).branches;
496
652
  }
497
653
  get tables() {
498
- if (!__privateGet$6(this, _namespaces).tables)
499
- __privateGet$6(this, _namespaces).tables = new TableApi(__privateGet$6(this, _extraProps));
500
- return __privateGet$6(this, _namespaces).tables;
654
+ if (!__privateGet$7(this, _namespaces).tables)
655
+ __privateGet$7(this, _namespaces).tables = new TableApi(__privateGet$7(this, _extraProps));
656
+ return __privateGet$7(this, _namespaces).tables;
501
657
  }
502
658
  get records() {
503
- if (!__privateGet$6(this, _namespaces).records)
504
- __privateGet$6(this, _namespaces).records = new RecordsApi(__privateGet$6(this, _extraProps));
505
- return __privateGet$6(this, _namespaces).records;
659
+ if (!__privateGet$7(this, _namespaces).records)
660
+ __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
661
+ return __privateGet$7(this, _namespaces).records;
506
662
  }
507
663
  }
508
664
  _extraProps = new WeakMap();
@@ -594,6 +750,13 @@ class WorkspaceApi {
594
750
  ...this.extraProps
595
751
  });
596
752
  }
753
+ updateWorkspaceMemberInvite(workspaceId, inviteId, role) {
754
+ return operationsByTag.workspaces.updateWorkspaceMemberInvite({
755
+ pathParams: { workspaceId, inviteId },
756
+ body: { role },
757
+ ...this.extraProps
758
+ });
759
+ }
597
760
  cancelWorkspaceMemberInvite(workspaceId, inviteId) {
598
761
  return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
599
762
  pathParams: { workspaceId, inviteId },
@@ -636,6 +799,39 @@ class DatabaseApi {
636
799
  ...this.extraProps
637
800
  });
638
801
  }
802
+ getDatabaseMetadata(workspace, dbName) {
803
+ return operationsByTag.database.getDatabaseMetadata({
804
+ pathParams: { workspace, dbName },
805
+ ...this.extraProps
806
+ });
807
+ }
808
+ getGitBranchesMapping(workspace, dbName) {
809
+ return operationsByTag.database.getGitBranchesMapping({
810
+ pathParams: { workspace, dbName },
811
+ ...this.extraProps
812
+ });
813
+ }
814
+ addGitBranchesEntry(workspace, dbName, body) {
815
+ return operationsByTag.database.addGitBranchesEntry({
816
+ pathParams: { workspace, dbName },
817
+ body,
818
+ ...this.extraProps
819
+ });
820
+ }
821
+ removeGitBranchesEntry(workspace, dbName, gitBranch) {
822
+ return operationsByTag.database.removeGitBranchesEntry({
823
+ pathParams: { workspace, dbName },
824
+ queryParams: { gitBranch },
825
+ ...this.extraProps
826
+ });
827
+ }
828
+ resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
829
+ return operationsByTag.database.resolveBranch({
830
+ pathParams: { workspace, dbName },
831
+ queryParams: { gitBranch, fallbackBranch },
832
+ ...this.extraProps
833
+ });
834
+ }
639
835
  }
640
836
  class BranchApi {
641
837
  constructor(extraProps) {
@@ -653,10 +849,10 @@ class BranchApi {
653
849
  ...this.extraProps
654
850
  });
655
851
  }
656
- createBranch(workspace, database, branch, from = "", options = {}) {
852
+ createBranch(workspace, database, branch, from, options = {}) {
657
853
  return operationsByTag.branch.createBranch({
658
854
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
659
- queryParams: { from },
855
+ queryParams: isString(from) ? { from } : void 0,
660
856
  body: options,
661
857
  ...this.extraProps
662
858
  });
@@ -781,9 +977,10 @@ class RecordsApi {
781
977
  constructor(extraProps) {
782
978
  this.extraProps = extraProps;
783
979
  }
784
- insertRecord(workspace, database, branch, tableName, record) {
980
+ insertRecord(workspace, database, branch, tableName, record, options = {}) {
785
981
  return operationsByTag.records.insertRecord({
786
982
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
983
+ queryParams: options,
787
984
  body: record,
788
985
  ...this.extraProps
789
986
  });
@@ -812,21 +1009,24 @@ class RecordsApi {
812
1009
  ...this.extraProps
813
1010
  });
814
1011
  }
815
- deleteRecord(workspace, database, branch, tableName, recordId) {
1012
+ deleteRecord(workspace, database, branch, tableName, recordId, options = {}) {
816
1013
  return operationsByTag.records.deleteRecord({
817
1014
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1015
+ queryParams: options,
818
1016
  ...this.extraProps
819
1017
  });
820
1018
  }
821
1019
  getRecord(workspace, database, branch, tableName, recordId, options = {}) {
822
1020
  return operationsByTag.records.getRecord({
823
1021
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1022
+ queryParams: options,
824
1023
  ...this.extraProps
825
1024
  });
826
1025
  }
827
- bulkInsertTableRecords(workspace, database, branch, tableName, records) {
1026
+ bulkInsertTableRecords(workspace, database, branch, tableName, records, options = {}) {
828
1027
  return operationsByTag.records.bulkInsertTableRecords({
829
1028
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1029
+ queryParams: options,
830
1030
  body: { records },
831
1031
  ...this.extraProps
832
1032
  });
@@ -838,6 +1038,13 @@ class RecordsApi {
838
1038
  ...this.extraProps
839
1039
  });
840
1040
  }
1041
+ searchTable(workspace, database, branch, tableName, query) {
1042
+ return operationsByTag.records.searchTable({
1043
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1044
+ body: query,
1045
+ ...this.extraProps
1046
+ });
1047
+ }
841
1048
  searchBranch(workspace, database, branch, query) {
842
1049
  return operationsByTag.records.searchBranch({
843
1050
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -861,7 +1068,7 @@ var __accessCheck$6 = (obj, member, msg) => {
861
1068
  if (!member.has(obj))
862
1069
  throw TypeError("Cannot " + msg);
863
1070
  };
864
- var __privateGet$5 = (obj, member, getter) => {
1071
+ var __privateGet$6 = (obj, member, getter) => {
865
1072
  __accessCheck$6(obj, member, "read from private field");
866
1073
  return getter ? getter.call(obj) : member.get(obj);
867
1074
  };
@@ -870,30 +1077,30 @@ var __privateAdd$6 = (obj, member, value) => {
870
1077
  throw TypeError("Cannot add the same private member more than once");
871
1078
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
872
1079
  };
873
- var __privateSet$4 = (obj, member, value, setter) => {
1080
+ var __privateSet$6 = (obj, member, value, setter) => {
874
1081
  __accessCheck$6(obj, member, "write to private field");
875
1082
  setter ? setter.call(obj, value) : member.set(obj, value);
876
1083
  return value;
877
1084
  };
878
- var _query;
1085
+ var _query, _page;
879
1086
  class Page {
880
1087
  constructor(query, meta, records = []) {
881
1088
  __privateAdd$6(this, _query, void 0);
882
- __privateSet$4(this, _query, query);
1089
+ __privateSet$6(this, _query, query);
883
1090
  this.meta = meta;
884
- this.records = records;
1091
+ this.records = new RecordArray(this, records);
885
1092
  }
886
1093
  async nextPage(size, offset) {
887
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, after: this.meta.page.cursor } });
1094
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
888
1095
  }
889
1096
  async previousPage(size, offset) {
890
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, before: this.meta.page.cursor } });
1097
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
891
1098
  }
892
1099
  async firstPage(size, offset) {
893
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, first: this.meta.page.cursor } });
1100
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
894
1101
  }
895
1102
  async lastPage(size, offset) {
896
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, last: this.meta.page.cursor } });
1103
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
897
1104
  }
898
1105
  hasNextPage() {
899
1106
  return this.meta.page.more;
@@ -901,15 +1108,62 @@ class Page {
901
1108
  }
902
1109
  _query = new WeakMap();
903
1110
  const PAGINATION_MAX_SIZE = 200;
904
- const PAGINATION_DEFAULT_SIZE = 200;
1111
+ const PAGINATION_DEFAULT_SIZE = 20;
905
1112
  const PAGINATION_MAX_OFFSET = 800;
906
1113
  const PAGINATION_DEFAULT_OFFSET = 0;
1114
+ function isCursorPaginationOptions(options) {
1115
+ return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
1116
+ }
1117
+ const _RecordArray = class extends Array {
1118
+ constructor(...args) {
1119
+ super(..._RecordArray.parseConstructorParams(...args));
1120
+ __privateAdd$6(this, _page, void 0);
1121
+ __privateSet$6(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
1122
+ }
1123
+ static parseConstructorParams(...args) {
1124
+ if (args.length === 1 && typeof args[0] === "number") {
1125
+ return new Array(args[0]);
1126
+ }
1127
+ if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
1128
+ const result = args[1] ?? args[0].records ?? [];
1129
+ return new Array(...result);
1130
+ }
1131
+ return new Array(...args);
1132
+ }
1133
+ toArray() {
1134
+ return new Array(...this);
1135
+ }
1136
+ map(callbackfn, thisArg) {
1137
+ return this.toArray().map(callbackfn, thisArg);
1138
+ }
1139
+ async nextPage(size, offset) {
1140
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1141
+ return new _RecordArray(newPage);
1142
+ }
1143
+ async previousPage(size, offset) {
1144
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1145
+ return new _RecordArray(newPage);
1146
+ }
1147
+ async firstPage(size, offset) {
1148
+ const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1149
+ return new _RecordArray(newPage);
1150
+ }
1151
+ async lastPage(size, offset) {
1152
+ const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1153
+ return new _RecordArray(newPage);
1154
+ }
1155
+ hasNextPage() {
1156
+ return __privateGet$6(this, _page).meta.page.more;
1157
+ }
1158
+ };
1159
+ let RecordArray = _RecordArray;
1160
+ _page = new WeakMap();
907
1161
 
908
1162
  var __accessCheck$5 = (obj, member, msg) => {
909
1163
  if (!member.has(obj))
910
1164
  throw TypeError("Cannot " + msg);
911
1165
  };
912
- var __privateGet$4 = (obj, member, getter) => {
1166
+ var __privateGet$5 = (obj, member, getter) => {
913
1167
  __accessCheck$5(obj, member, "read from private field");
914
1168
  return getter ? getter.call(obj) : member.get(obj);
915
1169
  };
@@ -918,34 +1172,35 @@ var __privateAdd$5 = (obj, member, value) => {
918
1172
  throw TypeError("Cannot add the same private member more than once");
919
1173
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
920
1174
  };
921
- var __privateSet$3 = (obj, member, value, setter) => {
1175
+ var __privateSet$5 = (obj, member, value, setter) => {
922
1176
  __accessCheck$5(obj, member, "write to private field");
923
1177
  setter ? setter.call(obj, value) : member.set(obj, value);
924
1178
  return value;
925
1179
  };
926
1180
  var _table$1, _repository, _data;
927
1181
  const _Query = class {
928
- constructor(repository, table, data, parent) {
1182
+ constructor(repository, table, data, rawParent) {
929
1183
  __privateAdd$5(this, _table$1, void 0);
930
1184
  __privateAdd$5(this, _repository, void 0);
931
1185
  __privateAdd$5(this, _data, { filter: {} });
932
1186
  this.meta = { page: { cursor: "start", more: true } };
933
- this.records = [];
934
- __privateSet$3(this, _table$1, table);
1187
+ this.records = new RecordArray(this, []);
1188
+ __privateSet$5(this, _table$1, table);
935
1189
  if (repository) {
936
- __privateSet$3(this, _repository, repository);
1190
+ __privateSet$5(this, _repository, repository);
937
1191
  } else {
938
- __privateSet$3(this, _repository, this);
1192
+ __privateSet$5(this, _repository, this);
939
1193
  }
940
- __privateGet$4(this, _data).filter = data.filter ?? parent?.filter ?? {};
941
- __privateGet$4(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
942
- __privateGet$4(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
943
- __privateGet$4(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
944
- __privateGet$4(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
945
- __privateGet$4(this, _data).sort = data.sort ?? parent?.sort;
946
- __privateGet$4(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
947
- __privateGet$4(this, _data).page = data.page ?? parent?.page;
948
- __privateGet$4(this, _data).cache = data.cache ?? parent?.cache;
1194
+ const parent = cleanParent(data, rawParent);
1195
+ __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
1196
+ __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
1197
+ __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
1198
+ __privateGet$5(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
1199
+ __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1200
+ __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1201
+ __privateGet$5(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
1202
+ __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1203
+ __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
949
1204
  this.any = this.any.bind(this);
950
1205
  this.all = this.all.bind(this);
951
1206
  this.not = this.not.bind(this);
@@ -956,83 +1211,93 @@ const _Query = class {
956
1211
  Object.defineProperty(this, "repository", { enumerable: false });
957
1212
  }
958
1213
  getQueryOptions() {
959
- return __privateGet$4(this, _data);
1214
+ return __privateGet$5(this, _data);
960
1215
  }
961
1216
  key() {
962
- const { columns = [], filter = {}, sort = [], page = {} } = __privateGet$4(this, _data);
963
- const key = JSON.stringify({ columns, filter, sort, page });
1217
+ const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$5(this, _data);
1218
+ const key = JSON.stringify({ columns, filter, sort, pagination });
964
1219
  return toBase64(key);
965
1220
  }
966
1221
  any(...queries) {
967
1222
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
968
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $any } }, __privateGet$4(this, _data));
1223
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
969
1224
  }
970
1225
  all(...queries) {
971
1226
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
972
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1227
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
973
1228
  }
974
1229
  not(...queries) {
975
1230
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
976
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $not } }, __privateGet$4(this, _data));
1231
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
977
1232
  }
978
1233
  none(...queries) {
979
1234
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
980
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $none } }, __privateGet$4(this, _data));
1235
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
981
1236
  }
982
1237
  filter(a, b) {
983
1238
  if (arguments.length === 1) {
984
1239
  const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
985
- const $all = compact([__privateGet$4(this, _data).filter?.$all].flat().concat(constraints));
986
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1240
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1241
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
987
1242
  } else {
988
- const $all = compact([__privateGet$4(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
989
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1243
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
1244
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
990
1245
  }
991
1246
  }
992
- sort(column, direction) {
993
- const originalSort = [__privateGet$4(this, _data).sort ?? []].flat();
1247
+ sort(column, direction = "asc") {
1248
+ const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
994
1249
  const sort = [...originalSort, { column, direction }];
995
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { sort }, __privateGet$4(this, _data));
1250
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
996
1251
  }
997
1252
  select(columns) {
998
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { columns }, __privateGet$4(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
+ );
999
1259
  }
1000
1260
  getPaginated(options = {}) {
1001
- const query = new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), options, __privateGet$4(this, _data));
1002
- return __privateGet$4(this, _repository).query(query);
1261
+ const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
1262
+ return __privateGet$5(this, _repository).query(query);
1003
1263
  }
1004
1264
  async *[Symbol.asyncIterator]() {
1005
- for await (const [record] of this.getIterator(1)) {
1265
+ for await (const [record] of this.getIterator({ batchSize: 1 })) {
1006
1266
  yield record;
1007
1267
  }
1008
1268
  }
1009
- async *getIterator(chunk, options = {}) {
1010
- let offset = 0;
1011
- let end = false;
1012
- while (!end) {
1013
- const { records, meta } = await this.getPaginated({ ...options, page: { size: chunk, offset } });
1014
- yield records;
1015
- offset += chunk;
1016
- end = !meta.page.more;
1269
+ async *getIterator(options = {}) {
1270
+ const { batchSize = 1 } = options;
1271
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
1272
+ let more = page.hasNextPage();
1273
+ yield page.records;
1274
+ while (more) {
1275
+ page = await page.nextPage();
1276
+ more = page.hasNextPage();
1277
+ yield page.records;
1017
1278
  }
1018
1279
  }
1019
1280
  async getMany(options = {}) {
1020
- const { records } = await this.getPaginated(options);
1021
- return records;
1281
+ const page = await this.getPaginated(options);
1282
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1283
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1284
+ }
1285
+ return page.records;
1022
1286
  }
1023
- async getAll(chunk = PAGINATION_MAX_SIZE, options = {}) {
1287
+ async getAll(options = {}) {
1288
+ const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
1024
1289
  const results = [];
1025
- for await (const page of this.getIterator(chunk, options)) {
1290
+ for await (const page of this.getIterator({ ...rest, batchSize })) {
1026
1291
  results.push(...page);
1027
1292
  }
1028
1293
  return results;
1029
1294
  }
1030
1295
  async getFirst(options = {}) {
1031
- const records = await this.getMany({ ...options, page: { size: 1 } });
1032
- return records[0] || null;
1296
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1297
+ return records[0] ?? null;
1033
1298
  }
1034
1299
  cache(ttl) {
1035
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { cache: ttl }, __privateGet$4(this, _data));
1300
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1036
1301
  }
1037
1302
  nextPage(size, offset) {
1038
1303
  return this.firstPage(size, offset);
@@ -1041,10 +1306,10 @@ const _Query = class {
1041
1306
  return this.firstPage(size, offset);
1042
1307
  }
1043
1308
  firstPage(size, offset) {
1044
- return this.getPaginated({ page: { size, offset } });
1309
+ return this.getPaginated({ pagination: { size, offset } });
1045
1310
  }
1046
1311
  lastPage(size, offset) {
1047
- return this.getPaginated({ page: { size, offset, before: "end" } });
1312
+ return this.getPaginated({ pagination: { size, offset, before: "end" } });
1048
1313
  }
1049
1314
  hasNextPage() {
1050
1315
  return this.meta.page.more;
@@ -1054,12 +1319,20 @@ let Query = _Query;
1054
1319
  _table$1 = new WeakMap();
1055
1320
  _repository = new WeakMap();
1056
1321
  _data = new WeakMap();
1322
+ function cleanParent(data, parent) {
1323
+ if (isCursorPaginationOptions(data.pagination)) {
1324
+ return { ...parent, sorting: void 0, filter: void 0 };
1325
+ }
1326
+ return parent;
1327
+ }
1057
1328
 
1058
1329
  function isIdentifiable(x) {
1059
1330
  return isObject(x) && isString(x?.id);
1060
1331
  }
1061
1332
  function isXataRecord(x) {
1062
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1333
+ const record = x;
1334
+ const metadata = record?.getMetadata();
1335
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1063
1336
  }
1064
1337
 
1065
1338
  function isSortFilterString(value) {
@@ -1089,7 +1362,7 @@ var __accessCheck$4 = (obj, member, msg) => {
1089
1362
  if (!member.has(obj))
1090
1363
  throw TypeError("Cannot " + msg);
1091
1364
  };
1092
- var __privateGet$3 = (obj, member, getter) => {
1365
+ var __privateGet$4 = (obj, member, getter) => {
1093
1366
  __accessCheck$4(obj, member, "read from private field");
1094
1367
  return getter ? getter.call(obj) : member.get(obj);
1095
1368
  };
@@ -1098,7 +1371,7 @@ var __privateAdd$4 = (obj, member, value) => {
1098
1371
  throw TypeError("Cannot add the same private member more than once");
1099
1372
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1100
1373
  };
1101
- var __privateSet$2 = (obj, member, value, setter) => {
1374
+ var __privateSet$4 = (obj, member, value, setter) => {
1102
1375
  __accessCheck$4(obj, member, "write to private field");
1103
1376
  setter ? setter.call(obj, value) : member.set(obj, value);
1104
1377
  return value;
@@ -1107,7 +1380,7 @@ var __privateMethod$2 = (obj, member, method) => {
1107
1380
  __accessCheck$4(obj, member, "access private method");
1108
1381
  return method;
1109
1382
  };
1110
- var _table, _links, _getFetchProps, _cache, _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;
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;
1111
1384
  class Repository extends Query {
1112
1385
  }
1113
1386
  class RestRepository extends Query {
@@ -1119,292 +1392,338 @@ class RestRepository extends Query {
1119
1392
  __privateAdd$4(this, _updateRecordWithID);
1120
1393
  __privateAdd$4(this, _upsertRecordWithID);
1121
1394
  __privateAdd$4(this, _deleteRecord);
1122
- __privateAdd$4(this, _invalidateCache);
1123
- __privateAdd$4(this, _setCacheRecord);
1124
- __privateAdd$4(this, _getCacheRecord);
1125
1395
  __privateAdd$4(this, _setCacheQuery);
1126
1396
  __privateAdd$4(this, _getCacheQuery);
1397
+ __privateAdd$4(this, _getSchemaTables$1);
1127
1398
  __privateAdd$4(this, _table, void 0);
1128
- __privateAdd$4(this, _links, void 0);
1129
1399
  __privateAdd$4(this, _getFetchProps, void 0);
1400
+ __privateAdd$4(this, _db, void 0);
1130
1401
  __privateAdd$4(this, _cache, void 0);
1131
- __privateSet$2(this, _table, options.table);
1132
- __privateSet$2(this, _links, options.links ?? {});
1133
- __privateSet$2(this, _getFetchProps, options.pluginOptions.getFetchProps);
1134
- this.db = options.db;
1135
- __privateSet$2(this, _cache, options.pluginOptions.cache);
1136
- }
1137
- async create(a, b) {
1138
- if (Array.isArray(a)) {
1139
- const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1140
- await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1141
- return records;
1142
- }
1143
- if (isString(a) && isObject(b)) {
1144
- if (a === "")
1145
- throw new Error("The id can't be empty");
1146
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1147
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1148
- return record;
1149
- }
1150
- if (isObject(a) && isString(a.id)) {
1151
- if (a.id === "")
1152
- throw new Error("The id can't be empty");
1153
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1154
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1155
- return record;
1156
- }
1157
- if (isObject(a)) {
1158
- const record = await __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1159
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1160
- return record;
1161
- }
1162
- throw new Error("Invalid arguments for create method");
1163
- }
1164
- async read(recordId) {
1165
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, recordId);
1166
- if (cacheRecord)
1167
- return cacheRecord;
1168
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1169
- try {
1170
- const response = await getRecord({
1171
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1172
- ...fetchProps
1402
+ __privateAdd$4(this, _schemaTables$2, void 0);
1403
+ __privateAdd$4(this, _trace, void 0);
1404
+ __privateSet$4(this, _table, options.table);
1405
+ __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1406
+ __privateSet$4(this, _db, options.db);
1407
+ __privateSet$4(this, _cache, options.pluginOptions.cache);
1408
+ __privateSet$4(this, _schemaTables$2, options.schemaTables);
1409
+ const trace = options.pluginOptions.trace ?? defaultTrace;
1410
+ __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
1411
+ return trace(name, fn, {
1412
+ ...options2,
1413
+ [TraceAttributes.TABLE]: __privateGet$4(this, _table),
1414
+ [TraceAttributes.VERSION]: VERSION
1173
1415
  });
1174
- return initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), response);
1175
- } catch (e) {
1176
- if (isObject(e) && e.status === 404) {
1177
- return null;
1416
+ });
1417
+ }
1418
+ async create(a, b, c) {
1419
+ return __privateGet$4(this, _trace).call(this, "create", async () => {
1420
+ if (Array.isArray(a)) {
1421
+ if (a.length === 0)
1422
+ return [];
1423
+ const columns = isStringArray(b) ? b : void 0;
1424
+ return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
1178
1425
  }
1179
- throw e;
1180
- }
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
+ });
1181
1444
  }
1182
- async update(a, b) {
1183
- if (Array.isArray(a)) {
1184
- if (a.length > 100) {
1185
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
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);
1186
1458
  }
1187
- return Promise.all(a.map((object) => this.update(object)));
1188
- }
1189
- if (isString(a) && isObject(b)) {
1190
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1191
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1192
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1193
- return record;
1194
- }
1195
- if (isObject(a) && isString(a.id)) {
1196
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1197
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1198
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1199
- return record;
1200
- }
1201
- throw new Error("Invalid arguments for update method");
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;
1480
+ }
1481
+ }
1482
+ return null;
1483
+ });
1202
1484
  }
1203
- async createOrUpdate(a, b) {
1204
- if (Array.isArray(a)) {
1205
- if (a.length > 100) {
1206
- 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)));
1207
1495
  }
1208
- return Promise.all(a.map((object) => this.createOrUpdate(object)));
1209
- }
1210
- if (isString(a) && isObject(b)) {
1211
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1212
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1213
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1214
- return record;
1215
- }
1216
- if (isObject(a) && isString(a.id)) {
1217
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1218
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1219
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1220
- return record;
1221
- }
1222
- throw new Error("Invalid arguments for createOrUpdate method");
1496
+ if (isString(a) && isObject(b)) {
1497
+ const columns = isStringArray(c) ? c : void 0;
1498
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns);
1499
+ }
1500
+ if (isObject(a) && isString(a.id)) {
1501
+ const columns = isStringArray(b) ? b : void 0;
1502
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1503
+ }
1504
+ throw new Error("Invalid arguments for update method");
1505
+ });
1223
1506
  }
1224
- async delete(a) {
1225
- if (Array.isArray(a)) {
1226
- if (a.length > 100) {
1227
- console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
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)));
1228
1517
  }
1229
- await Promise.all(a.map((id) => this.delete(id)));
1230
- return;
1231
- }
1232
- if (isString(a)) {
1233
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1234
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1235
- return;
1236
- }
1237
- if (isObject(a) && isString(a.id)) {
1238
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1239
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1240
- return;
1241
- }
1242
- throw new Error("Invalid arguments for delete method");
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
+ });
1243
1547
  }
1244
1548
  async search(query, options = {}) {
1245
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1246
- const { records } = await searchBranch({
1247
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1248
- body: { tables: [__privateGet$3(this, _table)], query, fuzziness: options.fuzziness },
1249
- ...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));
1250
1565
  });
1251
- return records.map((item) => initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), item));
1252
1566
  }
1253
1567
  async query(query) {
1254
- const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1255
- if (cacheQuery)
1256
- return new Page(query, cacheQuery.meta, cacheQuery.records);
1257
- const data = query.getQueryOptions();
1258
- const body = {
1259
- filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1260
- sort: data.sort ? buildSortFilter(data.sort) : void 0,
1261
- page: data.page,
1262
- columns: data.columns
1263
- };
1264
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1265
- const { meta, records: objects } = await queryTable({
1266
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table) },
1267
- body,
1268
- ...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);
1269
1589
  });
1270
- const records = objects.map((record) => initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), record));
1271
- await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1272
- return new Page(query, meta, records);
1273
1590
  }
1274
1591
  }
1275
1592
  _table = new WeakMap();
1276
- _links = new WeakMap();
1277
1593
  _getFetchProps = new WeakMap();
1594
+ _db = new WeakMap();
1278
1595
  _cache = new WeakMap();
1596
+ _schemaTables$2 = new WeakMap();
1597
+ _trace = new WeakMap();
1279
1598
  _insertRecordWithoutId = new WeakSet();
1280
- insertRecordWithoutId_fn = async function(object) {
1281
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1599
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1600
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1282
1601
  const record = transformObjectLinks(object);
1283
1602
  const response = await insertRecord({
1284
1603
  pathParams: {
1285
1604
  workspace: "{workspaceId}",
1286
1605
  dbBranchName: "{dbBranch}",
1287
- tableName: __privateGet$3(this, _table)
1606
+ tableName: __privateGet$4(this, _table)
1288
1607
  },
1608
+ queryParams: { columns },
1289
1609
  body: record,
1290
1610
  ...fetchProps
1291
1611
  });
1292
- const finalObject = await this.read(response.id);
1293
- if (!finalObject) {
1294
- throw new Error("The server failed to save the record");
1295
- }
1296
- 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);
1297
1614
  };
1298
1615
  _insertRecordWithId = new WeakSet();
1299
- insertRecordWithId_fn = async function(recordId, object) {
1300
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1616
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
1617
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1301
1618
  const record = transformObjectLinks(object);
1302
1619
  const response = await insertRecordWithID({
1303
1620
  pathParams: {
1304
1621
  workspace: "{workspaceId}",
1305
1622
  dbBranchName: "{dbBranch}",
1306
- tableName: __privateGet$3(this, _table),
1623
+ tableName: __privateGet$4(this, _table),
1307
1624
  recordId
1308
1625
  },
1309
1626
  body: record,
1310
- queryParams: { createOnly: true },
1627
+ queryParams: { createOnly: true, columns },
1311
1628
  ...fetchProps
1312
1629
  });
1313
- const finalObject = await this.read(response.id);
1314
- if (!finalObject) {
1315
- throw new Error("The server failed to save the record");
1316
- }
1317
- 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);
1318
1632
  };
1319
1633
  _bulkInsertTableRecords = new WeakSet();
1320
- bulkInsertTableRecords_fn = async function(objects) {
1321
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1634
+ bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
1635
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1322
1636
  const records = objects.map((object) => transformObjectLinks(object));
1323
1637
  const response = await bulkInsertTableRecords({
1324
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table) },
1638
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1639
+ queryParams: { columns },
1325
1640
  body: { records },
1326
1641
  ...fetchProps
1327
1642
  });
1328
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1329
- if (finalObjects.length !== objects.length) {
1330
- 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");
1331
1645
  }
1332
- return finalObjects;
1646
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1647
+ return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1333
1648
  };
1334
1649
  _updateRecordWithID = new WeakSet();
1335
- updateRecordWithID_fn = async function(recordId, object) {
1336
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1650
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1651
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1337
1652
  const record = transformObjectLinks(object);
1338
- const response = await updateRecordWithID({
1339
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1340
- body: record,
1341
- ...fetchProps
1342
- });
1343
- const item = await this.read(response.id);
1344
- if (!item)
1345
- throw new Error("The server failed to save the record");
1346
- 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
+ }
1347
1668
  };
1348
1669
  _upsertRecordWithID = new WeakSet();
1349
- upsertRecordWithID_fn = async function(recordId, object) {
1350
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1670
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1671
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1351
1672
  const response = await upsertRecordWithID({
1352
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1673
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1674
+ queryParams: { columns },
1353
1675
  body: object,
1354
1676
  ...fetchProps
1355
1677
  });
1356
- const item = await this.read(response.id);
1357
- if (!item)
1358
- throw new Error("The server failed to save the record");
1359
- 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);
1360
1680
  };
1361
1681
  _deleteRecord = new WeakSet();
1362
- deleteRecord_fn = async function(recordId) {
1363
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1364
- await deleteRecord({
1365
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1366
- ...fetchProps
1367
- });
1368
- };
1369
- _invalidateCache = new WeakSet();
1370
- invalidateCache_fn = async function(recordId) {
1371
- await __privateGet$3(this, _cache).delete(`rec_${__privateGet$3(this, _table)}:${recordId}`);
1372
- const cacheItems = await __privateGet$3(this, _cache).getAll();
1373
- const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1374
- for (const [key, value] of queries) {
1375
- const ids = getIds(value);
1376
- if (ids.includes(recordId))
1377
- await __privateGet$3(this, _cache).delete(key);
1682
+ deleteRecord_fn = async function(recordId, columns = ["*"]) {
1683
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
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;
1378
1697
  }
1379
1698
  };
1380
- _setCacheRecord = new WeakSet();
1381
- setCacheRecord_fn = async function(record) {
1382
- if (!__privateGet$3(this, _cache).cacheRecords)
1383
- return;
1384
- await __privateGet$3(this, _cache).set(`rec_${__privateGet$3(this, _table)}:${record.id}`, record);
1385
- };
1386
- _getCacheRecord = new WeakSet();
1387
- getCacheRecord_fn = async function(recordId) {
1388
- if (!__privateGet$3(this, _cache).cacheRecords)
1389
- return null;
1390
- return __privateGet$3(this, _cache).get(`rec_${__privateGet$3(this, _table)}:${recordId}`);
1391
- };
1392
1699
  _setCacheQuery = new WeakSet();
1393
1700
  setCacheQuery_fn = async function(query, meta, records) {
1394
- await __privateGet$3(this, _cache).set(`query_${__privateGet$3(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1701
+ await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1395
1702
  };
1396
1703
  _getCacheQuery = new WeakSet();
1397
1704
  getCacheQuery_fn = async function(query) {
1398
- const key = `query_${__privateGet$3(this, _table)}:${query.key()}`;
1399
- const result = await __privateGet$3(this, _cache).get(key);
1705
+ const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
1706
+ const result = await __privateGet$4(this, _cache).get(key);
1400
1707
  if (!result)
1401
1708
  return null;
1402
- const { cache: ttl = __privateGet$3(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1403
- if (!ttl || ttl < 0)
1404
- return result;
1709
+ const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1710
+ if (ttl < 0)
1711
+ return null;
1405
1712
  const hasExpired = result.date.getTime() + ttl < Date.now();
1406
1713
  return hasExpired ? null : result;
1407
1714
  };
1715
+ _getSchemaTables$1 = new WeakSet();
1716
+ getSchemaTables_fn$1 = async function() {
1717
+ if (__privateGet$4(this, _schemaTables$2))
1718
+ return __privateGet$4(this, _schemaTables$2);
1719
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1720
+ const { schema } = await getBranchDetails({
1721
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1722
+ ...fetchProps
1723
+ });
1724
+ __privateSet$4(this, _schemaTables$2, schema.tables);
1725
+ return schema.tables;
1726
+ };
1408
1727
  const transformObjectLinks = (object) => {
1409
1728
  return Object.entries(object).reduce((acc, [key, value]) => {
1410
1729
  if (key === "xata")
@@ -1412,47 +1731,70 @@ const transformObjectLinks = (object) => {
1412
1731
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1413
1732
  }, {});
1414
1733
  };
1415
- const initObject = (db, links, table, object) => {
1734
+ const initObject = (db, schemaTables, table, object) => {
1416
1735
  const result = {};
1417
- Object.assign(result, object);
1418
- const tableLinks = links[table] || [];
1419
- for (const link of tableLinks) {
1420
- const [field, linkTable] = link;
1421
- const value = result[field];
1422
- if (value && isObject(value)) {
1423
- result[field] = initObject(db, links, linkTable, value);
1736
+ const { xata, ...rest } = object ?? {};
1737
+ Object.assign(result, rest);
1738
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
1739
+ if (!columns)
1740
+ console.error(`Table ${table} not found in schema`);
1741
+ for (const column of columns ?? []) {
1742
+ const value = result[column.name];
1743
+ switch (column.type) {
1744
+ case "datetime": {
1745
+ const date = value !== void 0 ? new Date(value) : void 0;
1746
+ if (date && isNaN(date.getTime())) {
1747
+ console.error(`Failed to parse date ${value} for field ${column.name}`);
1748
+ } else if (date) {
1749
+ result[column.name] = date;
1750
+ }
1751
+ break;
1752
+ }
1753
+ case "link": {
1754
+ const linkTable = column.link?.table;
1755
+ if (!linkTable) {
1756
+ console.error(`Failed to parse link for field ${column.name}`);
1757
+ } else if (isObject(value)) {
1758
+ result[column.name] = initObject(db, schemaTables, linkTable, value);
1759
+ }
1760
+ break;
1761
+ }
1424
1762
  }
1425
1763
  }
1426
- result.read = function() {
1427
- return db[table].read(result["id"]);
1764
+ result.read = function(columns2) {
1765
+ return db[table].read(result["id"], columns2);
1428
1766
  };
1429
- result.update = function(data) {
1430
- return db[table].update(result["id"], data);
1767
+ result.update = function(data, columns2) {
1768
+ return db[table].update(result["id"], data, columns2);
1431
1769
  };
1432
1770
  result.delete = function() {
1433
1771
  return db[table].delete(result["id"]);
1434
1772
  };
1435
- for (const prop of ["read", "update", "delete"]) {
1773
+ result.getMetadata = function() {
1774
+ return xata;
1775
+ };
1776
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1436
1777
  Object.defineProperty(result, prop, { enumerable: false });
1437
1778
  }
1438
1779
  Object.freeze(result);
1439
1780
  return result;
1440
1781
  };
1441
- function getIds(value) {
1442
- if (Array.isArray(value)) {
1443
- return value.map((item) => getIds(item)).flat();
1444
- }
1445
- if (!isObject(value))
1446
- return [];
1447
- const nestedIds = Object.values(value).map((item) => getIds(item)).flat();
1448
- 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;
1449
1791
  }
1450
1792
 
1451
1793
  var __accessCheck$3 = (obj, member, msg) => {
1452
1794
  if (!member.has(obj))
1453
1795
  throw TypeError("Cannot " + msg);
1454
1796
  };
1455
- var __privateGet$2 = (obj, member, getter) => {
1797
+ var __privateGet$3 = (obj, member, getter) => {
1456
1798
  __accessCheck$3(obj, member, "read from private field");
1457
1799
  return getter ? getter.call(obj) : member.get(obj);
1458
1800
  };
@@ -1461,7 +1803,7 @@ var __privateAdd$3 = (obj, member, value) => {
1461
1803
  throw TypeError("Cannot add the same private member more than once");
1462
1804
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1463
1805
  };
1464
- var __privateSet$1 = (obj, member, value, setter) => {
1806
+ var __privateSet$3 = (obj, member, value, setter) => {
1465
1807
  __accessCheck$3(obj, member, "write to private field");
1466
1808
  setter ? setter.call(obj, value) : member.set(obj, value);
1467
1809
  return value;
@@ -1470,46 +1812,52 @@ var _map;
1470
1812
  class SimpleCache {
1471
1813
  constructor(options = {}) {
1472
1814
  __privateAdd$3(this, _map, void 0);
1473
- __privateSet$1(this, _map, /* @__PURE__ */ new Map());
1815
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1474
1816
  this.capacity = options.max ?? 500;
1475
- this.cacheRecords = options.cacheRecords ?? true;
1476
1817
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1477
1818
  }
1478
1819
  async getAll() {
1479
- return Object.fromEntries(__privateGet$2(this, _map));
1820
+ return Object.fromEntries(__privateGet$3(this, _map));
1480
1821
  }
1481
1822
  async get(key) {
1482
- return __privateGet$2(this, _map).get(key) ?? null;
1823
+ return __privateGet$3(this, _map).get(key) ?? null;
1483
1824
  }
1484
1825
  async set(key, value) {
1485
1826
  await this.delete(key);
1486
- __privateGet$2(this, _map).set(key, value);
1487
- if (__privateGet$2(this, _map).size > this.capacity) {
1488
- const leastRecentlyUsed = __privateGet$2(this, _map).keys().next().value;
1827
+ __privateGet$3(this, _map).set(key, value);
1828
+ if (__privateGet$3(this, _map).size > this.capacity) {
1829
+ const leastRecentlyUsed = __privateGet$3(this, _map).keys().next().value;
1489
1830
  await this.delete(leastRecentlyUsed);
1490
1831
  }
1491
1832
  }
1492
1833
  async delete(key) {
1493
- __privateGet$2(this, _map).delete(key);
1834
+ __privateGet$3(this, _map).delete(key);
1494
1835
  }
1495
1836
  async clear() {
1496
- return __privateGet$2(this, _map).clear();
1837
+ return __privateGet$3(this, _map).clear();
1497
1838
  }
1498
1839
  }
1499
1840
  _map = new WeakMap();
1500
1841
 
1501
- const gt = (value) => ({ $gt: value });
1502
- const ge = (value) => ({ $ge: value });
1503
- const gte = (value) => ({ $ge: value });
1504
- const lt = (value) => ({ $lt: value });
1505
- const lte = (value) => ({ $le: value });
1506
- 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;
1507
1854
  const exists = (column) => ({ $exists: column });
1508
1855
  const notExists = (column) => ({ $notExists: column });
1509
1856
  const startsWith = (value) => ({ $startsWith: value });
1510
1857
  const endsWith = (value) => ({ $endsWith: value });
1511
1858
  const pattern = (value) => ({ $pattern: value });
1512
1859
  const is = (value) => ({ $is: value });
1860
+ const equals = is;
1513
1861
  const isNot = (value) => ({ $isNot: value });
1514
1862
  const contains = (value) => ({ $contains: value });
1515
1863
  const includes = (value) => ({ $includes: value });
@@ -1521,7 +1869,7 @@ var __accessCheck$2 = (obj, member, msg) => {
1521
1869
  if (!member.has(obj))
1522
1870
  throw TypeError("Cannot " + msg);
1523
1871
  };
1524
- var __privateGet$1 = (obj, member, getter) => {
1872
+ var __privateGet$2 = (obj, member, getter) => {
1525
1873
  __accessCheck$2(obj, member, "read from private field");
1526
1874
  return getter ? getter.call(obj) : member.get(obj);
1527
1875
  };
@@ -1530,130 +1878,178 @@ var __privateAdd$2 = (obj, member, value) => {
1530
1878
  throw TypeError("Cannot add the same private member more than once");
1531
1879
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1532
1880
  };
1533
- var _tables;
1881
+ var __privateSet$2 = (obj, member, value, setter) => {
1882
+ __accessCheck$2(obj, member, "write to private field");
1883
+ setter ? setter.call(obj, value) : member.set(obj, value);
1884
+ return value;
1885
+ };
1886
+ var _tables, _schemaTables$1;
1534
1887
  class SchemaPlugin extends XataPlugin {
1535
- constructor(links, tableNames) {
1888
+ constructor(schemaTables) {
1536
1889
  super();
1537
- this.links = links;
1538
- this.tableNames = tableNames;
1539
1890
  __privateAdd$2(this, _tables, {});
1891
+ __privateAdd$2(this, _schemaTables$1, void 0);
1892
+ __privateSet$2(this, _schemaTables$1, schemaTables);
1540
1893
  }
1541
1894
  build(pluginOptions) {
1542
- const links = this.links;
1543
- const db = new Proxy({}, {
1544
- get: (_target, table) => {
1545
- if (!isString(table))
1546
- throw new Error("Invalid table name");
1547
- if (!__privateGet$1(this, _tables)[table]) {
1548
- __privateGet$1(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, links });
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];
1549
1905
  }
1550
- return __privateGet$1(this, _tables)[table];
1551
1906
  }
1552
- });
1553
- for (const table of this.tableNames ?? []) {
1554
- db[table] = new RestRepository({ db, pluginOptions, table, links });
1907
+ );
1908
+ const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
1909
+ for (const table of tableNames) {
1910
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1555
1911
  }
1556
1912
  return db;
1557
1913
  }
1558
1914
  }
1559
1915
  _tables = new WeakMap();
1916
+ _schemaTables$1 = new WeakMap();
1560
1917
 
1561
1918
  var __accessCheck$1 = (obj, member, msg) => {
1562
1919
  if (!member.has(obj))
1563
1920
  throw TypeError("Cannot " + msg);
1564
1921
  };
1922
+ var __privateGet$1 = (obj, member, getter) => {
1923
+ __accessCheck$1(obj, member, "read from private field");
1924
+ return getter ? getter.call(obj) : member.get(obj);
1925
+ };
1565
1926
  var __privateAdd$1 = (obj, member, value) => {
1566
1927
  if (member.has(obj))
1567
1928
  throw TypeError("Cannot add the same private member more than once");
1568
1929
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1569
1930
  };
1931
+ var __privateSet$1 = (obj, member, value, setter) => {
1932
+ __accessCheck$1(obj, member, "write to private field");
1933
+ setter ? setter.call(obj, value) : member.set(obj, value);
1934
+ return value;
1935
+ };
1570
1936
  var __privateMethod$1 = (obj, member, method) => {
1571
1937
  __accessCheck$1(obj, member, "access private method");
1572
1938
  return method;
1573
1939
  };
1574
- var _search, search_fn;
1940
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1575
1941
  class SearchPlugin extends XataPlugin {
1576
- constructor(db, links) {
1942
+ constructor(db, schemaTables) {
1577
1943
  super();
1578
1944
  this.db = db;
1579
- this.links = links;
1580
1945
  __privateAdd$1(this, _search);
1946
+ __privateAdd$1(this, _getSchemaTables);
1947
+ __privateAdd$1(this, _schemaTables, void 0);
1948
+ __privateSet$1(this, _schemaTables, schemaTables);
1581
1949
  }
1582
1950
  build({ getFetchProps }) {
1583
1951
  return {
1584
1952
  all: async (query, options = {}) => {
1585
1953
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1954
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1586
1955
  return records.map((record) => {
1587
1956
  const { table = "orphan" } = record.xata;
1588
- return { table, record: initObject(this.db, this.links, table, record) };
1957
+ return { table, record: initObject(this.db, schemaTables, table, record) };
1589
1958
  });
1590
1959
  },
1591
1960
  byTable: async (query, options = {}) => {
1592
1961
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1962
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1593
1963
  return records.reduce((acc, record) => {
1594
1964
  const { table = "orphan" } = record.xata;
1595
1965
  const items = acc[table] ?? [];
1596
- const item = initObject(this.db, this.links, table, record);
1966
+ const item = initObject(this.db, schemaTables, table, record);
1597
1967
  return { ...acc, [table]: [...items, item] };
1598
1968
  }, {});
1599
1969
  }
1600
1970
  };
1601
1971
  }
1602
1972
  }
1973
+ _schemaTables = new WeakMap();
1603
1974
  _search = new WeakSet();
1604
1975
  search_fn = async function(query, options, getFetchProps) {
1605
1976
  const fetchProps = await getFetchProps();
1606
- const { tables, fuzziness } = options ?? {};
1977
+ const { tables, fuzziness, highlight, prefix } = options ?? {};
1607
1978
  const { records } = await searchBranch({
1608
1979
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1609
- body: { tables, query, fuzziness },
1980
+ body: { tables, query, fuzziness, prefix, highlight },
1610
1981
  ...fetchProps
1611
1982
  });
1612
1983
  return records;
1613
1984
  };
1985
+ _getSchemaTables = new WeakSet();
1986
+ getSchemaTables_fn = async function(getFetchProps) {
1987
+ if (__privateGet$1(this, _schemaTables))
1988
+ return __privateGet$1(this, _schemaTables);
1989
+ const fetchProps = await getFetchProps();
1990
+ const { schema } = await getBranchDetails({
1991
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1992
+ ...fetchProps
1993
+ });
1994
+ __privateSet$1(this, _schemaTables, schema.tables);
1995
+ return schema.tables;
1996
+ };
1614
1997
 
1615
1998
  const isBranchStrategyBuilder = (strategy) => {
1616
1999
  return typeof strategy === "function";
1617
2000
  };
1618
2001
 
1619
- const envBranchNames = [
1620
- "XATA_BRANCH",
1621
- "VERCEL_GIT_COMMIT_REF",
1622
- "CF_PAGES_BRANCH",
1623
- "BRANCH"
1624
- ];
1625
- const defaultBranch = "main";
1626
2002
  async function getCurrentBranchName(options) {
1627
- const env = await getBranchByEnvVariable();
1628
- if (env)
1629
- return env;
1630
- const branch = await getGitBranch();
1631
- if (!branch)
1632
- return defaultBranch;
1633
- const details = await getDatabaseBranch(branch, options);
1634
- if (details)
1635
- return branch;
1636
- return defaultBranch;
2003
+ const { branch, envBranch } = getEnvironment();
2004
+ if (branch) {
2005
+ const details = await getDatabaseBranch(branch, options);
2006
+ if (details)
2007
+ return branch;
2008
+ console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
2009
+ }
2010
+ const gitBranch = envBranch || await getGitBranch();
2011
+ return resolveXataBranch(gitBranch, options);
1637
2012
  }
1638
2013
  async function getCurrentBranchDetails(options) {
1639
- const env = await getBranchByEnvVariable();
1640
- if (env)
1641
- return getDatabaseBranch(env, options);
1642
- const branch = await getGitBranch();
1643
- if (!branch)
1644
- return getDatabaseBranch(defaultBranch, options);
1645
- const details = await getDatabaseBranch(branch, options);
1646
- if (details)
1647
- return details;
1648
- return getDatabaseBranch(defaultBranch, options);
2014
+ const branch = await getCurrentBranchName(options);
2015
+ return getDatabaseBranch(branch, options);
2016
+ }
2017
+ async function resolveXataBranch(gitBranch, options) {
2018
+ const databaseURL = options?.databaseURL || getDatabaseURL();
2019
+ const apiKey = options?.apiKey || getAPIKey();
2020
+ if (!databaseURL)
2021
+ throw new Error(
2022
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2023
+ );
2024
+ if (!apiKey)
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
+ );
2028
+ const [protocol, , host, , dbName] = databaseURL.split("/");
2029
+ const [workspace] = host.split(".");
2030
+ const { fallbackBranch } = getEnvironment();
2031
+ const { branch } = await resolveBranch({
2032
+ apiKey,
2033
+ apiUrl: databaseURL,
2034
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
2035
+ workspacesApiUrl: `${protocol}//${host}`,
2036
+ pathParams: { dbName, workspace },
2037
+ queryParams: { gitBranch, fallbackBranch },
2038
+ trace: defaultTrace
2039
+ });
2040
+ return branch;
1649
2041
  }
1650
2042
  async function getDatabaseBranch(branch, options) {
1651
2043
  const databaseURL = options?.databaseURL || getDatabaseURL();
1652
2044
  const apiKey = options?.apiKey || getAPIKey();
1653
2045
  if (!databaseURL)
1654
- 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
+ );
1655
2049
  if (!apiKey)
1656
- 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
+ );
1657
2053
  const [protocol, , host, , database] = databaseURL.split("/");
1658
2054
  const [workspace] = host.split(".");
1659
2055
  const dbBranchName = `${database}:${branch}`;
@@ -1663,10 +2059,8 @@ async function getDatabaseBranch(branch, options) {
1663
2059
  apiUrl: databaseURL,
1664
2060
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1665
2061
  workspacesApiUrl: `${protocol}//${host}`,
1666
- pathParams: {
1667
- dbBranchName,
1668
- workspace
1669
- }
2062
+ pathParams: { dbBranchName, workspace },
2063
+ trace: defaultTrace
1670
2064
  });
1671
2065
  } catch (err) {
1672
2066
  if (isObject(err) && err.status === 404)
@@ -1674,21 +2068,10 @@ async function getDatabaseBranch(branch, options) {
1674
2068
  throw err;
1675
2069
  }
1676
2070
  }
1677
- function getBranchByEnvVariable() {
1678
- for (const name of envBranchNames) {
1679
- const value = getEnvVariable(name);
1680
- if (value) {
1681
- return value;
1682
- }
1683
- }
1684
- try {
1685
- return XATA_BRANCH;
1686
- } catch (err) {
1687
- }
1688
- }
1689
2071
  function getDatabaseURL() {
1690
2072
  try {
1691
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
2073
+ const { databaseURL } = getEnvironment();
2074
+ return databaseURL;
1692
2075
  } catch (err) {
1693
2076
  return void 0;
1694
2077
  }
@@ -1717,24 +2100,27 @@ var __privateMethod = (obj, member, method) => {
1717
2100
  return method;
1718
2101
  };
1719
2102
  const buildClient = (plugins) => {
1720
- 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;
1721
2104
  return _a = class {
1722
- constructor(options = {}, links, tables) {
2105
+ constructor(options = {}, schemaTables) {
1723
2106
  __privateAdd(this, _parseOptions);
1724
2107
  __privateAdd(this, _getFetchProps);
1725
2108
  __privateAdd(this, _evaluateBranch);
1726
2109
  __privateAdd(this, _branch, void 0);
2110
+ __privateAdd(this, _options, void 0);
1727
2111
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
2112
+ __privateSet(this, _options, safeOptions);
1728
2113
  const pluginOptions = {
1729
2114
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1730
- cache: safeOptions.cache
2115
+ cache: safeOptions.cache,
2116
+ trace: safeOptions.trace
1731
2117
  };
1732
- const db = new SchemaPlugin(links, tables).build(pluginOptions);
1733
- const search = new SearchPlugin(db, links ?? {}).build(pluginOptions);
2118
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2119
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1734
2120
  this.db = db;
1735
2121
  this.search = search;
1736
2122
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
1737
- if (!namespace)
2123
+ if (namespace === void 0)
1738
2124
  continue;
1739
2125
  const result = namespace.build(pluginOptions);
1740
2126
  if (result instanceof Promise) {
@@ -1746,22 +2132,26 @@ const buildClient = (plugins) => {
1746
2132
  }
1747
2133
  }
1748
2134
  }
1749
- }, _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) {
1750
2141
  const fetch = getFetchImplementation(options?.fetch);
1751
2142
  const databaseURL = options?.databaseURL || getDatabaseURL();
1752
2143
  const apiKey = options?.apiKey || getAPIKey();
1753
- const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
1754
- const branch = async () => options?.branch ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1755
- if (!databaseURL || !apiKey) {
1756
- throw new Error("Options databaseURL and apiKey are required");
2144
+ const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
2145
+ const trace = options?.trace ?? defaultTrace;
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 });
2147
+ if (!apiKey) {
2148
+ throw new Error("Option apiKey is required");
1757
2149
  }
1758
- return { fetch, databaseURL, apiKey, branch, cache };
1759
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
1760
- fetch,
1761
- apiKey,
1762
- databaseURL,
1763
- branch
1764
- }) {
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 }) {
1765
2155
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
1766
2156
  if (!branchValue)
1767
2157
  throw new Error("Unable to resolve branch value");
@@ -1773,12 +2163,13 @@ const buildClient = (plugins) => {
1773
2163
  const hasBranch = params.dbBranchName ?? params.branch;
1774
2164
  const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branchValue}` : "");
1775
2165
  return databaseURL + newPath;
1776
- }
2166
+ },
2167
+ trace
1777
2168
  };
1778
2169
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1779
2170
  if (__privateGet(this, _branch))
1780
2171
  return __privateGet(this, _branch);
1781
- if (!param)
2172
+ if (param === void 0)
1782
2173
  return void 0;
1783
2174
  const strategies = Array.isArray(param) ? [...param] : [param];
1784
2175
  const evaluateBranch = async (strategy) => {
@@ -1796,6 +2187,88 @@ const buildClient = (plugins) => {
1796
2187
  class BaseClient extends buildClient() {
1797
2188
  }
1798
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
+
1799
2272
  class XataError extends Error {
1800
2273
  constructor(message, status) {
1801
2274
  super(message);
@@ -1803,5 +2276,5 @@ class XataError extends Error {
1803
2276
  }
1804
2277
  }
1805
2278
 
1806
- 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, 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, 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, removeWorkspaceMember, resendWorkspaceMemberInvite, searchBranch, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberRole, upsertRecordWithID };
2279
+ export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, Serializer, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, buildClient, buildWorkerRunner, bulkInsertTableRecords, cancelWorkspaceMemberInvite, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, deserialize, endsWith, equals, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseMetadata, getDatabaseURL, getGitBranchesMapping, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, greaterEquals, greaterThan, greaterThanEquals, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isIdentifiable, isNot, isXataRecord, le, lessEquals, lessThan, lessThanEquals, lt, lte, notExists, operationsByTag, pattern, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, serialize, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID };
1807
2280
  //# sourceMappingURL=index.mjs.map