@xata.io/client 0.0.0-alpha.vf2696e7 → 0.0.0-alpha.vf2ed8b7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -2,6 +2,46 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
+ function _interopNamespace(e) {
6
+ if (e && e.__esModule) return e;
7
+ var n = Object.create(null);
8
+ if (e) {
9
+ Object.keys(e).forEach(function (k) {
10
+ if (k !== 'default') {
11
+ var d = Object.getOwnPropertyDescriptor(e, k);
12
+ Object.defineProperty(n, k, d.get ? d : {
13
+ enumerable: true,
14
+ get: function () { return e[k]; }
15
+ });
16
+ }
17
+ });
18
+ }
19
+ n["default"] = e;
20
+ return Object.freeze(n);
21
+ }
22
+
23
+ const defaultTrace = async (_name, fn, _options) => {
24
+ return await fn({
25
+ setAttributes: () => {
26
+ return;
27
+ }
28
+ });
29
+ };
30
+ const TraceAttributes = {
31
+ KIND: "xata.trace.kind",
32
+ VERSION: "xata.sdk.version",
33
+ TABLE: "xata.table",
34
+ HTTP_REQUEST_ID: "http.request_id",
35
+ HTTP_STATUS_CODE: "http.status_code",
36
+ HTTP_HOST: "http.host",
37
+ HTTP_SCHEME: "http.scheme",
38
+ HTTP_USER_AGENT: "http.user_agent",
39
+ HTTP_METHOD: "http.method",
40
+ HTTP_URL: "http.url",
41
+ HTTP_ROUTE: "http.route",
42
+ HTTP_TARGET: "http.target"
43
+ };
44
+
5
45
  function notEmpty(value) {
6
46
  return value !== null && value !== void 0;
7
47
  }
@@ -11,43 +51,101 @@ function compact(arr) {
11
51
  function isObject(value) {
12
52
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
13
53
  }
54
+ function isDefined(value) {
55
+ return value !== null && value !== void 0;
56
+ }
14
57
  function isString(value) {
15
- return value !== void 0 && value !== null && typeof value === "string";
58
+ return isDefined(value) && typeof value === "string";
59
+ }
60
+ function isStringArray(value) {
61
+ return isDefined(value) && Array.isArray(value) && value.every(isString);
16
62
  }
17
63
  function toBase64(value) {
18
64
  try {
19
65
  return btoa(value);
20
66
  } catch (err) {
21
- return Buffer.from(value).toString("base64");
67
+ const buf = Buffer;
68
+ return buf.from(value).toString("base64");
22
69
  }
23
70
  }
24
71
 
25
- function getEnvVariable(name) {
72
+ function getEnvironment() {
26
73
  try {
27
- if (isObject(process) && isString(process?.env?.[name])) {
28
- return process.env[name];
74
+ if (isObject(process) && isObject(process.env)) {
75
+ return {
76
+ apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
77
+ databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
78
+ branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
79
+ envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
80
+ fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
81
+ };
29
82
  }
30
83
  } catch (err) {
31
84
  }
32
85
  try {
33
- if (isObject(Deno) && isString(Deno?.env?.get(name))) {
34
- return Deno.env.get(name);
86
+ if (isObject(Deno) && isObject(Deno.env)) {
87
+ return {
88
+ apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
89
+ databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
90
+ branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
91
+ envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
92
+ fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
93
+ };
35
94
  }
36
95
  } catch (err) {
37
96
  }
97
+ return {
98
+ apiKey: getGlobalApiKey(),
99
+ databaseURL: getGlobalDatabaseURL(),
100
+ branch: getGlobalBranch(),
101
+ envBranch: void 0,
102
+ fallbackBranch: getGlobalFallbackBranch()
103
+ };
104
+ }
105
+ function getGlobalApiKey() {
106
+ try {
107
+ return XATA_API_KEY;
108
+ } catch (err) {
109
+ return void 0;
110
+ }
111
+ }
112
+ function getGlobalDatabaseURL() {
113
+ try {
114
+ return XATA_DATABASE_URL;
115
+ } catch (err) {
116
+ return void 0;
117
+ }
118
+ }
119
+ function getGlobalBranch() {
120
+ try {
121
+ return XATA_BRANCH;
122
+ } catch (err) {
123
+ return void 0;
124
+ }
125
+ }
126
+ function getGlobalFallbackBranch() {
127
+ try {
128
+ return XATA_FALLBACK_BRANCH;
129
+ } catch (err) {
130
+ return void 0;
131
+ }
38
132
  }
39
133
  async function getGitBranch() {
134
+ const cmd = ["git", "branch", "--show-current"];
135
+ const fullCmd = cmd.join(" ");
136
+ const nodeModule = ["child", "process"].join("_");
137
+ const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
40
138
  try {
41
- return require("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
139
+ if (typeof require === "function") {
140
+ return require(nodeModule).execSync(fullCmd, execOptions).trim();
141
+ }
142
+ const { execSync } = await (function (t) { return Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require(t)); }); })(nodeModule);
143
+ return execSync(fullCmd, execOptions).toString().trim();
42
144
  } catch (err) {
43
145
  }
44
146
  try {
45
147
  if (isObject(Deno)) {
46
- const process2 = Deno.run({
47
- cmd: ["git", "branch", "--show-current"],
48
- stdout: "piped",
49
- stderr: "piped"
50
- });
148
+ const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
51
149
  return new TextDecoder().decode(await process2.output()).trim();
52
150
  }
53
151
  } catch (err) {
@@ -56,7 +154,8 @@ async function getGitBranch() {
56
154
 
57
155
  function getAPIKey() {
58
156
  try {
59
- return getEnvVariable("XATA_API_KEY") ?? XATA_API_KEY;
157
+ const { apiKey } = getEnvironment();
158
+ return apiKey;
60
159
  } catch (err) {
61
160
  return void 0;
62
161
  }
@@ -66,21 +165,35 @@ function getFetchImplementation(userFetch) {
66
165
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
67
166
  const fetchImpl = userFetch ?? globalFetch;
68
167
  if (!fetchImpl) {
69
- throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
168
+ throw new Error(
169
+ `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
170
+ );
70
171
  }
71
172
  return fetchImpl;
72
173
  }
73
174
 
74
- class FetcherError extends Error {
75
- constructor(status, data) {
175
+ const VERSION = "0.0.0-alpha.vf2ed8b7";
176
+
177
+ class ErrorWithCause extends Error {
178
+ constructor(message, options) {
179
+ super(message, options);
180
+ }
181
+ }
182
+ class FetcherError extends ErrorWithCause {
183
+ constructor(status, data, requestId) {
76
184
  super(getMessage(data));
77
185
  this.status = status;
78
186
  this.errors = isBulkError(data) ? data.errors : void 0;
187
+ this.requestId = requestId;
79
188
  if (data instanceof Error) {
80
189
  this.stack = data.stack;
81
190
  this.cause = data.cause;
82
191
  }
83
192
  }
193
+ toString() {
194
+ const error = super.toString();
195
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
196
+ }
84
197
  }
85
198
  function isBulkError(error) {
86
199
  return isObject(error) && Array.isArray(error.errors);
@@ -103,9 +216,17 @@ function getMessage(data) {
103
216
  }
104
217
 
105
218
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
106
- const query = new URLSearchParams(queryParams).toString();
219
+ const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
220
+ if (value === void 0 || value === null)
221
+ return acc;
222
+ return { ...acc, [key]: value };
223
+ }, {});
224
+ const query = new URLSearchParams(cleanQueryParams).toString();
107
225
  const queryString = query.length > 0 ? `?${query}` : "";
108
- return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
226
+ const cleanPathParams = Object.entries(pathParams).reduce((acc, [key, value]) => {
227
+ return { ...acc, [key]: encodeURIComponent(value).replace("%3A", ":") };
228
+ }, {});
229
+ return url.replace(/\{\w*\}/g, (key) => cleanPathParams[key.slice(1, -1)]) + queryString;
109
230
  };
110
231
  function buildBaseUrl({
111
232
  path,
@@ -133,32 +254,61 @@ async function fetch$1({
133
254
  fetchImpl,
134
255
  apiKey,
135
256
  apiUrl,
136
- workspacesApiUrl
257
+ workspacesApiUrl,
258
+ trace
137
259
  }) {
138
- const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
139
- const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
140
- const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
141
- const response = await fetchImpl(url, {
142
- method: method.toUpperCase(),
143
- body: body ? JSON.stringify(body) : void 0,
144
- headers: {
145
- "Content-Type": "application/json",
146
- ...headers,
147
- ...hostHeader(fullUrl),
148
- Authorization: `Bearer ${apiKey}`
149
- }
150
- });
151
- if (response.status === 204) {
152
- return {};
153
- }
260
+ return trace(
261
+ `${method.toUpperCase()} ${path}`,
262
+ async ({ setAttributes }) => {
263
+ const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
264
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
265
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
266
+ setAttributes({
267
+ [TraceAttributes.HTTP_URL]: url,
268
+ [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
269
+ });
270
+ const response = await fetchImpl(url, {
271
+ method: method.toUpperCase(),
272
+ body: body ? JSON.stringify(body) : void 0,
273
+ headers: {
274
+ "Content-Type": "application/json",
275
+ "User-Agent": `Xata client-ts/${VERSION}`,
276
+ ...headers,
277
+ ...hostHeader(fullUrl),
278
+ Authorization: `Bearer ${apiKey}`
279
+ }
280
+ });
281
+ if (response.status === 204) {
282
+ return {};
283
+ }
284
+ const { host, protocol } = parseUrl(response.url);
285
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
286
+ setAttributes({
287
+ [TraceAttributes.KIND]: "http",
288
+ [TraceAttributes.HTTP_REQUEST_ID]: requestId,
289
+ [TraceAttributes.HTTP_STATUS_CODE]: response.status,
290
+ [TraceAttributes.HTTP_HOST]: host,
291
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
292
+ });
293
+ try {
294
+ const jsonResponse = await response.json();
295
+ if (response.ok) {
296
+ return jsonResponse;
297
+ }
298
+ throw new FetcherError(response.status, jsonResponse, requestId);
299
+ } catch (error) {
300
+ throw new FetcherError(response.status, error, requestId);
301
+ }
302
+ },
303
+ { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
304
+ );
305
+ }
306
+ function parseUrl(url) {
154
307
  try {
155
- const jsonResponse = await response.json();
156
- if (response.ok) {
157
- return jsonResponse;
158
- }
159
- throw new FetcherError(response.status, jsonResponse);
308
+ const { host, protocol } = new URL(url);
309
+ return { host, protocol };
160
310
  } catch (error) {
161
- throw new FetcherError(response.status, error);
311
+ return {};
162
312
  }
163
313
  }
164
314
 
@@ -217,6 +367,7 @@ const removeWorkspaceMember = (variables) => fetch$1({
217
367
  ...variables
218
368
  });
219
369
  const inviteWorkspaceMember = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables });
370
+ const updateWorkspaceMemberInvite = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables });
220
371
  const cancelWorkspaceMemberInvite = (variables) => fetch$1({
221
372
  url: "/workspaces/{workspaceId}/invites/{inviteId}",
222
373
  method: "delete",
@@ -252,16 +403,25 @@ const deleteDatabase = (variables) => fetch$1({
252
403
  method: "delete",
253
404
  ...variables
254
405
  });
255
- const getBranchDetails = (variables) => fetch$1({
256
- url: "/db/{dbBranchName}",
406
+ const getDatabaseMetadata = (variables) => fetch$1({
407
+ url: "/dbs/{dbName}/metadata",
257
408
  method: "get",
258
409
  ...variables
259
410
  });
260
- const createBranch = (variables) => fetch$1({
411
+ const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
412
+ const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
413
+ const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
414
+ const resolveBranch = (variables) => fetch$1({
415
+ url: "/dbs/{dbName}/resolveBranch",
416
+ method: "get",
417
+ ...variables
418
+ });
419
+ const getBranchDetails = (variables) => fetch$1({
261
420
  url: "/db/{dbBranchName}",
262
- method: "put",
421
+ method: "get",
263
422
  ...variables
264
423
  });
424
+ const createBranch = (variables) => fetch$1({ url: "/db/{dbBranchName}", method: "put", ...variables });
265
425
  const deleteBranch = (variables) => fetch$1({
266
426
  url: "/db/{dbBranchName}",
267
427
  method: "delete",
@@ -335,11 +495,7 @@ const updateColumn = (variables) => fetch$1({
335
495
  method: "patch",
336
496
  ...variables
337
497
  });
338
- const insertRecord = (variables) => fetch$1({
339
- url: "/db/{dbBranchName}/tables/{tableName}/data",
340
- method: "post",
341
- ...variables
342
- });
498
+ const insertRecord = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables });
343
499
  const insertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables });
344
500
  const updateRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables });
345
501
  const upsertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables });
@@ -359,6 +515,11 @@ const queryTable = (variables) => fetch$1({
359
515
  method: "post",
360
516
  ...variables
361
517
  });
518
+ const searchTable = (variables) => fetch$1({
519
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
520
+ method: "post",
521
+ ...variables
522
+ });
362
523
  const searchBranch = (variables) => fetch$1({
363
524
  url: "/db/{dbBranchName}/search",
364
525
  method: "post",
@@ -376,11 +537,21 @@ const operationsByTag = {
376
537
  updateWorkspaceMemberRole,
377
538
  removeWorkspaceMember,
378
539
  inviteWorkspaceMember,
540
+ updateWorkspaceMemberInvite,
379
541
  cancelWorkspaceMemberInvite,
380
542
  resendWorkspaceMemberInvite,
381
543
  acceptWorkspaceMemberInvite
382
544
  },
383
- database: { getDatabaseList, createDatabase, deleteDatabase },
545
+ database: {
546
+ getDatabaseList,
547
+ createDatabase,
548
+ deleteDatabase,
549
+ getDatabaseMetadata,
550
+ getGitBranchesMapping,
551
+ addGitBranchesEntry,
552
+ removeGitBranchesEntry,
553
+ resolveBranch
554
+ },
384
555
  branch: {
385
556
  getBranchList,
386
557
  getBranchDetails,
@@ -414,14 +585,15 @@ const operationsByTag = {
414
585
  getRecord,
415
586
  bulkInsertTableRecords,
416
587
  queryTable,
588
+ searchTable,
417
589
  searchBranch
418
590
  }
419
591
  };
420
592
 
421
593
  function getHostUrl(provider, type) {
422
- if (isValidAlias(provider)) {
594
+ if (isHostProviderAlias(provider)) {
423
595
  return providers[provider][type];
424
- } else if (isValidBuilder(provider)) {
596
+ } else if (isHostProviderBuilder(provider)) {
425
597
  return provider[type];
426
598
  }
427
599
  throw new Error("Invalid API provider");
@@ -436,10 +608,10 @@ const providers = {
436
608
  workspaces: "https://{workspaceId}.staging.xatabase.co"
437
609
  }
438
610
  };
439
- function isValidAlias(alias) {
611
+ function isHostProviderAlias(alias) {
440
612
  return isString(alias) && Object.keys(providers).includes(alias);
441
613
  }
442
- function isValidBuilder(builder) {
614
+ function isHostProviderBuilder(builder) {
443
615
  return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
444
616
  }
445
617
 
@@ -447,7 +619,7 @@ var __accessCheck$7 = (obj, member, msg) => {
447
619
  if (!member.has(obj))
448
620
  throw TypeError("Cannot " + msg);
449
621
  };
450
- var __privateGet$6 = (obj, member, getter) => {
622
+ var __privateGet$7 = (obj, member, getter) => {
451
623
  __accessCheck$7(obj, member, "read from private field");
452
624
  return getter ? getter.call(obj) : member.get(obj);
453
625
  };
@@ -456,7 +628,7 @@ var __privateAdd$7 = (obj, member, value) => {
456
628
  throw TypeError("Cannot add the same private member more than once");
457
629
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
458
630
  };
459
- var __privateSet$5 = (obj, member, value, setter) => {
631
+ var __privateSet$7 = (obj, member, value, setter) => {
460
632
  __accessCheck$7(obj, member, "write to private field");
461
633
  setter ? setter.call(obj, value) : member.set(obj, value);
462
634
  return value;
@@ -467,46 +639,48 @@ class XataApiClient {
467
639
  __privateAdd$7(this, _extraProps, void 0);
468
640
  __privateAdd$7(this, _namespaces, {});
469
641
  const provider = options.host ?? "production";
470
- const apiKey = options?.apiKey ?? getAPIKey();
642
+ const apiKey = options.apiKey ?? getAPIKey();
643
+ const trace = options.trace ?? defaultTrace;
471
644
  if (!apiKey) {
472
645
  throw new Error("Could not resolve a valid apiKey");
473
646
  }
474
- __privateSet$5(this, _extraProps, {
647
+ __privateSet$7(this, _extraProps, {
475
648
  apiUrl: getHostUrl(provider, "main"),
476
649
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
477
650
  fetchImpl: getFetchImplementation(options.fetch),
478
- apiKey
651
+ apiKey,
652
+ trace
479
653
  });
480
654
  }
481
655
  get user() {
482
- if (!__privateGet$6(this, _namespaces).user)
483
- __privateGet$6(this, _namespaces).user = new UserApi(__privateGet$6(this, _extraProps));
484
- return __privateGet$6(this, _namespaces).user;
656
+ if (!__privateGet$7(this, _namespaces).user)
657
+ __privateGet$7(this, _namespaces).user = new UserApi(__privateGet$7(this, _extraProps));
658
+ return __privateGet$7(this, _namespaces).user;
485
659
  }
486
660
  get workspaces() {
487
- if (!__privateGet$6(this, _namespaces).workspaces)
488
- __privateGet$6(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$6(this, _extraProps));
489
- return __privateGet$6(this, _namespaces).workspaces;
661
+ if (!__privateGet$7(this, _namespaces).workspaces)
662
+ __privateGet$7(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$7(this, _extraProps));
663
+ return __privateGet$7(this, _namespaces).workspaces;
490
664
  }
491
665
  get databases() {
492
- if (!__privateGet$6(this, _namespaces).databases)
493
- __privateGet$6(this, _namespaces).databases = new DatabaseApi(__privateGet$6(this, _extraProps));
494
- return __privateGet$6(this, _namespaces).databases;
666
+ if (!__privateGet$7(this, _namespaces).databases)
667
+ __privateGet$7(this, _namespaces).databases = new DatabaseApi(__privateGet$7(this, _extraProps));
668
+ return __privateGet$7(this, _namespaces).databases;
495
669
  }
496
670
  get branches() {
497
- if (!__privateGet$6(this, _namespaces).branches)
498
- __privateGet$6(this, _namespaces).branches = new BranchApi(__privateGet$6(this, _extraProps));
499
- return __privateGet$6(this, _namespaces).branches;
671
+ if (!__privateGet$7(this, _namespaces).branches)
672
+ __privateGet$7(this, _namespaces).branches = new BranchApi(__privateGet$7(this, _extraProps));
673
+ return __privateGet$7(this, _namespaces).branches;
500
674
  }
501
675
  get tables() {
502
- if (!__privateGet$6(this, _namespaces).tables)
503
- __privateGet$6(this, _namespaces).tables = new TableApi(__privateGet$6(this, _extraProps));
504
- return __privateGet$6(this, _namespaces).tables;
676
+ if (!__privateGet$7(this, _namespaces).tables)
677
+ __privateGet$7(this, _namespaces).tables = new TableApi(__privateGet$7(this, _extraProps));
678
+ return __privateGet$7(this, _namespaces).tables;
505
679
  }
506
680
  get records() {
507
- if (!__privateGet$6(this, _namespaces).records)
508
- __privateGet$6(this, _namespaces).records = new RecordsApi(__privateGet$6(this, _extraProps));
509
- return __privateGet$6(this, _namespaces).records;
681
+ if (!__privateGet$7(this, _namespaces).records)
682
+ __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
683
+ return __privateGet$7(this, _namespaces).records;
510
684
  }
511
685
  }
512
686
  _extraProps = new WeakMap();
@@ -598,6 +772,13 @@ class WorkspaceApi {
598
772
  ...this.extraProps
599
773
  });
600
774
  }
775
+ updateWorkspaceMemberInvite(workspaceId, inviteId, role) {
776
+ return operationsByTag.workspaces.updateWorkspaceMemberInvite({
777
+ pathParams: { workspaceId, inviteId },
778
+ body: { role },
779
+ ...this.extraProps
780
+ });
781
+ }
601
782
  cancelWorkspaceMemberInvite(workspaceId, inviteId) {
602
783
  return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
603
784
  pathParams: { workspaceId, inviteId },
@@ -640,6 +821,39 @@ class DatabaseApi {
640
821
  ...this.extraProps
641
822
  });
642
823
  }
824
+ getDatabaseMetadata(workspace, dbName) {
825
+ return operationsByTag.database.getDatabaseMetadata({
826
+ pathParams: { workspace, dbName },
827
+ ...this.extraProps
828
+ });
829
+ }
830
+ getGitBranchesMapping(workspace, dbName) {
831
+ return operationsByTag.database.getGitBranchesMapping({
832
+ pathParams: { workspace, dbName },
833
+ ...this.extraProps
834
+ });
835
+ }
836
+ addGitBranchesEntry(workspace, dbName, body) {
837
+ return operationsByTag.database.addGitBranchesEntry({
838
+ pathParams: { workspace, dbName },
839
+ body,
840
+ ...this.extraProps
841
+ });
842
+ }
843
+ removeGitBranchesEntry(workspace, dbName, gitBranch) {
844
+ return operationsByTag.database.removeGitBranchesEntry({
845
+ pathParams: { workspace, dbName },
846
+ queryParams: { gitBranch },
847
+ ...this.extraProps
848
+ });
849
+ }
850
+ resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
851
+ return operationsByTag.database.resolveBranch({
852
+ pathParams: { workspace, dbName },
853
+ queryParams: { gitBranch, fallbackBranch },
854
+ ...this.extraProps
855
+ });
856
+ }
643
857
  }
644
858
  class BranchApi {
645
859
  constructor(extraProps) {
@@ -657,10 +871,10 @@ class BranchApi {
657
871
  ...this.extraProps
658
872
  });
659
873
  }
660
- createBranch(workspace, database, branch, from = "", options = {}) {
874
+ createBranch(workspace, database, branch, from, options = {}) {
661
875
  return operationsByTag.branch.createBranch({
662
876
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
663
- queryParams: { from },
877
+ queryParams: isString(from) ? { from } : void 0,
664
878
  body: options,
665
879
  ...this.extraProps
666
880
  });
@@ -785,9 +999,10 @@ class RecordsApi {
785
999
  constructor(extraProps) {
786
1000
  this.extraProps = extraProps;
787
1001
  }
788
- insertRecord(workspace, database, branch, tableName, record) {
1002
+ insertRecord(workspace, database, branch, tableName, record, options = {}) {
789
1003
  return operationsByTag.records.insertRecord({
790
1004
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1005
+ queryParams: options,
791
1006
  body: record,
792
1007
  ...this.extraProps
793
1008
  });
@@ -816,21 +1031,24 @@ class RecordsApi {
816
1031
  ...this.extraProps
817
1032
  });
818
1033
  }
819
- deleteRecord(workspace, database, branch, tableName, recordId) {
1034
+ deleteRecord(workspace, database, branch, tableName, recordId, options = {}) {
820
1035
  return operationsByTag.records.deleteRecord({
821
1036
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1037
+ queryParams: options,
822
1038
  ...this.extraProps
823
1039
  });
824
1040
  }
825
1041
  getRecord(workspace, database, branch, tableName, recordId, options = {}) {
826
1042
  return operationsByTag.records.getRecord({
827
1043
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1044
+ queryParams: options,
828
1045
  ...this.extraProps
829
1046
  });
830
1047
  }
831
- bulkInsertTableRecords(workspace, database, branch, tableName, records) {
1048
+ bulkInsertTableRecords(workspace, database, branch, tableName, records, options = {}) {
832
1049
  return operationsByTag.records.bulkInsertTableRecords({
833
1050
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1051
+ queryParams: options,
834
1052
  body: { records },
835
1053
  ...this.extraProps
836
1054
  });
@@ -842,6 +1060,13 @@ class RecordsApi {
842
1060
  ...this.extraProps
843
1061
  });
844
1062
  }
1063
+ searchTable(workspace, database, branch, tableName, query) {
1064
+ return operationsByTag.records.searchTable({
1065
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1066
+ body: query,
1067
+ ...this.extraProps
1068
+ });
1069
+ }
845
1070
  searchBranch(workspace, database, branch, query) {
846
1071
  return operationsByTag.records.searchBranch({
847
1072
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -865,7 +1090,7 @@ var __accessCheck$6 = (obj, member, msg) => {
865
1090
  if (!member.has(obj))
866
1091
  throw TypeError("Cannot " + msg);
867
1092
  };
868
- var __privateGet$5 = (obj, member, getter) => {
1093
+ var __privateGet$6 = (obj, member, getter) => {
869
1094
  __accessCheck$6(obj, member, "read from private field");
870
1095
  return getter ? getter.call(obj) : member.get(obj);
871
1096
  };
@@ -874,30 +1099,30 @@ var __privateAdd$6 = (obj, member, value) => {
874
1099
  throw TypeError("Cannot add the same private member more than once");
875
1100
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
876
1101
  };
877
- var __privateSet$4 = (obj, member, value, setter) => {
1102
+ var __privateSet$6 = (obj, member, value, setter) => {
878
1103
  __accessCheck$6(obj, member, "write to private field");
879
1104
  setter ? setter.call(obj, value) : member.set(obj, value);
880
1105
  return value;
881
1106
  };
882
- var _query;
1107
+ var _query, _page;
883
1108
  class Page {
884
1109
  constructor(query, meta, records = []) {
885
1110
  __privateAdd$6(this, _query, void 0);
886
- __privateSet$4(this, _query, query);
1111
+ __privateSet$6(this, _query, query);
887
1112
  this.meta = meta;
888
- this.records = records;
1113
+ this.records = new RecordArray(this, records);
889
1114
  }
890
1115
  async nextPage(size, offset) {
891
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, after: this.meta.page.cursor } });
1116
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
892
1117
  }
893
1118
  async previousPage(size, offset) {
894
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, before: this.meta.page.cursor } });
1119
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
895
1120
  }
896
1121
  async firstPage(size, offset) {
897
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, first: this.meta.page.cursor } });
1122
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
898
1123
  }
899
1124
  async lastPage(size, offset) {
900
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, last: this.meta.page.cursor } });
1125
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
901
1126
  }
902
1127
  hasNextPage() {
903
1128
  return this.meta.page.more;
@@ -905,15 +1130,62 @@ class Page {
905
1130
  }
906
1131
  _query = new WeakMap();
907
1132
  const PAGINATION_MAX_SIZE = 200;
908
- const PAGINATION_DEFAULT_SIZE = 200;
1133
+ const PAGINATION_DEFAULT_SIZE = 20;
909
1134
  const PAGINATION_MAX_OFFSET = 800;
910
1135
  const PAGINATION_DEFAULT_OFFSET = 0;
1136
+ function isCursorPaginationOptions(options) {
1137
+ return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
1138
+ }
1139
+ const _RecordArray = class extends Array {
1140
+ constructor(...args) {
1141
+ super(..._RecordArray.parseConstructorParams(...args));
1142
+ __privateAdd$6(this, _page, void 0);
1143
+ __privateSet$6(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
1144
+ }
1145
+ static parseConstructorParams(...args) {
1146
+ if (args.length === 1 && typeof args[0] === "number") {
1147
+ return new Array(args[0]);
1148
+ }
1149
+ if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
1150
+ const result = args[1] ?? args[0].records ?? [];
1151
+ return new Array(...result);
1152
+ }
1153
+ return new Array(...args);
1154
+ }
1155
+ toArray() {
1156
+ return new Array(...this);
1157
+ }
1158
+ map(callbackfn, thisArg) {
1159
+ return this.toArray().map(callbackfn, thisArg);
1160
+ }
1161
+ async nextPage(size, offset) {
1162
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1163
+ return new _RecordArray(newPage);
1164
+ }
1165
+ async previousPage(size, offset) {
1166
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1167
+ return new _RecordArray(newPage);
1168
+ }
1169
+ async firstPage(size, offset) {
1170
+ const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1171
+ return new _RecordArray(newPage);
1172
+ }
1173
+ async lastPage(size, offset) {
1174
+ const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1175
+ return new _RecordArray(newPage);
1176
+ }
1177
+ hasNextPage() {
1178
+ return __privateGet$6(this, _page).meta.page.more;
1179
+ }
1180
+ };
1181
+ let RecordArray = _RecordArray;
1182
+ _page = new WeakMap();
911
1183
 
912
1184
  var __accessCheck$5 = (obj, member, msg) => {
913
1185
  if (!member.has(obj))
914
1186
  throw TypeError("Cannot " + msg);
915
1187
  };
916
- var __privateGet$4 = (obj, member, getter) => {
1188
+ var __privateGet$5 = (obj, member, getter) => {
917
1189
  __accessCheck$5(obj, member, "read from private field");
918
1190
  return getter ? getter.call(obj) : member.get(obj);
919
1191
  };
@@ -922,34 +1194,35 @@ var __privateAdd$5 = (obj, member, value) => {
922
1194
  throw TypeError("Cannot add the same private member more than once");
923
1195
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
924
1196
  };
925
- var __privateSet$3 = (obj, member, value, setter) => {
1197
+ var __privateSet$5 = (obj, member, value, setter) => {
926
1198
  __accessCheck$5(obj, member, "write to private field");
927
1199
  setter ? setter.call(obj, value) : member.set(obj, value);
928
1200
  return value;
929
1201
  };
930
1202
  var _table$1, _repository, _data;
931
1203
  const _Query = class {
932
- constructor(repository, table, data, parent) {
1204
+ constructor(repository, table, data, rawParent) {
933
1205
  __privateAdd$5(this, _table$1, void 0);
934
1206
  __privateAdd$5(this, _repository, void 0);
935
1207
  __privateAdd$5(this, _data, { filter: {} });
936
1208
  this.meta = { page: { cursor: "start", more: true } };
937
- this.records = [];
938
- __privateSet$3(this, _table$1, table);
1209
+ this.records = new RecordArray(this, []);
1210
+ __privateSet$5(this, _table$1, table);
939
1211
  if (repository) {
940
- __privateSet$3(this, _repository, repository);
1212
+ __privateSet$5(this, _repository, repository);
941
1213
  } else {
942
- __privateSet$3(this, _repository, this);
1214
+ __privateSet$5(this, _repository, this);
943
1215
  }
944
- __privateGet$4(this, _data).filter = data.filter ?? parent?.filter ?? {};
945
- __privateGet$4(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
946
- __privateGet$4(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
947
- __privateGet$4(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
948
- __privateGet$4(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
949
- __privateGet$4(this, _data).sort = data.sort ?? parent?.sort;
950
- __privateGet$4(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
951
- __privateGet$4(this, _data).page = data.page ?? parent?.page;
952
- __privateGet$4(this, _data).cache = data.cache ?? parent?.cache;
1216
+ const parent = cleanParent(data, rawParent);
1217
+ __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
1218
+ __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
1219
+ __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
1220
+ __privateGet$5(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
1221
+ __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1222
+ __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1223
+ __privateGet$5(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
1224
+ __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1225
+ __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
953
1226
  this.any = this.any.bind(this);
954
1227
  this.all = this.all.bind(this);
955
1228
  this.not = this.not.bind(this);
@@ -960,83 +1233,101 @@ const _Query = class {
960
1233
  Object.defineProperty(this, "repository", { enumerable: false });
961
1234
  }
962
1235
  getQueryOptions() {
963
- return __privateGet$4(this, _data);
1236
+ return __privateGet$5(this, _data);
964
1237
  }
965
1238
  key() {
966
- const { columns = [], filter = {}, sort = [], page = {} } = __privateGet$4(this, _data);
967
- const key = JSON.stringify({ columns, filter, sort, page });
1239
+ const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$5(this, _data);
1240
+ const key = JSON.stringify({ columns, filter, sort, pagination });
968
1241
  return toBase64(key);
969
1242
  }
970
1243
  any(...queries) {
971
1244
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
972
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $any } }, __privateGet$4(this, _data));
1245
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
973
1246
  }
974
1247
  all(...queries) {
975
1248
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
976
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1249
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
977
1250
  }
978
1251
  not(...queries) {
979
1252
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
980
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $not } }, __privateGet$4(this, _data));
1253
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
981
1254
  }
982
1255
  none(...queries) {
983
1256
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
984
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $none } }, __privateGet$4(this, _data));
1257
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
985
1258
  }
986
1259
  filter(a, b) {
987
1260
  if (arguments.length === 1) {
988
- const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
989
- const $all = compact([__privateGet$4(this, _data).filter?.$all].flat().concat(constraints));
990
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1261
+ const constraints = Object.entries(a ?? {}).map(([column, constraint]) => ({ [column]: constraint }));
1262
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1263
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
991
1264
  } else {
992
- const $all = compact([__privateGet$4(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
993
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1265
+ const constraints = isDefined(a) && isDefined(b) ? [{ [a]: this.defaultFilter(a, b) }] : void 0;
1266
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1267
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1268
+ }
1269
+ }
1270
+ defaultFilter(column, value) {
1271
+ const columnType = __privateGet$5(this, _table$1).schema?.columns.find(({ name }) => name === column)?.type;
1272
+ if (columnType === "multiple" && (isString(value) || isStringArray(value))) {
1273
+ return { $includes: value };
994
1274
  }
1275
+ return value;
995
1276
  }
996
- sort(column, direction) {
997
- const originalSort = [__privateGet$4(this, _data).sort ?? []].flat();
1277
+ sort(column, direction = "asc") {
1278
+ const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
998
1279
  const sort = [...originalSort, { column, direction }];
999
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { sort }, __privateGet$4(this, _data));
1280
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
1000
1281
  }
1001
1282
  select(columns) {
1002
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { columns }, __privateGet$4(this, _data));
1283
+ return new _Query(
1284
+ __privateGet$5(this, _repository),
1285
+ __privateGet$5(this, _table$1),
1286
+ { columns },
1287
+ __privateGet$5(this, _data)
1288
+ );
1003
1289
  }
1004
1290
  getPaginated(options = {}) {
1005
- const query = new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), options, __privateGet$4(this, _data));
1006
- return __privateGet$4(this, _repository).query(query);
1291
+ const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
1292
+ return __privateGet$5(this, _repository).query(query);
1007
1293
  }
1008
1294
  async *[Symbol.asyncIterator]() {
1009
- for await (const [record] of this.getIterator(1)) {
1295
+ for await (const [record] of this.getIterator({ batchSize: 1 })) {
1010
1296
  yield record;
1011
1297
  }
1012
1298
  }
1013
- async *getIterator(chunk, options = {}) {
1014
- let offset = 0;
1015
- let end = false;
1016
- while (!end) {
1017
- const { records, meta } = await this.getPaginated({ ...options, page: { size: chunk, offset } });
1018
- yield records;
1019
- offset += chunk;
1020
- end = !meta.page.more;
1299
+ async *getIterator(options = {}) {
1300
+ const { batchSize = 1 } = options;
1301
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
1302
+ let more = page.hasNextPage();
1303
+ yield page.records;
1304
+ while (more) {
1305
+ page = await page.nextPage();
1306
+ more = page.hasNextPage();
1307
+ yield page.records;
1021
1308
  }
1022
1309
  }
1023
1310
  async getMany(options = {}) {
1024
- const { records } = await this.getPaginated(options);
1025
- return records;
1311
+ const page = await this.getPaginated(options);
1312
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1313
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1314
+ }
1315
+ return page.records;
1026
1316
  }
1027
- async getAll(chunk = PAGINATION_MAX_SIZE, options = {}) {
1317
+ async getAll(options = {}) {
1318
+ const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
1028
1319
  const results = [];
1029
- for await (const page of this.getIterator(chunk, options)) {
1320
+ for await (const page of this.getIterator({ ...rest, batchSize })) {
1030
1321
  results.push(...page);
1031
1322
  }
1032
1323
  return results;
1033
1324
  }
1034
1325
  async getFirst(options = {}) {
1035
- const records = await this.getMany({ ...options, page: { size: 1 } });
1036
- return records[0] || null;
1326
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1327
+ return records[0] ?? null;
1037
1328
  }
1038
1329
  cache(ttl) {
1039
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { cache: ttl }, __privateGet$4(this, _data));
1330
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1040
1331
  }
1041
1332
  nextPage(size, offset) {
1042
1333
  return this.firstPage(size, offset);
@@ -1045,10 +1336,10 @@ const _Query = class {
1045
1336
  return this.firstPage(size, offset);
1046
1337
  }
1047
1338
  firstPage(size, offset) {
1048
- return this.getPaginated({ page: { size, offset } });
1339
+ return this.getPaginated({ pagination: { size, offset } });
1049
1340
  }
1050
1341
  lastPage(size, offset) {
1051
- return this.getPaginated({ page: { size, offset, before: "end" } });
1342
+ return this.getPaginated({ pagination: { size, offset, before: "end" } });
1052
1343
  }
1053
1344
  hasNextPage() {
1054
1345
  return this.meta.page.more;
@@ -1058,12 +1349,20 @@ let Query = _Query;
1058
1349
  _table$1 = new WeakMap();
1059
1350
  _repository = new WeakMap();
1060
1351
  _data = new WeakMap();
1352
+ function cleanParent(data, parent) {
1353
+ if (isCursorPaginationOptions(data.pagination)) {
1354
+ return { ...parent, sorting: void 0, filter: void 0 };
1355
+ }
1356
+ return parent;
1357
+ }
1061
1358
 
1062
1359
  function isIdentifiable(x) {
1063
1360
  return isObject(x) && isString(x?.id);
1064
1361
  }
1065
1362
  function isXataRecord(x) {
1066
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1363
+ const record = x;
1364
+ const metadata = record?.getMetadata();
1365
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1067
1366
  }
1068
1367
 
1069
1368
  function isSortFilterString(value) {
@@ -1093,7 +1392,7 @@ var __accessCheck$4 = (obj, member, msg) => {
1093
1392
  if (!member.has(obj))
1094
1393
  throw TypeError("Cannot " + msg);
1095
1394
  };
1096
- var __privateGet$3 = (obj, member, getter) => {
1395
+ var __privateGet$4 = (obj, member, getter) => {
1097
1396
  __accessCheck$4(obj, member, "read from private field");
1098
1397
  return getter ? getter.call(obj) : member.get(obj);
1099
1398
  };
@@ -1102,7 +1401,7 @@ var __privateAdd$4 = (obj, member, value) => {
1102
1401
  throw TypeError("Cannot add the same private member more than once");
1103
1402
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1104
1403
  };
1105
- var __privateSet$2 = (obj, member, value, setter) => {
1404
+ var __privateSet$4 = (obj, member, value, setter) => {
1106
1405
  __accessCheck$4(obj, member, "write to private field");
1107
1406
  setter ? setter.call(obj, value) : member.set(obj, value);
1108
1407
  return value;
@@ -1111,304 +1410,355 @@ var __privateMethod$2 = (obj, member, method) => {
1111
1410
  __accessCheck$4(obj, member, "access private method");
1112
1411
  return method;
1113
1412
  };
1114
- 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;
1413
+ 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;
1115
1414
  class Repository extends Query {
1116
1415
  }
1117
1416
  class RestRepository extends Query {
1118
1417
  constructor(options) {
1119
- super(null, options.table, {});
1418
+ super(
1419
+ null,
1420
+ { name: options.table, schema: options.schemaTables?.find((table) => table.name === options.table) },
1421
+ {}
1422
+ );
1120
1423
  __privateAdd$4(this, _insertRecordWithoutId);
1121
1424
  __privateAdd$4(this, _insertRecordWithId);
1122
1425
  __privateAdd$4(this, _bulkInsertTableRecords);
1123
1426
  __privateAdd$4(this, _updateRecordWithID);
1124
1427
  __privateAdd$4(this, _upsertRecordWithID);
1125
1428
  __privateAdd$4(this, _deleteRecord);
1126
- __privateAdd$4(this, _invalidateCache);
1127
- __privateAdd$4(this, _setCacheRecord);
1128
- __privateAdd$4(this, _getCacheRecord);
1129
1429
  __privateAdd$4(this, _setCacheQuery);
1130
1430
  __privateAdd$4(this, _getCacheQuery);
1431
+ __privateAdd$4(this, _getSchemaTables$1);
1131
1432
  __privateAdd$4(this, _table, void 0);
1132
- __privateAdd$4(this, _links, void 0);
1133
1433
  __privateAdd$4(this, _getFetchProps, void 0);
1434
+ __privateAdd$4(this, _db, void 0);
1134
1435
  __privateAdd$4(this, _cache, void 0);
1135
- __privateSet$2(this, _table, options.table);
1136
- __privateSet$2(this, _links, options.links ?? {});
1137
- __privateSet$2(this, _getFetchProps, options.pluginOptions.getFetchProps);
1138
- this.db = options.db;
1139
- __privateSet$2(this, _cache, options.pluginOptions.cache);
1140
- }
1141
- async create(a, b) {
1142
- if (Array.isArray(a)) {
1143
- const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1144
- await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1145
- return records;
1146
- }
1147
- if (isString(a) && isObject(b)) {
1148
- if (a === "")
1149
- throw new Error("The id can't be empty");
1150
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1151
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1152
- return record;
1153
- }
1154
- if (isObject(a) && isString(a.id)) {
1155
- if (a.id === "")
1156
- throw new Error("The id can't be empty");
1157
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1158
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1159
- return record;
1160
- }
1161
- if (isObject(a)) {
1162
- const record = await __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1163
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1164
- return record;
1165
- }
1166
- throw new Error("Invalid arguments for create method");
1167
- }
1168
- async read(recordId) {
1169
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, recordId);
1170
- if (cacheRecord)
1171
- return cacheRecord;
1172
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1173
- try {
1174
- const response = await getRecord({
1175
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1176
- ...fetchProps
1436
+ __privateAdd$4(this, _schemaTables$2, void 0);
1437
+ __privateAdd$4(this, _trace, void 0);
1438
+ __privateSet$4(this, _table, options.table);
1439
+ __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1440
+ __privateSet$4(this, _db, options.db);
1441
+ __privateSet$4(this, _cache, options.pluginOptions.cache);
1442
+ __privateSet$4(this, _schemaTables$2, options.schemaTables);
1443
+ const trace = options.pluginOptions.trace ?? defaultTrace;
1444
+ __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
1445
+ return trace(name, fn, {
1446
+ ...options2,
1447
+ [TraceAttributes.TABLE]: __privateGet$4(this, _table),
1448
+ [TraceAttributes.KIND]: "sdk-operation",
1449
+ [TraceAttributes.VERSION]: VERSION
1177
1450
  });
1178
- return initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), response);
1179
- } catch (e) {
1180
- if (isObject(e) && e.status === 404) {
1181
- return null;
1451
+ });
1452
+ }
1453
+ async create(a, b, c) {
1454
+ return __privateGet$4(this, _trace).call(this, "create", async () => {
1455
+ if (Array.isArray(a)) {
1456
+ if (a.length === 0)
1457
+ return [];
1458
+ const columns = isStringArray(b) ? b : void 0;
1459
+ return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
1182
1460
  }
1183
- throw e;
1184
- }
1461
+ if (isString(a) && isObject(b)) {
1462
+ if (a === "")
1463
+ throw new Error("The id can't be empty");
1464
+ const columns = isStringArray(c) ? c : void 0;
1465
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns);
1466
+ }
1467
+ if (isObject(a) && isString(a.id)) {
1468
+ if (a.id === "")
1469
+ throw new Error("The id can't be empty");
1470
+ const columns = isStringArray(b) ? b : void 0;
1471
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1472
+ }
1473
+ if (isObject(a)) {
1474
+ const columns = isStringArray(b) ? b : void 0;
1475
+ return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
1476
+ }
1477
+ throw new Error("Invalid arguments for create method");
1478
+ });
1185
1479
  }
1186
- async update(a, b) {
1187
- if (Array.isArray(a)) {
1188
- if (a.length > 100) {
1189
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1480
+ async read(a, b) {
1481
+ return __privateGet$4(this, _trace).call(this, "read", async () => {
1482
+ const columns = isStringArray(b) ? b : ["*"];
1483
+ if (Array.isArray(a)) {
1484
+ if (a.length === 0)
1485
+ return [];
1486
+ const ids = a.map((item) => extractId(item));
1487
+ const finalObjects = await this.getAll({ filter: { id: { $any: compact(ids) } }, columns });
1488
+ const dictionary = finalObjects.reduce((acc, object) => {
1489
+ acc[object.id] = object;
1490
+ return acc;
1491
+ }, {});
1492
+ return ids.map((id2) => dictionary[id2 ?? ""] ?? null);
1190
1493
  }
1191
- return Promise.all(a.map((object) => this.update(object)));
1192
- }
1193
- if (isString(a) && isObject(b)) {
1194
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1195
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1196
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1197
- return record;
1198
- }
1199
- if (isObject(a) && isString(a.id)) {
1200
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1201
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1202
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1203
- return record;
1204
- }
1205
- throw new Error("Invalid arguments for update method");
1494
+ const id = extractId(a);
1495
+ if (id) {
1496
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1497
+ try {
1498
+ const response = await getRecord({
1499
+ pathParams: {
1500
+ workspace: "{workspaceId}",
1501
+ dbBranchName: "{dbBranch}",
1502
+ tableName: __privateGet$4(this, _table),
1503
+ recordId: id
1504
+ },
1505
+ queryParams: { columns },
1506
+ ...fetchProps
1507
+ });
1508
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1509
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1510
+ } catch (e) {
1511
+ if (isObject(e) && e.status === 404) {
1512
+ return null;
1513
+ }
1514
+ throw e;
1515
+ }
1516
+ }
1517
+ return null;
1518
+ });
1206
1519
  }
1207
- async createOrUpdate(a, b) {
1208
- if (Array.isArray(a)) {
1209
- if (a.length > 100) {
1210
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1520
+ async update(a, b, c) {
1521
+ return __privateGet$4(this, _trace).call(this, "update", async () => {
1522
+ if (Array.isArray(a)) {
1523
+ if (a.length === 0)
1524
+ return [];
1525
+ if (a.length > 100) {
1526
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1527
+ }
1528
+ const columns = isStringArray(b) ? b : ["*"];
1529
+ return Promise.all(a.map((object) => this.update(object, columns)));
1211
1530
  }
1212
- return Promise.all(a.map((object) => this.createOrUpdate(object)));
1213
- }
1214
- if (isString(a) && isObject(b)) {
1215
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1216
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1217
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1218
- return record;
1219
- }
1220
- if (isObject(a) && isString(a.id)) {
1221
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1222
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1223
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1224
- return record;
1225
- }
1226
- throw new Error("Invalid arguments for createOrUpdate method");
1531
+ if (isString(a) && isObject(b)) {
1532
+ const columns = isStringArray(c) ? c : void 0;
1533
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns);
1534
+ }
1535
+ if (isObject(a) && isString(a.id)) {
1536
+ const columns = isStringArray(b) ? b : void 0;
1537
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1538
+ }
1539
+ throw new Error("Invalid arguments for update method");
1540
+ });
1227
1541
  }
1228
- async delete(a) {
1229
- if (Array.isArray(a)) {
1230
- if (a.length > 100) {
1231
- console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1542
+ async createOrUpdate(a, b, c) {
1543
+ return __privateGet$4(this, _trace).call(this, "createOrUpdate", async () => {
1544
+ if (Array.isArray(a)) {
1545
+ if (a.length === 0)
1546
+ return [];
1547
+ if (a.length > 100) {
1548
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1549
+ }
1550
+ const columns = isStringArray(b) ? b : ["*"];
1551
+ return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
1232
1552
  }
1233
- await Promise.all(a.map((id) => this.delete(id)));
1234
- return;
1235
- }
1236
- if (isString(a)) {
1237
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1238
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1239
- return;
1240
- }
1241
- if (isObject(a) && isString(a.id)) {
1242
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1243
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1244
- return;
1245
- }
1246
- throw new Error("Invalid arguments for delete method");
1553
+ if (isString(a) && isObject(b)) {
1554
+ const columns = isStringArray(c) ? c : void 0;
1555
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns);
1556
+ }
1557
+ if (isObject(a) && isString(a.id)) {
1558
+ const columns = isStringArray(c) ? c : void 0;
1559
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1560
+ }
1561
+ throw new Error("Invalid arguments for createOrUpdate method");
1562
+ });
1563
+ }
1564
+ async delete(a, b) {
1565
+ return __privateGet$4(this, _trace).call(this, "delete", async () => {
1566
+ if (Array.isArray(a)) {
1567
+ if (a.length === 0)
1568
+ return [];
1569
+ if (a.length > 100) {
1570
+ console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1571
+ }
1572
+ return Promise.all(a.map((id) => this.delete(id, b)));
1573
+ }
1574
+ if (isString(a)) {
1575
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
1576
+ }
1577
+ if (isObject(a) && isString(a.id)) {
1578
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id, b);
1579
+ }
1580
+ throw new Error("Invalid arguments for delete method");
1581
+ });
1247
1582
  }
1248
1583
  async search(query, options = {}) {
1249
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1250
- const { records } = await searchBranch({
1251
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1252
- body: { tables: [__privateGet$3(this, _table)], query, fuzziness: options.fuzziness },
1253
- ...fetchProps
1584
+ return __privateGet$4(this, _trace).call(this, "search", async () => {
1585
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1586
+ const { records } = await searchTable({
1587
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1588
+ body: {
1589
+ query,
1590
+ fuzziness: options.fuzziness,
1591
+ prefix: options.prefix,
1592
+ highlight: options.highlight,
1593
+ filter: options.filter,
1594
+ boosters: options.boosters
1595
+ },
1596
+ ...fetchProps
1597
+ });
1598
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1599
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1254
1600
  });
1255
- return records.map((item) => initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), item));
1256
1601
  }
1257
1602
  async query(query) {
1258
- const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1259
- if (cacheQuery)
1260
- return new Page(query, cacheQuery.meta, cacheQuery.records);
1261
- const data = query.getQueryOptions();
1262
- const body = {
1263
- filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1264
- sort: data.sort ? buildSortFilter(data.sort) : void 0,
1265
- page: data.page,
1266
- columns: data.columns
1267
- };
1268
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1269
- const { meta, records: objects } = await queryTable({
1270
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table) },
1271
- body,
1272
- ...fetchProps
1603
+ return __privateGet$4(this, _trace).call(this, "query", async () => {
1604
+ const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1605
+ if (cacheQuery)
1606
+ return new Page(query, cacheQuery.meta, cacheQuery.records);
1607
+ const data = query.getQueryOptions();
1608
+ const body = {
1609
+ filter: cleanFilter(data.filter),
1610
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1611
+ page: data.pagination,
1612
+ columns: data.columns
1613
+ };
1614
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1615
+ const { meta, records: objects } = await queryTable({
1616
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1617
+ body,
1618
+ ...fetchProps
1619
+ });
1620
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1621
+ const records = objects.map((record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record));
1622
+ await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1623
+ return new Page(query, meta, records);
1273
1624
  });
1274
- const records = objects.map((record) => initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), record));
1275
- await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1276
- return new Page(query, meta, records);
1277
1625
  }
1278
1626
  }
1279
1627
  _table = new WeakMap();
1280
- _links = new WeakMap();
1281
1628
  _getFetchProps = new WeakMap();
1629
+ _db = new WeakMap();
1282
1630
  _cache = new WeakMap();
1631
+ _schemaTables$2 = new WeakMap();
1632
+ _trace = new WeakMap();
1283
1633
  _insertRecordWithoutId = new WeakSet();
1284
- insertRecordWithoutId_fn = async function(object) {
1285
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1634
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1635
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1286
1636
  const record = transformObjectLinks(object);
1287
1637
  const response = await insertRecord({
1288
1638
  pathParams: {
1289
1639
  workspace: "{workspaceId}",
1290
1640
  dbBranchName: "{dbBranch}",
1291
- tableName: __privateGet$3(this, _table)
1641
+ tableName: __privateGet$4(this, _table)
1292
1642
  },
1643
+ queryParams: { columns },
1293
1644
  body: record,
1294
1645
  ...fetchProps
1295
1646
  });
1296
- const finalObject = await this.read(response.id);
1297
- if (!finalObject) {
1298
- throw new Error("The server failed to save the record");
1299
- }
1300
- return finalObject;
1647
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1648
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1301
1649
  };
1302
1650
  _insertRecordWithId = new WeakSet();
1303
- insertRecordWithId_fn = async function(recordId, object) {
1304
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1651
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
1652
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1305
1653
  const record = transformObjectLinks(object);
1306
1654
  const response = await insertRecordWithID({
1307
1655
  pathParams: {
1308
1656
  workspace: "{workspaceId}",
1309
1657
  dbBranchName: "{dbBranch}",
1310
- tableName: __privateGet$3(this, _table),
1658
+ tableName: __privateGet$4(this, _table),
1311
1659
  recordId
1312
1660
  },
1313
1661
  body: record,
1314
- queryParams: { createOnly: true },
1662
+ queryParams: { createOnly: true, columns },
1315
1663
  ...fetchProps
1316
1664
  });
1317
- const finalObject = await this.read(response.id);
1318
- if (!finalObject) {
1319
- throw new Error("The server failed to save the record");
1320
- }
1321
- return finalObject;
1665
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1666
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1322
1667
  };
1323
1668
  _bulkInsertTableRecords = new WeakSet();
1324
- bulkInsertTableRecords_fn = async function(objects) {
1325
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1669
+ bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
1670
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1326
1671
  const records = objects.map((object) => transformObjectLinks(object));
1327
1672
  const response = await bulkInsertTableRecords({
1328
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table) },
1673
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1674
+ queryParams: { columns },
1329
1675
  body: { records },
1330
1676
  ...fetchProps
1331
1677
  });
1332
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1333
- if (finalObjects.length !== objects.length) {
1334
- throw new Error("The server failed to save some records");
1678
+ if (!isResponseWithRecords(response)) {
1679
+ throw new Error("Request included columns but server didn't include them");
1335
1680
  }
1336
- return finalObjects;
1681
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1682
+ return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1337
1683
  };
1338
1684
  _updateRecordWithID = new WeakSet();
1339
- updateRecordWithID_fn = async function(recordId, object) {
1340
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1685
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1686
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1341
1687
  const record = transformObjectLinks(object);
1342
- const response = await updateRecordWithID({
1343
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1344
- body: record,
1345
- ...fetchProps
1346
- });
1347
- const item = await this.read(response.id);
1348
- if (!item)
1349
- throw new Error("The server failed to save the record");
1350
- return item;
1688
+ try {
1689
+ const response = await updateRecordWithID({
1690
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1691
+ queryParams: { columns },
1692
+ body: record,
1693
+ ...fetchProps
1694
+ });
1695
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1696
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1697
+ } catch (e) {
1698
+ if (isObject(e) && e.status === 404) {
1699
+ return null;
1700
+ }
1701
+ throw e;
1702
+ }
1351
1703
  };
1352
1704
  _upsertRecordWithID = new WeakSet();
1353
- upsertRecordWithID_fn = async function(recordId, object) {
1354
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1705
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1706
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1355
1707
  const response = await upsertRecordWithID({
1356
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1708
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1709
+ queryParams: { columns },
1357
1710
  body: object,
1358
1711
  ...fetchProps
1359
1712
  });
1360
- const item = await this.read(response.id);
1361
- if (!item)
1362
- throw new Error("The server failed to save the record");
1363
- return item;
1713
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1714
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1364
1715
  };
1365
1716
  _deleteRecord = new WeakSet();
1366
- deleteRecord_fn = async function(recordId) {
1367
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1368
- await deleteRecord({
1369
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1370
- ...fetchProps
1371
- });
1372
- };
1373
- _invalidateCache = new WeakSet();
1374
- invalidateCache_fn = async function(recordId) {
1375
- await __privateGet$3(this, _cache).delete(`rec_${__privateGet$3(this, _table)}:${recordId}`);
1376
- const cacheItems = await __privateGet$3(this, _cache).getAll();
1377
- const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1378
- for (const [key, value] of queries) {
1379
- const ids = getIds(value);
1380
- if (ids.includes(recordId))
1381
- await __privateGet$3(this, _cache).delete(key);
1717
+ deleteRecord_fn = async function(recordId, columns = ["*"]) {
1718
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1719
+ try {
1720
+ const response = await deleteRecord({
1721
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1722
+ queryParams: { columns },
1723
+ ...fetchProps
1724
+ });
1725
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1726
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1727
+ } catch (e) {
1728
+ if (isObject(e) && e.status === 404) {
1729
+ return null;
1730
+ }
1731
+ throw e;
1382
1732
  }
1383
1733
  };
1384
- _setCacheRecord = new WeakSet();
1385
- setCacheRecord_fn = async function(record) {
1386
- if (!__privateGet$3(this, _cache).cacheRecords)
1387
- return;
1388
- await __privateGet$3(this, _cache).set(`rec_${__privateGet$3(this, _table)}:${record.id}`, record);
1389
- };
1390
- _getCacheRecord = new WeakSet();
1391
- getCacheRecord_fn = async function(recordId) {
1392
- if (!__privateGet$3(this, _cache).cacheRecords)
1393
- return null;
1394
- return __privateGet$3(this, _cache).get(`rec_${__privateGet$3(this, _table)}:${recordId}`);
1395
- };
1396
1734
  _setCacheQuery = new WeakSet();
1397
1735
  setCacheQuery_fn = async function(query, meta, records) {
1398
- await __privateGet$3(this, _cache).set(`query_${__privateGet$3(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1736
+ await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1399
1737
  };
1400
1738
  _getCacheQuery = new WeakSet();
1401
1739
  getCacheQuery_fn = async function(query) {
1402
- const key = `query_${__privateGet$3(this, _table)}:${query.key()}`;
1403
- const result = await __privateGet$3(this, _cache).get(key);
1740
+ const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
1741
+ const result = await __privateGet$4(this, _cache).get(key);
1404
1742
  if (!result)
1405
1743
  return null;
1406
- const { cache: ttl = __privateGet$3(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1407
- if (!ttl || ttl < 0)
1408
- return result;
1744
+ const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1745
+ if (ttl < 0)
1746
+ return null;
1409
1747
  const hasExpired = result.date.getTime() + ttl < Date.now();
1410
1748
  return hasExpired ? null : result;
1411
1749
  };
1750
+ _getSchemaTables$1 = new WeakSet();
1751
+ getSchemaTables_fn$1 = async function() {
1752
+ if (__privateGet$4(this, _schemaTables$2))
1753
+ return __privateGet$4(this, _schemaTables$2);
1754
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1755
+ const { schema } = await getBranchDetails({
1756
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1757
+ ...fetchProps
1758
+ });
1759
+ __privateSet$4(this, _schemaTables$2, schema.tables);
1760
+ return schema.tables;
1761
+ };
1412
1762
  const transformObjectLinks = (object) => {
1413
1763
  return Object.entries(object).reduce((acc, [key, value]) => {
1414
1764
  if (key === "xata")
@@ -1416,47 +1766,76 @@ const transformObjectLinks = (object) => {
1416
1766
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1417
1767
  }, {});
1418
1768
  };
1419
- const initObject = (db, links, table, object) => {
1769
+ const initObject = (db, schemaTables, table, object) => {
1420
1770
  const result = {};
1421
- Object.assign(result, object);
1422
- const tableLinks = links[table] || [];
1423
- for (const link of tableLinks) {
1424
- const [field, linkTable] = link;
1425
- const value = result[field];
1426
- if (value && isObject(value)) {
1427
- result[field] = initObject(db, links, linkTable, value);
1771
+ const { xata, ...rest } = object ?? {};
1772
+ Object.assign(result, rest);
1773
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
1774
+ if (!columns)
1775
+ console.error(`Table ${table} not found in schema`);
1776
+ for (const column of columns ?? []) {
1777
+ const value = result[column.name];
1778
+ switch (column.type) {
1779
+ case "datetime": {
1780
+ const date = value !== void 0 ? new Date(value) : void 0;
1781
+ if (date && isNaN(date.getTime())) {
1782
+ console.error(`Failed to parse date ${value} for field ${column.name}`);
1783
+ } else if (date) {
1784
+ result[column.name] = date;
1785
+ }
1786
+ break;
1787
+ }
1788
+ case "link": {
1789
+ const linkTable = column.link?.table;
1790
+ if (!linkTable) {
1791
+ console.error(`Failed to parse link for field ${column.name}`);
1792
+ } else if (isObject(value)) {
1793
+ result[column.name] = initObject(db, schemaTables, linkTable, value);
1794
+ }
1795
+ break;
1796
+ }
1428
1797
  }
1429
1798
  }
1430
- result.read = function() {
1431
- return db[table].read(result["id"]);
1799
+ result.read = function(columns2) {
1800
+ return db[table].read(result["id"], columns2);
1432
1801
  };
1433
- result.update = function(data) {
1434
- return db[table].update(result["id"], data);
1802
+ result.update = function(data, columns2) {
1803
+ return db[table].update(result["id"], data, columns2);
1435
1804
  };
1436
1805
  result.delete = function() {
1437
1806
  return db[table].delete(result["id"]);
1438
1807
  };
1439
- for (const prop of ["read", "update", "delete"]) {
1808
+ result.getMetadata = function() {
1809
+ return xata;
1810
+ };
1811
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1440
1812
  Object.defineProperty(result, prop, { enumerable: false });
1441
1813
  }
1442
1814
  Object.freeze(result);
1443
1815
  return result;
1444
1816
  };
1445
- function getIds(value) {
1446
- if (Array.isArray(value)) {
1447
- return value.map((item) => getIds(item)).flat();
1448
- }
1449
- if (!isObject(value))
1450
- return [];
1451
- const nestedIds = Object.values(value).map((item) => getIds(item)).flat();
1452
- return isString(value.id) ? [value.id, ...nestedIds] : nestedIds;
1817
+ function isResponseWithRecords(value) {
1818
+ return isObject(value) && Array.isArray(value.records);
1819
+ }
1820
+ function extractId(value) {
1821
+ if (isString(value))
1822
+ return value;
1823
+ if (isObject(value) && isString(value.id))
1824
+ return value.id;
1825
+ return void 0;
1826
+ }
1827
+ function cleanFilter(filter) {
1828
+ if (!filter)
1829
+ return void 0;
1830
+ const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
1831
+ return values.length > 0 ? filter : void 0;
1453
1832
  }
1454
1833
 
1455
1834
  var __accessCheck$3 = (obj, member, msg) => {
1456
1835
  if (!member.has(obj))
1457
1836
  throw TypeError("Cannot " + msg);
1458
1837
  };
1459
- var __privateGet$2 = (obj, member, getter) => {
1838
+ var __privateGet$3 = (obj, member, getter) => {
1460
1839
  __accessCheck$3(obj, member, "read from private field");
1461
1840
  return getter ? getter.call(obj) : member.get(obj);
1462
1841
  };
@@ -1465,7 +1844,7 @@ var __privateAdd$3 = (obj, member, value) => {
1465
1844
  throw TypeError("Cannot add the same private member more than once");
1466
1845
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1467
1846
  };
1468
- var __privateSet$1 = (obj, member, value, setter) => {
1847
+ var __privateSet$3 = (obj, member, value, setter) => {
1469
1848
  __accessCheck$3(obj, member, "write to private field");
1470
1849
  setter ? setter.call(obj, value) : member.set(obj, value);
1471
1850
  return value;
@@ -1474,46 +1853,52 @@ var _map;
1474
1853
  class SimpleCache {
1475
1854
  constructor(options = {}) {
1476
1855
  __privateAdd$3(this, _map, void 0);
1477
- __privateSet$1(this, _map, /* @__PURE__ */ new Map());
1856
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1478
1857
  this.capacity = options.max ?? 500;
1479
- this.cacheRecords = options.cacheRecords ?? true;
1480
1858
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1481
1859
  }
1482
1860
  async getAll() {
1483
- return Object.fromEntries(__privateGet$2(this, _map));
1861
+ return Object.fromEntries(__privateGet$3(this, _map));
1484
1862
  }
1485
1863
  async get(key) {
1486
- return __privateGet$2(this, _map).get(key) ?? null;
1864
+ return __privateGet$3(this, _map).get(key) ?? null;
1487
1865
  }
1488
1866
  async set(key, value) {
1489
1867
  await this.delete(key);
1490
- __privateGet$2(this, _map).set(key, value);
1491
- if (__privateGet$2(this, _map).size > this.capacity) {
1492
- const leastRecentlyUsed = __privateGet$2(this, _map).keys().next().value;
1868
+ __privateGet$3(this, _map).set(key, value);
1869
+ if (__privateGet$3(this, _map).size > this.capacity) {
1870
+ const leastRecentlyUsed = __privateGet$3(this, _map).keys().next().value;
1493
1871
  await this.delete(leastRecentlyUsed);
1494
1872
  }
1495
1873
  }
1496
1874
  async delete(key) {
1497
- __privateGet$2(this, _map).delete(key);
1875
+ __privateGet$3(this, _map).delete(key);
1498
1876
  }
1499
1877
  async clear() {
1500
- return __privateGet$2(this, _map).clear();
1878
+ return __privateGet$3(this, _map).clear();
1501
1879
  }
1502
1880
  }
1503
1881
  _map = new WeakMap();
1504
1882
 
1505
- const gt = (value) => ({ $gt: value });
1506
- const ge = (value) => ({ $ge: value });
1507
- const gte = (value) => ({ $ge: value });
1508
- const lt = (value) => ({ $lt: value });
1509
- const lte = (value) => ({ $le: value });
1510
- const le = (value) => ({ $le: value });
1883
+ const greaterThan = (value) => ({ $gt: value });
1884
+ const gt = greaterThan;
1885
+ const greaterThanEquals = (value) => ({ $ge: value });
1886
+ const greaterEquals = greaterThanEquals;
1887
+ const gte = greaterThanEquals;
1888
+ const ge = greaterThanEquals;
1889
+ const lessThan = (value) => ({ $lt: value });
1890
+ const lt = lessThan;
1891
+ const lessThanEquals = (value) => ({ $le: value });
1892
+ const lessEquals = lessThanEquals;
1893
+ const lte = lessThanEquals;
1894
+ const le = lessThanEquals;
1511
1895
  const exists = (column) => ({ $exists: column });
1512
1896
  const notExists = (column) => ({ $notExists: column });
1513
1897
  const startsWith = (value) => ({ $startsWith: value });
1514
1898
  const endsWith = (value) => ({ $endsWith: value });
1515
1899
  const pattern = (value) => ({ $pattern: value });
1516
1900
  const is = (value) => ({ $is: value });
1901
+ const equals = is;
1517
1902
  const isNot = (value) => ({ $isNot: value });
1518
1903
  const contains = (value) => ({ $contains: value });
1519
1904
  const includes = (value) => ({ $includes: value });
@@ -1525,7 +1910,7 @@ var __accessCheck$2 = (obj, member, msg) => {
1525
1910
  if (!member.has(obj))
1526
1911
  throw TypeError("Cannot " + msg);
1527
1912
  };
1528
- var __privateGet$1 = (obj, member, getter) => {
1913
+ var __privateGet$2 = (obj, member, getter) => {
1529
1914
  __accessCheck$2(obj, member, "read from private field");
1530
1915
  return getter ? getter.call(obj) : member.get(obj);
1531
1916
  };
@@ -1534,130 +1919,178 @@ var __privateAdd$2 = (obj, member, value) => {
1534
1919
  throw TypeError("Cannot add the same private member more than once");
1535
1920
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1536
1921
  };
1537
- var _tables;
1922
+ var __privateSet$2 = (obj, member, value, setter) => {
1923
+ __accessCheck$2(obj, member, "write to private field");
1924
+ setter ? setter.call(obj, value) : member.set(obj, value);
1925
+ return value;
1926
+ };
1927
+ var _tables, _schemaTables$1;
1538
1928
  class SchemaPlugin extends XataPlugin {
1539
- constructor(links, tableNames) {
1929
+ constructor(schemaTables) {
1540
1930
  super();
1541
- this.links = links;
1542
- this.tableNames = tableNames;
1543
1931
  __privateAdd$2(this, _tables, {});
1932
+ __privateAdd$2(this, _schemaTables$1, void 0);
1933
+ __privateSet$2(this, _schemaTables$1, schemaTables);
1544
1934
  }
1545
1935
  build(pluginOptions) {
1546
- const links = this.links;
1547
- const db = new Proxy({}, {
1548
- get: (_target, table) => {
1549
- if (!isString(table))
1550
- throw new Error("Invalid table name");
1551
- if (!__privateGet$1(this, _tables)[table]) {
1552
- __privateGet$1(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, links });
1936
+ const db = new Proxy(
1937
+ {},
1938
+ {
1939
+ get: (_target, table) => {
1940
+ if (!isString(table))
1941
+ throw new Error("Invalid table name");
1942
+ if (__privateGet$2(this, _tables)[table] === void 0) {
1943
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1944
+ }
1945
+ return __privateGet$2(this, _tables)[table];
1553
1946
  }
1554
- return __privateGet$1(this, _tables)[table];
1555
1947
  }
1556
- });
1557
- for (const table of this.tableNames ?? []) {
1558
- db[table] = new RestRepository({ db, pluginOptions, table, links });
1948
+ );
1949
+ const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
1950
+ for (const table of tableNames) {
1951
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1559
1952
  }
1560
1953
  return db;
1561
1954
  }
1562
1955
  }
1563
1956
  _tables = new WeakMap();
1957
+ _schemaTables$1 = new WeakMap();
1564
1958
 
1565
1959
  var __accessCheck$1 = (obj, member, msg) => {
1566
1960
  if (!member.has(obj))
1567
1961
  throw TypeError("Cannot " + msg);
1568
1962
  };
1963
+ var __privateGet$1 = (obj, member, getter) => {
1964
+ __accessCheck$1(obj, member, "read from private field");
1965
+ return getter ? getter.call(obj) : member.get(obj);
1966
+ };
1569
1967
  var __privateAdd$1 = (obj, member, value) => {
1570
1968
  if (member.has(obj))
1571
1969
  throw TypeError("Cannot add the same private member more than once");
1572
1970
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1573
1971
  };
1972
+ var __privateSet$1 = (obj, member, value, setter) => {
1973
+ __accessCheck$1(obj, member, "write to private field");
1974
+ setter ? setter.call(obj, value) : member.set(obj, value);
1975
+ return value;
1976
+ };
1574
1977
  var __privateMethod$1 = (obj, member, method) => {
1575
1978
  __accessCheck$1(obj, member, "access private method");
1576
1979
  return method;
1577
1980
  };
1578
- var _search, search_fn;
1981
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1579
1982
  class SearchPlugin extends XataPlugin {
1580
- constructor(db, links) {
1983
+ constructor(db, schemaTables) {
1581
1984
  super();
1582
1985
  this.db = db;
1583
- this.links = links;
1584
1986
  __privateAdd$1(this, _search);
1987
+ __privateAdd$1(this, _getSchemaTables);
1988
+ __privateAdd$1(this, _schemaTables, void 0);
1989
+ __privateSet$1(this, _schemaTables, schemaTables);
1585
1990
  }
1586
1991
  build({ getFetchProps }) {
1587
1992
  return {
1588
1993
  all: async (query, options = {}) => {
1589
1994
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1995
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1590
1996
  return records.map((record) => {
1591
1997
  const { table = "orphan" } = record.xata;
1592
- return { table, record: initObject(this.db, this.links, table, record) };
1998
+ return { table, record: initObject(this.db, schemaTables, table, record) };
1593
1999
  });
1594
2000
  },
1595
2001
  byTable: async (query, options = {}) => {
1596
2002
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
2003
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1597
2004
  return records.reduce((acc, record) => {
1598
2005
  const { table = "orphan" } = record.xata;
1599
2006
  const items = acc[table] ?? [];
1600
- const item = initObject(this.db, this.links, table, record);
2007
+ const item = initObject(this.db, schemaTables, table, record);
1601
2008
  return { ...acc, [table]: [...items, item] };
1602
2009
  }, {});
1603
2010
  }
1604
2011
  };
1605
2012
  }
1606
2013
  }
2014
+ _schemaTables = new WeakMap();
1607
2015
  _search = new WeakSet();
1608
2016
  search_fn = async function(query, options, getFetchProps) {
1609
2017
  const fetchProps = await getFetchProps();
1610
- const { tables, fuzziness } = options ?? {};
2018
+ const { tables, fuzziness, highlight, prefix } = options ?? {};
1611
2019
  const { records } = await searchBranch({
1612
2020
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1613
- body: { tables, query, fuzziness },
2021
+ body: { tables, query, fuzziness, prefix, highlight },
1614
2022
  ...fetchProps
1615
2023
  });
1616
2024
  return records;
1617
2025
  };
2026
+ _getSchemaTables = new WeakSet();
2027
+ getSchemaTables_fn = async function(getFetchProps) {
2028
+ if (__privateGet$1(this, _schemaTables))
2029
+ return __privateGet$1(this, _schemaTables);
2030
+ const fetchProps = await getFetchProps();
2031
+ const { schema } = await getBranchDetails({
2032
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
2033
+ ...fetchProps
2034
+ });
2035
+ __privateSet$1(this, _schemaTables, schema.tables);
2036
+ return schema.tables;
2037
+ };
1618
2038
 
1619
2039
  const isBranchStrategyBuilder = (strategy) => {
1620
2040
  return typeof strategy === "function";
1621
2041
  };
1622
2042
 
1623
- const envBranchNames = [
1624
- "XATA_BRANCH",
1625
- "VERCEL_GIT_COMMIT_REF",
1626
- "CF_PAGES_BRANCH",
1627
- "BRANCH"
1628
- ];
1629
- const defaultBranch = "main";
1630
2043
  async function getCurrentBranchName(options) {
1631
- const env = await getBranchByEnvVariable();
1632
- if (env)
1633
- return env;
1634
- const branch = await getGitBranch();
1635
- if (!branch)
1636
- return defaultBranch;
1637
- const details = await getDatabaseBranch(branch, options);
1638
- if (details)
1639
- return branch;
1640
- return defaultBranch;
2044
+ const { branch, envBranch } = getEnvironment();
2045
+ if (branch) {
2046
+ const details = await getDatabaseBranch(branch, options);
2047
+ if (details)
2048
+ return branch;
2049
+ console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
2050
+ }
2051
+ const gitBranch = envBranch || await getGitBranch();
2052
+ return resolveXataBranch(gitBranch, options);
1641
2053
  }
1642
2054
  async function getCurrentBranchDetails(options) {
1643
- const env = await getBranchByEnvVariable();
1644
- if (env)
1645
- return getDatabaseBranch(env, options);
1646
- const branch = await getGitBranch();
1647
- if (!branch)
1648
- return getDatabaseBranch(defaultBranch, options);
1649
- const details = await getDatabaseBranch(branch, options);
1650
- if (details)
1651
- return details;
1652
- return getDatabaseBranch(defaultBranch, options);
2055
+ const branch = await getCurrentBranchName(options);
2056
+ return getDatabaseBranch(branch, options);
2057
+ }
2058
+ async function resolveXataBranch(gitBranch, options) {
2059
+ const databaseURL = options?.databaseURL || getDatabaseURL();
2060
+ const apiKey = options?.apiKey || getAPIKey();
2061
+ if (!databaseURL)
2062
+ throw new Error(
2063
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2064
+ );
2065
+ if (!apiKey)
2066
+ throw new Error(
2067
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2068
+ );
2069
+ const [protocol, , host, , dbName] = databaseURL.split("/");
2070
+ const [workspace] = host.split(".");
2071
+ const { fallbackBranch } = getEnvironment();
2072
+ const { branch } = await resolveBranch({
2073
+ apiKey,
2074
+ apiUrl: databaseURL,
2075
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
2076
+ workspacesApiUrl: `${protocol}//${host}`,
2077
+ pathParams: { dbName, workspace },
2078
+ queryParams: { gitBranch, fallbackBranch },
2079
+ trace: defaultTrace
2080
+ });
2081
+ return branch;
1653
2082
  }
1654
2083
  async function getDatabaseBranch(branch, options) {
1655
2084
  const databaseURL = options?.databaseURL || getDatabaseURL();
1656
2085
  const apiKey = options?.apiKey || getAPIKey();
1657
2086
  if (!databaseURL)
1658
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
2087
+ throw new Error(
2088
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2089
+ );
1659
2090
  if (!apiKey)
1660
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
2091
+ throw new Error(
2092
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2093
+ );
1661
2094
  const [protocol, , host, , database] = databaseURL.split("/");
1662
2095
  const [workspace] = host.split(".");
1663
2096
  const dbBranchName = `${database}:${branch}`;
@@ -1667,10 +2100,8 @@ async function getDatabaseBranch(branch, options) {
1667
2100
  apiUrl: databaseURL,
1668
2101
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1669
2102
  workspacesApiUrl: `${protocol}//${host}`,
1670
- pathParams: {
1671
- dbBranchName,
1672
- workspace
1673
- }
2103
+ pathParams: { dbBranchName, workspace },
2104
+ trace: defaultTrace
1674
2105
  });
1675
2106
  } catch (err) {
1676
2107
  if (isObject(err) && err.status === 404)
@@ -1678,21 +2109,10 @@ async function getDatabaseBranch(branch, options) {
1678
2109
  throw err;
1679
2110
  }
1680
2111
  }
1681
- function getBranchByEnvVariable() {
1682
- for (const name of envBranchNames) {
1683
- const value = getEnvVariable(name);
1684
- if (value) {
1685
- return value;
1686
- }
1687
- }
1688
- try {
1689
- return XATA_BRANCH;
1690
- } catch (err) {
1691
- }
1692
- }
1693
2112
  function getDatabaseURL() {
1694
2113
  try {
1695
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
2114
+ const { databaseURL } = getEnvironment();
2115
+ return databaseURL;
1696
2116
  } catch (err) {
1697
2117
  return void 0;
1698
2118
  }
@@ -1721,24 +2141,27 @@ var __privateMethod = (obj, member, method) => {
1721
2141
  return method;
1722
2142
  };
1723
2143
  const buildClient = (plugins) => {
1724
- var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
2144
+ var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1725
2145
  return _a = class {
1726
- constructor(options = {}, links, tables) {
2146
+ constructor(options = {}, schemaTables) {
1727
2147
  __privateAdd(this, _parseOptions);
1728
2148
  __privateAdd(this, _getFetchProps);
1729
2149
  __privateAdd(this, _evaluateBranch);
1730
2150
  __privateAdd(this, _branch, void 0);
2151
+ __privateAdd(this, _options, void 0);
1731
2152
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
2153
+ __privateSet(this, _options, safeOptions);
1732
2154
  const pluginOptions = {
1733
2155
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1734
- cache: safeOptions.cache
2156
+ cache: safeOptions.cache,
2157
+ trace: safeOptions.trace
1735
2158
  };
1736
- const db = new SchemaPlugin(links, tables).build(pluginOptions);
1737
- const search = new SearchPlugin(db, links ?? {}).build(pluginOptions);
2159
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2160
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1738
2161
  this.db = db;
1739
2162
  this.search = search;
1740
2163
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
1741
- if (!namespace)
2164
+ if (namespace === void 0)
1742
2165
  continue;
1743
2166
  const result = namespace.build(pluginOptions);
1744
2167
  if (result instanceof Promise) {
@@ -1750,22 +2173,26 @@ const buildClient = (plugins) => {
1750
2173
  }
1751
2174
  }
1752
2175
  }
1753
- }, _branch = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
2176
+ async getConfig() {
2177
+ const databaseURL = __privateGet(this, _options).databaseURL;
2178
+ const branch = await __privateGet(this, _options).branch();
2179
+ return { databaseURL, branch };
2180
+ }
2181
+ }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
1754
2182
  const fetch = getFetchImplementation(options?.fetch);
1755
2183
  const databaseURL = options?.databaseURL || getDatabaseURL();
1756
2184
  const apiKey = options?.apiKey || getAPIKey();
1757
- const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
1758
- const branch = async () => options?.branch ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1759
- if (!databaseURL || !apiKey) {
1760
- throw new Error("Options databaseURL and apiKey are required");
2185
+ const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
2186
+ const trace = options?.trace ?? defaultTrace;
2187
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
2188
+ if (!apiKey) {
2189
+ throw new Error("Option apiKey is required");
1761
2190
  }
1762
- return { fetch, databaseURL, apiKey, branch, cache };
1763
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
1764
- fetch,
1765
- apiKey,
1766
- databaseURL,
1767
- branch
1768
- }) {
2191
+ if (!databaseURL) {
2192
+ throw new Error("Option databaseURL is required");
2193
+ }
2194
+ return { fetch, databaseURL, apiKey, branch, cache, trace };
2195
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace }) {
1769
2196
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
1770
2197
  if (!branchValue)
1771
2198
  throw new Error("Unable to resolve branch value");
@@ -1777,12 +2204,13 @@ const buildClient = (plugins) => {
1777
2204
  const hasBranch = params.dbBranchName ?? params.branch;
1778
2205
  const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branchValue}` : "");
1779
2206
  return databaseURL + newPath;
1780
- }
2207
+ },
2208
+ trace
1781
2209
  };
1782
2210
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1783
2211
  if (__privateGet(this, _branch))
1784
2212
  return __privateGet(this, _branch);
1785
- if (!param)
2213
+ if (param === void 0)
1786
2214
  return void 0;
1787
2215
  const strategies = Array.isArray(param) ? [...param] : [param];
1788
2216
  const evaluateBranch = async (strategy) => {
@@ -1800,6 +2228,88 @@ const buildClient = (plugins) => {
1800
2228
  class BaseClient extends buildClient() {
1801
2229
  }
1802
2230
 
2231
+ const META = "__";
2232
+ const VALUE = "___";
2233
+ class Serializer {
2234
+ constructor() {
2235
+ this.classes = {};
2236
+ }
2237
+ add(clazz) {
2238
+ this.classes[clazz.name] = clazz;
2239
+ }
2240
+ toJSON(data) {
2241
+ function visit(obj) {
2242
+ if (Array.isArray(obj))
2243
+ return obj.map(visit);
2244
+ const type = typeof obj;
2245
+ if (type === "undefined")
2246
+ return { [META]: "undefined" };
2247
+ if (type === "bigint")
2248
+ return { [META]: "bigint", [VALUE]: obj.toString() };
2249
+ if (obj === null || type !== "object")
2250
+ return obj;
2251
+ const constructor = obj.constructor;
2252
+ const o = { [META]: constructor.name };
2253
+ for (const [key, value] of Object.entries(obj)) {
2254
+ o[key] = visit(value);
2255
+ }
2256
+ if (constructor === Date)
2257
+ o[VALUE] = obj.toISOString();
2258
+ if (constructor === Map)
2259
+ o[VALUE] = Object.fromEntries(obj);
2260
+ if (constructor === Set)
2261
+ o[VALUE] = [...obj];
2262
+ return o;
2263
+ }
2264
+ return JSON.stringify(visit(data));
2265
+ }
2266
+ fromJSON(json) {
2267
+ return JSON.parse(json, (key, value) => {
2268
+ if (value && typeof value === "object" && !Array.isArray(value)) {
2269
+ const { [META]: clazz, [VALUE]: val, ...rest } = value;
2270
+ const constructor = this.classes[clazz];
2271
+ if (constructor) {
2272
+ return Object.assign(Object.create(constructor.prototype), rest);
2273
+ }
2274
+ if (clazz === "Date")
2275
+ return new Date(val);
2276
+ if (clazz === "Set")
2277
+ return new Set(val);
2278
+ if (clazz === "Map")
2279
+ return new Map(Object.entries(val));
2280
+ if (clazz === "bigint")
2281
+ return BigInt(val);
2282
+ if (clazz === "undefined")
2283
+ return void 0;
2284
+ return rest;
2285
+ }
2286
+ return value;
2287
+ });
2288
+ }
2289
+ }
2290
+ const defaultSerializer = new Serializer();
2291
+ const serialize = (data) => {
2292
+ return defaultSerializer.toJSON(data);
2293
+ };
2294
+ const deserialize = (json) => {
2295
+ return defaultSerializer.fromJSON(json);
2296
+ };
2297
+
2298
+ function buildWorkerRunner(config) {
2299
+ return function xataWorker(name, _worker) {
2300
+ return async (...args) => {
2301
+ const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
2302
+ const result = await fetch(url, {
2303
+ method: "POST",
2304
+ headers: { "Content-Type": "application/json" },
2305
+ body: serialize({ args })
2306
+ });
2307
+ const text = await result.text();
2308
+ return deserialize(text);
2309
+ };
2310
+ };
2311
+ }
2312
+
1803
2313
  class XataError extends Error {
1804
2314
  constructor(message, status) {
1805
2315
  super(message);
@@ -1815,18 +2325,22 @@ exports.PAGINATION_MAX_OFFSET = PAGINATION_MAX_OFFSET;
1815
2325
  exports.PAGINATION_MAX_SIZE = PAGINATION_MAX_SIZE;
1816
2326
  exports.Page = Page;
1817
2327
  exports.Query = Query;
2328
+ exports.RecordArray = RecordArray;
1818
2329
  exports.Repository = Repository;
1819
2330
  exports.RestRepository = RestRepository;
1820
2331
  exports.SchemaPlugin = SchemaPlugin;
1821
2332
  exports.SearchPlugin = SearchPlugin;
2333
+ exports.Serializer = Serializer;
1822
2334
  exports.SimpleCache = SimpleCache;
1823
2335
  exports.XataApiClient = XataApiClient;
1824
2336
  exports.XataApiPlugin = XataApiPlugin;
1825
2337
  exports.XataError = XataError;
1826
2338
  exports.XataPlugin = XataPlugin;
1827
2339
  exports.acceptWorkspaceMemberInvite = acceptWorkspaceMemberInvite;
2340
+ exports.addGitBranchesEntry = addGitBranchesEntry;
1828
2341
  exports.addTableColumn = addTableColumn;
1829
2342
  exports.buildClient = buildClient;
2343
+ exports.buildWorkerRunner = buildWorkerRunner;
1830
2344
  exports.bulkInsertTableRecords = bulkInsertTableRecords;
1831
2345
  exports.cancelWorkspaceMemberInvite = cancelWorkspaceMemberInvite;
1832
2346
  exports.contains = contains;
@@ -1843,7 +2357,9 @@ exports.deleteTable = deleteTable;
1843
2357
  exports.deleteUser = deleteUser;
1844
2358
  exports.deleteUserAPIKey = deleteUserAPIKey;
1845
2359
  exports.deleteWorkspace = deleteWorkspace;
2360
+ exports.deserialize = deserialize;
1846
2361
  exports.endsWith = endsWith;
2362
+ exports.equals = equals;
1847
2363
  exports.executeBranchMigrationPlan = executeBranchMigrationPlan;
1848
2364
  exports.exists = exists;
1849
2365
  exports.ge = ge;
@@ -1858,7 +2374,9 @@ exports.getColumn = getColumn;
1858
2374
  exports.getCurrentBranchDetails = getCurrentBranchDetails;
1859
2375
  exports.getCurrentBranchName = getCurrentBranchName;
1860
2376
  exports.getDatabaseList = getDatabaseList;
2377
+ exports.getDatabaseMetadata = getDatabaseMetadata;
1861
2378
  exports.getDatabaseURL = getDatabaseURL;
2379
+ exports.getGitBranchesMapping = getGitBranchesMapping;
1862
2380
  exports.getRecord = getRecord;
1863
2381
  exports.getTableColumns = getTableColumns;
1864
2382
  exports.getTableSchema = getTableSchema;
@@ -1867,6 +2385,9 @@ exports.getUserAPIKeys = getUserAPIKeys;
1867
2385
  exports.getWorkspace = getWorkspace;
1868
2386
  exports.getWorkspaceMembersList = getWorkspaceMembersList;
1869
2387
  exports.getWorkspacesList = getWorkspacesList;
2388
+ exports.greaterEquals = greaterEquals;
2389
+ exports.greaterThan = greaterThan;
2390
+ exports.greaterThanEquals = greaterThanEquals;
1870
2391
  exports.gt = gt;
1871
2392
  exports.gte = gte;
1872
2393
  exports.includes = includes;
@@ -1877,19 +2398,27 @@ exports.insertRecord = insertRecord;
1877
2398
  exports.insertRecordWithID = insertRecordWithID;
1878
2399
  exports.inviteWorkspaceMember = inviteWorkspaceMember;
1879
2400
  exports.is = is;
2401
+ exports.isCursorPaginationOptions = isCursorPaginationOptions;
1880
2402
  exports.isIdentifiable = isIdentifiable;
1881
2403
  exports.isNot = isNot;
1882
2404
  exports.isXataRecord = isXataRecord;
1883
2405
  exports.le = le;
2406
+ exports.lessEquals = lessEquals;
2407
+ exports.lessThan = lessThan;
2408
+ exports.lessThanEquals = lessThanEquals;
1884
2409
  exports.lt = lt;
1885
2410
  exports.lte = lte;
1886
2411
  exports.notExists = notExists;
1887
2412
  exports.operationsByTag = operationsByTag;
1888
2413
  exports.pattern = pattern;
1889
2414
  exports.queryTable = queryTable;
2415
+ exports.removeGitBranchesEntry = removeGitBranchesEntry;
1890
2416
  exports.removeWorkspaceMember = removeWorkspaceMember;
1891
2417
  exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite;
2418
+ exports.resolveBranch = resolveBranch;
1892
2419
  exports.searchBranch = searchBranch;
2420
+ exports.searchTable = searchTable;
2421
+ exports.serialize = serialize;
1893
2422
  exports.setTableSchema = setTableSchema;
1894
2423
  exports.startsWith = startsWith;
1895
2424
  exports.updateBranchMetadata = updateBranchMetadata;
@@ -1898,6 +2427,7 @@ exports.updateRecordWithID = updateRecordWithID;
1898
2427
  exports.updateTable = updateTable;
1899
2428
  exports.updateUser = updateUser;
1900
2429
  exports.updateWorkspace = updateWorkspace;
2430
+ exports.updateWorkspaceMemberInvite = updateWorkspaceMemberInvite;
1901
2431
  exports.updateWorkspaceMemberRole = updateWorkspaceMemberRole;
1902
2432
  exports.upsertRecordWithID = upsertRecordWithID;
1903
2433
  //# sourceMappingURL=index.cjs.map