@xata.io/client 0.0.0-alpha.vecada6d → 0.0.0-alpha.ved155c7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,3 +1,25 @@
1
+ const defaultTrace = async (_name, fn, _options) => {
2
+ return await fn({
3
+ setAttributes: () => {
4
+ return;
5
+ }
6
+ });
7
+ };
8
+ const TraceAttributes = {
9
+ KIND: "xata.trace.kind",
10
+ VERSION: "xata.sdk.version",
11
+ TABLE: "xata.table",
12
+ HTTP_REQUEST_ID: "http.request_id",
13
+ HTTP_STATUS_CODE: "http.status_code",
14
+ HTTP_HOST: "http.host",
15
+ HTTP_SCHEME: "http.scheme",
16
+ HTTP_USER_AGENT: "http.user_agent",
17
+ HTTP_METHOD: "http.method",
18
+ HTTP_URL: "http.url",
19
+ HTTP_ROUTE: "http.route",
20
+ HTTP_TARGET: "http.target"
21
+ };
22
+
1
23
  function notEmpty(value) {
2
24
  return value !== null && value !== void 0;
3
25
  }
@@ -7,46 +29,101 @@ function compact(arr) {
7
29
  function isObject(value) {
8
30
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
9
31
  }
32
+ function isDefined(value) {
33
+ return value !== null && value !== void 0;
34
+ }
10
35
  function isString(value) {
11
- return value !== void 0 && value !== null && typeof value === "string";
36
+ return isDefined(value) && typeof value === "string";
37
+ }
38
+ function isStringArray(value) {
39
+ return isDefined(value) && Array.isArray(value) && value.every(isString);
12
40
  }
13
41
  function toBase64(value) {
14
42
  try {
15
43
  return btoa(value);
16
44
  } catch (err) {
17
- return Buffer.from(value).toString("base64");
45
+ const buf = Buffer;
46
+ return buf.from(value).toString("base64");
18
47
  }
19
48
  }
20
49
 
21
- function getEnvVariable(name) {
50
+ function getEnvironment() {
22
51
  try {
23
- if (isObject(process) && isString(process?.env?.[name])) {
24
- return process.env[name];
52
+ if (isObject(process) && isObject(process.env)) {
53
+ return {
54
+ apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
55
+ databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
56
+ branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
57
+ envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
58
+ fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
59
+ };
25
60
  }
26
61
  } catch (err) {
27
62
  }
28
63
  try {
29
- if (isObject(Deno) && isString(Deno?.env?.get(name))) {
30
- return Deno.env.get(name);
64
+ if (isObject(Deno) && isObject(Deno.env)) {
65
+ return {
66
+ apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
67
+ databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
68
+ branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
69
+ envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
70
+ fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
71
+ };
31
72
  }
32
73
  } catch (err) {
33
74
  }
75
+ return {
76
+ apiKey: getGlobalApiKey(),
77
+ databaseURL: getGlobalDatabaseURL(),
78
+ branch: getGlobalBranch(),
79
+ envBranch: void 0,
80
+ fallbackBranch: getGlobalFallbackBranch()
81
+ };
82
+ }
83
+ function getGlobalApiKey() {
84
+ try {
85
+ return XATA_API_KEY;
86
+ } catch (err) {
87
+ return void 0;
88
+ }
89
+ }
90
+ function getGlobalDatabaseURL() {
91
+ try {
92
+ return XATA_DATABASE_URL;
93
+ } catch (err) {
94
+ return void 0;
95
+ }
96
+ }
97
+ function getGlobalBranch() {
98
+ try {
99
+ return XATA_BRANCH;
100
+ } catch (err) {
101
+ return void 0;
102
+ }
103
+ }
104
+ function getGlobalFallbackBranch() {
105
+ try {
106
+ return XATA_FALLBACK_BRANCH;
107
+ } catch (err) {
108
+ return void 0;
109
+ }
34
110
  }
35
111
  async function getGitBranch() {
112
+ const cmd = ["git", "branch", "--show-current"];
113
+ const fullCmd = cmd.join(" ");
114
+ const nodeModule = ["child", "process"].join("_");
115
+ const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
36
116
  try {
37
117
  if (typeof require === "function") {
38
- const req = require;
39
- return req("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
118
+ return require(nodeModule).execSync(fullCmd, execOptions).trim();
40
119
  }
120
+ const { execSync } = await import(nodeModule);
121
+ return execSync(fullCmd, execOptions).toString().trim();
41
122
  } catch (err) {
42
123
  }
43
124
  try {
44
125
  if (isObject(Deno)) {
45
- const process2 = Deno.run({
46
- cmd: ["git", "branch", "--show-current"],
47
- stdout: "piped",
48
- stderr: "piped"
49
- });
126
+ const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
50
127
  return new TextDecoder().decode(await process2.output()).trim();
51
128
  }
52
129
  } catch (err) {
@@ -55,7 +132,8 @@ async function getGitBranch() {
55
132
 
56
133
  function getAPIKey() {
57
134
  try {
58
- return getEnvVariable("XATA_API_KEY") ?? XATA_API_KEY;
135
+ const { apiKey } = getEnvironment();
136
+ return apiKey;
59
137
  } catch (err) {
60
138
  return void 0;
61
139
  }
@@ -65,21 +143,35 @@ function getFetchImplementation(userFetch) {
65
143
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
66
144
  const fetchImpl = userFetch ?? globalFetch;
67
145
  if (!fetchImpl) {
68
- throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
146
+ throw new Error(
147
+ `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
148
+ );
69
149
  }
70
150
  return fetchImpl;
71
151
  }
72
152
 
73
- class FetcherError extends Error {
74
- constructor(status, data) {
153
+ const VERSION = "0.0.0-alpha.ved155c7";
154
+
155
+ class ErrorWithCause extends Error {
156
+ constructor(message, options) {
157
+ super(message, options);
158
+ }
159
+ }
160
+ class FetcherError extends ErrorWithCause {
161
+ constructor(status, data, requestId) {
75
162
  super(getMessage(data));
76
163
  this.status = status;
77
164
  this.errors = isBulkError(data) ? data.errors : void 0;
165
+ this.requestId = requestId;
78
166
  if (data instanceof Error) {
79
167
  this.stack = data.stack;
80
168
  this.cause = data.cause;
81
169
  }
82
170
  }
171
+ toString() {
172
+ const error = super.toString();
173
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
174
+ }
83
175
  }
84
176
  function isBulkError(error) {
85
177
  return isObject(error) && Array.isArray(error.errors);
@@ -102,9 +194,17 @@ function getMessage(data) {
102
194
  }
103
195
 
104
196
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
105
- const query = new URLSearchParams(queryParams).toString();
197
+ const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
198
+ if (value === void 0 || value === null)
199
+ return acc;
200
+ return { ...acc, [key]: value };
201
+ }, {});
202
+ const query = new URLSearchParams(cleanQueryParams).toString();
106
203
  const queryString = query.length > 0 ? `?${query}` : "";
107
- return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
204
+ const cleanPathParams = Object.entries(pathParams).reduce((acc, [key, value]) => {
205
+ return { ...acc, [key]: encodeURIComponent(String(value ?? "")).replace("%3A", ":") };
206
+ }, {});
207
+ return url.replace(/\{\w*\}/g, (key) => cleanPathParams[key.slice(1, -1)]) + queryString;
108
208
  };
109
209
  function buildBaseUrl({
110
210
  path,
@@ -112,10 +212,10 @@ function buildBaseUrl({
112
212
  apiUrl,
113
213
  pathParams
114
214
  }) {
115
- if (!pathParams?.workspace)
215
+ if (pathParams?.workspace === void 0)
116
216
  return `${apiUrl}${path}`;
117
217
  const url = typeof workspacesApiUrl === "string" ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
118
- return url.replace("{workspaceId}", pathParams.workspace);
218
+ return url.replace("{workspaceId}", String(pathParams.workspace));
119
219
  }
120
220
  function hostHeader(url) {
121
221
  const pattern = /.*:\/\/(?<host>[^/]+).*/;
@@ -132,32 +232,61 @@ async function fetch$1({
132
232
  fetchImpl,
133
233
  apiKey,
134
234
  apiUrl,
135
- workspacesApiUrl
235
+ workspacesApiUrl,
236
+ trace
136
237
  }) {
137
- const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
138
- const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
139
- const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
140
- const response = await fetchImpl(url, {
141
- method: method.toUpperCase(),
142
- body: body ? JSON.stringify(body) : void 0,
143
- headers: {
144
- "Content-Type": "application/json",
145
- ...headers,
146
- ...hostHeader(fullUrl),
147
- Authorization: `Bearer ${apiKey}`
148
- }
149
- });
150
- if (response.status === 204) {
151
- return {};
152
- }
238
+ return trace(
239
+ `${method.toUpperCase()} ${path}`,
240
+ async ({ setAttributes }) => {
241
+ const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
242
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
243
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
244
+ setAttributes({
245
+ [TraceAttributes.HTTP_URL]: url,
246
+ [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
247
+ });
248
+ const response = await fetchImpl(url, {
249
+ method: method.toUpperCase(),
250
+ body: body ? JSON.stringify(body) : void 0,
251
+ headers: {
252
+ "Content-Type": "application/json",
253
+ "User-Agent": `Xata client-ts/${VERSION}`,
254
+ ...headers,
255
+ ...hostHeader(fullUrl),
256
+ Authorization: `Bearer ${apiKey}`
257
+ }
258
+ });
259
+ if (response.status === 204) {
260
+ return {};
261
+ }
262
+ const { host, protocol } = parseUrl(response.url);
263
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
264
+ setAttributes({
265
+ [TraceAttributes.KIND]: "http",
266
+ [TraceAttributes.HTTP_REQUEST_ID]: requestId,
267
+ [TraceAttributes.HTTP_STATUS_CODE]: response.status,
268
+ [TraceAttributes.HTTP_HOST]: host,
269
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
270
+ });
271
+ try {
272
+ const jsonResponse = await response.json();
273
+ if (response.ok) {
274
+ return jsonResponse;
275
+ }
276
+ throw new FetcherError(response.status, jsonResponse, requestId);
277
+ } catch (error) {
278
+ throw new FetcherError(response.status, error, requestId);
279
+ }
280
+ },
281
+ { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
282
+ );
283
+ }
284
+ function parseUrl(url) {
153
285
  try {
154
- const jsonResponse = await response.json();
155
- if (response.ok) {
156
- return jsonResponse;
157
- }
158
- throw new FetcherError(response.status, jsonResponse);
286
+ const { host, protocol } = new URL(url);
287
+ return { host, protocol };
159
288
  } catch (error) {
160
- throw new FetcherError(response.status, error);
289
+ return {};
161
290
  }
162
291
  }
163
292
 
@@ -216,6 +345,7 @@ const removeWorkspaceMember = (variables) => fetch$1({
216
345
  ...variables
217
346
  });
218
347
  const inviteWorkspaceMember = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables });
348
+ const updateWorkspaceMemberInvite = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables });
219
349
  const cancelWorkspaceMemberInvite = (variables) => fetch$1({
220
350
  url: "/workspaces/{workspaceId}/invites/{inviteId}",
221
351
  method: "delete",
@@ -251,6 +381,12 @@ const deleteDatabase = (variables) => fetch$1({
251
381
  method: "delete",
252
382
  ...variables
253
383
  });
384
+ const getDatabaseMetadata = (variables) => fetch$1({
385
+ url: "/dbs/{dbName}/metadata",
386
+ method: "get",
387
+ ...variables
388
+ });
389
+ const patchDatabaseMetadata = (variables) => fetch$1({ url: "/dbs/{dbName}/metadata", method: "patch", ...variables });
254
390
  const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
255
391
  const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
256
392
  const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
@@ -259,16 +395,28 @@ const resolveBranch = (variables) => fetch$1({
259
395
  method: "get",
260
396
  ...variables
261
397
  });
262
- const getBranchDetails = (variables) => fetch$1({
263
- url: "/db/{dbBranchName}",
398
+ const listMigrationRequests = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/list", method: "post", ...variables });
399
+ const createMigrationRequest = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations", method: "post", ...variables });
400
+ const getMigrationRequest = (variables) => fetch$1({
401
+ url: "/dbs/{dbName}/migrations/{mrNumber}",
264
402
  method: "get",
265
403
  ...variables
266
404
  });
267
- const createBranch = (variables) => fetch$1({
405
+ const updateMigrationRequest = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}", method: "patch", ...variables });
406
+ const listMigrationRequestsCommits = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/commits", method: "post", ...variables });
407
+ const compareMigrationRequest = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/compare", method: "post", ...variables });
408
+ const getMigrationRequestIsMerged = (variables) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/merge", method: "get", ...variables });
409
+ const mergeMigrationRequest = (variables) => fetch$1({
410
+ url: "/dbs/{dbName}/migrations/{mrNumber}/merge",
411
+ method: "post",
412
+ ...variables
413
+ });
414
+ const getBranchDetails = (variables) => fetch$1({
268
415
  url: "/db/{dbBranchName}",
269
- method: "put",
416
+ method: "get",
270
417
  ...variables
271
418
  });
419
+ const createBranch = (variables) => fetch$1({ url: "/db/{dbBranchName}", method: "put", ...variables });
272
420
  const deleteBranch = (variables) => fetch$1({
273
421
  url: "/db/{dbBranchName}",
274
422
  method: "delete",
@@ -287,6 +435,16 @@ const getBranchMetadata = (variables) => fetch$1({
287
435
  const getBranchMigrationHistory = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables });
288
436
  const executeBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables });
289
437
  const getBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables });
438
+ const compareBranchWithUserSchema = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/compare", method: "post", ...variables });
439
+ const compareBranchSchemas = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/compare/{branchName}", method: "post", ...variables });
440
+ const updateBranchSchema = (variables) => fetch$1({
441
+ url: "/db/{dbBranchName}/schema/update",
442
+ method: "post",
443
+ ...variables
444
+ });
445
+ const previewBranchSchemaEdit = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables });
446
+ const applyBranchSchemaEdit = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables });
447
+ const getBranchSchemaHistory = (variables) => fetch$1({ url: "/db/{dbBranchName}/schema/history", method: "post", ...variables });
290
448
  const getBranchStats = (variables) => fetch$1({
291
449
  url: "/db/{dbBranchName}/stats",
292
450
  method: "get",
@@ -342,11 +500,7 @@ const updateColumn = (variables) => fetch$1({
342
500
  method: "patch",
343
501
  ...variables
344
502
  });
345
- const insertRecord = (variables) => fetch$1({
346
- url: "/db/{dbBranchName}/tables/{tableName}/data",
347
- method: "post",
348
- ...variables
349
- });
503
+ const insertRecord = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables });
350
504
  const insertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables });
351
505
  const updateRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables });
352
506
  const upsertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables });
@@ -388,6 +542,7 @@ const operationsByTag = {
388
542
  updateWorkspaceMemberRole,
389
543
  removeWorkspaceMember,
390
544
  inviteWorkspaceMember,
545
+ updateWorkspaceMemberInvite,
391
546
  cancelWorkspaceMemberInvite,
392
547
  resendWorkspaceMemberInvite,
393
548
  acceptWorkspaceMemberInvite
@@ -396,6 +551,8 @@ const operationsByTag = {
396
551
  getDatabaseList,
397
552
  createDatabase,
398
553
  deleteDatabase,
554
+ getDatabaseMetadata,
555
+ patchDatabaseMetadata,
399
556
  getGitBranchesMapping,
400
557
  addGitBranchesEntry,
401
558
  removeGitBranchesEntry,
@@ -408,10 +565,28 @@ const operationsByTag = {
408
565
  deleteBranch,
409
566
  updateBranchMetadata,
410
567
  getBranchMetadata,
568
+ getBranchStats
569
+ },
570
+ migrationRequests: {
571
+ listMigrationRequests,
572
+ createMigrationRequest,
573
+ getMigrationRequest,
574
+ updateMigrationRequest,
575
+ listMigrationRequestsCommits,
576
+ compareMigrationRequest,
577
+ getMigrationRequestIsMerged,
578
+ mergeMigrationRequest
579
+ },
580
+ branchSchema: {
411
581
  getBranchMigrationHistory,
412
582
  executeBranchMigrationPlan,
413
583
  getBranchMigrationPlan,
414
- getBranchStats
584
+ compareBranchWithUserSchema,
585
+ compareBranchSchemas,
586
+ updateBranchSchema,
587
+ previewBranchSchemaEdit,
588
+ applyBranchSchemaEdit,
589
+ getBranchSchemaHistory
415
590
  },
416
591
  table: {
417
592
  createTable,
@@ -440,9 +615,9 @@ const operationsByTag = {
440
615
  };
441
616
 
442
617
  function getHostUrl(provider, type) {
443
- if (isValidAlias(provider)) {
618
+ if (isHostProviderAlias(provider)) {
444
619
  return providers[provider][type];
445
- } else if (isValidBuilder(provider)) {
620
+ } else if (isHostProviderBuilder(provider)) {
446
621
  return provider[type];
447
622
  }
448
623
  throw new Error("Invalid API provider");
@@ -457,10 +632,10 @@ const providers = {
457
632
  workspaces: "https://{workspaceId}.staging.xatabase.co"
458
633
  }
459
634
  };
460
- function isValidAlias(alias) {
635
+ function isHostProviderAlias(alias) {
461
636
  return isString(alias) && Object.keys(providers).includes(alias);
462
637
  }
463
- function isValidBuilder(builder) {
638
+ function isHostProviderBuilder(builder) {
464
639
  return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
465
640
  }
466
641
 
@@ -477,7 +652,7 @@ var __privateAdd$7 = (obj, member, value) => {
477
652
  throw TypeError("Cannot add the same private member more than once");
478
653
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
479
654
  };
480
- var __privateSet$6 = (obj, member, value, setter) => {
655
+ var __privateSet$7 = (obj, member, value, setter) => {
481
656
  __accessCheck$7(obj, member, "write to private field");
482
657
  setter ? setter.call(obj, value) : member.set(obj, value);
483
658
  return value;
@@ -488,15 +663,17 @@ class XataApiClient {
488
663
  __privateAdd$7(this, _extraProps, void 0);
489
664
  __privateAdd$7(this, _namespaces, {});
490
665
  const provider = options.host ?? "production";
491
- const apiKey = options?.apiKey ?? getAPIKey();
666
+ const apiKey = options.apiKey ?? getAPIKey();
667
+ const trace = options.trace ?? defaultTrace;
492
668
  if (!apiKey) {
493
669
  throw new Error("Could not resolve a valid apiKey");
494
670
  }
495
- __privateSet$6(this, _extraProps, {
671
+ __privateSet$7(this, _extraProps, {
496
672
  apiUrl: getHostUrl(provider, "main"),
497
673
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
498
674
  fetchImpl: getFetchImplementation(options.fetch),
499
- apiKey
675
+ apiKey,
676
+ trace
500
677
  });
501
678
  }
502
679
  get user() {
@@ -529,6 +706,16 @@ class XataApiClient {
529
706
  __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
530
707
  return __privateGet$7(this, _namespaces).records;
531
708
  }
709
+ get migrationRequests() {
710
+ if (!__privateGet$7(this, _namespaces).migrationRequests)
711
+ __privateGet$7(this, _namespaces).migrationRequests = new MigrationRequestsApi(__privateGet$7(this, _extraProps));
712
+ return __privateGet$7(this, _namespaces).migrationRequests;
713
+ }
714
+ get branchSchema() {
715
+ if (!__privateGet$7(this, _namespaces).branchSchema)
716
+ __privateGet$7(this, _namespaces).branchSchema = new BranchSchemaApi(__privateGet$7(this, _extraProps));
717
+ return __privateGet$7(this, _namespaces).branchSchema;
718
+ }
532
719
  }
533
720
  _extraProps = new WeakMap();
534
721
  _namespaces = new WeakMap();
@@ -619,6 +806,13 @@ class WorkspaceApi {
619
806
  ...this.extraProps
620
807
  });
621
808
  }
809
+ updateWorkspaceMemberInvite(workspaceId, inviteId, role) {
810
+ return operationsByTag.workspaces.updateWorkspaceMemberInvite({
811
+ pathParams: { workspaceId, inviteId },
812
+ body: { role },
813
+ ...this.extraProps
814
+ });
815
+ }
622
816
  cancelWorkspaceMemberInvite(workspaceId, inviteId) {
623
817
  return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
624
818
  pathParams: { workspaceId, inviteId },
@@ -661,6 +855,19 @@ class DatabaseApi {
661
855
  ...this.extraProps
662
856
  });
663
857
  }
858
+ getDatabaseMetadata(workspace, dbName) {
859
+ return operationsByTag.database.getDatabaseMetadata({
860
+ pathParams: { workspace, dbName },
861
+ ...this.extraProps
862
+ });
863
+ }
864
+ patchDatabaseMetadata(workspace, dbName, options = {}) {
865
+ return operationsByTag.database.patchDatabaseMetadata({
866
+ pathParams: { workspace, dbName },
867
+ body: options,
868
+ ...this.extraProps
869
+ });
870
+ }
664
871
  getGitBranchesMapping(workspace, dbName) {
665
872
  return operationsByTag.database.getGitBranchesMapping({
666
873
  pathParams: { workspace, dbName },
@@ -681,10 +888,10 @@ class DatabaseApi {
681
888
  ...this.extraProps
682
889
  });
683
890
  }
684
- resolveBranch(workspace, dbName, gitBranch) {
891
+ resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
685
892
  return operationsByTag.database.resolveBranch({
686
893
  pathParams: { workspace, dbName },
687
- queryParams: { gitBranch },
894
+ queryParams: { gitBranch, fallbackBranch },
688
895
  ...this.extraProps
689
896
  });
690
897
  }
@@ -732,27 +939,6 @@ class BranchApi {
732
939
  ...this.extraProps
733
940
  });
734
941
  }
735
- getBranchMigrationHistory(workspace, database, branch, options = {}) {
736
- return operationsByTag.branch.getBranchMigrationHistory({
737
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
738
- body: options,
739
- ...this.extraProps
740
- });
741
- }
742
- executeBranchMigrationPlan(workspace, database, branch, migrationPlan) {
743
- return operationsByTag.branch.executeBranchMigrationPlan({
744
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
745
- body: migrationPlan,
746
- ...this.extraProps
747
- });
748
- }
749
- getBranchMigrationPlan(workspace, database, branch, schema) {
750
- return operationsByTag.branch.getBranchMigrationPlan({
751
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
752
- body: schema,
753
- ...this.extraProps
754
- });
755
- }
756
942
  getBranchStats(workspace, database, branch) {
757
943
  return operationsByTag.branch.getBranchStats({
758
944
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -833,9 +1019,10 @@ class RecordsApi {
833
1019
  constructor(extraProps) {
834
1020
  this.extraProps = extraProps;
835
1021
  }
836
- insertRecord(workspace, database, branch, tableName, record) {
1022
+ insertRecord(workspace, database, branch, tableName, record, options = {}) {
837
1023
  return operationsByTag.records.insertRecord({
838
1024
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1025
+ queryParams: options,
839
1026
  body: record,
840
1027
  ...this.extraProps
841
1028
  });
@@ -864,21 +1051,24 @@ class RecordsApi {
864
1051
  ...this.extraProps
865
1052
  });
866
1053
  }
867
- deleteRecord(workspace, database, branch, tableName, recordId) {
1054
+ deleteRecord(workspace, database, branch, tableName, recordId, options = {}) {
868
1055
  return operationsByTag.records.deleteRecord({
869
1056
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1057
+ queryParams: options,
870
1058
  ...this.extraProps
871
1059
  });
872
1060
  }
873
1061
  getRecord(workspace, database, branch, tableName, recordId, options = {}) {
874
1062
  return operationsByTag.records.getRecord({
875
1063
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1064
+ queryParams: options,
876
1065
  ...this.extraProps
877
1066
  });
878
1067
  }
879
- bulkInsertTableRecords(workspace, database, branch, tableName, records) {
1068
+ bulkInsertTableRecords(workspace, database, branch, tableName, records, options = {}) {
880
1069
  return operationsByTag.records.bulkInsertTableRecords({
881
1070
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1071
+ queryParams: options,
882
1072
  body: { records },
883
1073
  ...this.extraProps
884
1074
  });
@@ -905,6 +1095,131 @@ class RecordsApi {
905
1095
  });
906
1096
  }
907
1097
  }
1098
+ class MigrationRequestsApi {
1099
+ constructor(extraProps) {
1100
+ this.extraProps = extraProps;
1101
+ }
1102
+ listMigrationRequests(workspace, database, options = {}) {
1103
+ return operationsByTag.migrationRequests.listMigrationRequests({
1104
+ pathParams: { workspace, dbName: database },
1105
+ body: options,
1106
+ ...this.extraProps
1107
+ });
1108
+ }
1109
+ createMigrationRequest(workspace, database, options) {
1110
+ return operationsByTag.migrationRequests.createMigrationRequest({
1111
+ pathParams: { workspace, dbName: database },
1112
+ body: options,
1113
+ ...this.extraProps
1114
+ });
1115
+ }
1116
+ getMigrationRequest(workspace, database, migrationRequest) {
1117
+ return operationsByTag.migrationRequests.getMigrationRequest({
1118
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1119
+ ...this.extraProps
1120
+ });
1121
+ }
1122
+ updateMigrationRequest(workspace, database, migrationRequest, options) {
1123
+ return operationsByTag.migrationRequests.updateMigrationRequest({
1124
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1125
+ body: options,
1126
+ ...this.extraProps
1127
+ });
1128
+ }
1129
+ listMigrationRequestsCommits(workspace, database, migrationRequest, options = {}) {
1130
+ return operationsByTag.migrationRequests.listMigrationRequestsCommits({
1131
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1132
+ body: options,
1133
+ ...this.extraProps
1134
+ });
1135
+ }
1136
+ compareMigrationRequest(workspace, database, migrationRequest) {
1137
+ return operationsByTag.migrationRequests.compareMigrationRequest({
1138
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1139
+ ...this.extraProps
1140
+ });
1141
+ }
1142
+ getMigrationRequestIsMerged(workspace, database, migrationRequest) {
1143
+ return operationsByTag.migrationRequests.getMigrationRequestIsMerged({
1144
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1145
+ ...this.extraProps
1146
+ });
1147
+ }
1148
+ mergeMigrationRequest(workspace, database, migrationRequest) {
1149
+ return operationsByTag.migrationRequests.mergeMigrationRequest({
1150
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1151
+ ...this.extraProps
1152
+ });
1153
+ }
1154
+ }
1155
+ class BranchSchemaApi {
1156
+ constructor(extraProps) {
1157
+ this.extraProps = extraProps;
1158
+ }
1159
+ getBranchMigrationHistory(workspace, database, branch, options = {}) {
1160
+ return operationsByTag.branchSchema.getBranchMigrationHistory({
1161
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1162
+ body: options,
1163
+ ...this.extraProps
1164
+ });
1165
+ }
1166
+ executeBranchMigrationPlan(workspace, database, branch, migrationPlan) {
1167
+ return operationsByTag.branchSchema.executeBranchMigrationPlan({
1168
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1169
+ body: migrationPlan,
1170
+ ...this.extraProps
1171
+ });
1172
+ }
1173
+ getBranchMigrationPlan(workspace, database, branch, schema) {
1174
+ return operationsByTag.branchSchema.getBranchMigrationPlan({
1175
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1176
+ body: schema,
1177
+ ...this.extraProps
1178
+ });
1179
+ }
1180
+ compareBranchWithUserSchema(workspace, database, branch, schema) {
1181
+ return operationsByTag.branchSchema.compareBranchWithUserSchema({
1182
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1183
+ body: { schema },
1184
+ ...this.extraProps
1185
+ });
1186
+ }
1187
+ compareBranchSchemas(workspace, database, branch, branchName, schema) {
1188
+ return operationsByTag.branchSchema.compareBranchSchemas({
1189
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, branchName },
1190
+ body: { schema },
1191
+ ...this.extraProps
1192
+ });
1193
+ }
1194
+ updateBranchSchema(workspace, database, branch, migration) {
1195
+ return operationsByTag.branchSchema.updateBranchSchema({
1196
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1197
+ body: migration,
1198
+ ...this.extraProps
1199
+ });
1200
+ }
1201
+ previewBranchSchemaEdit(workspace, database, branch, migration) {
1202
+ return operationsByTag.branchSchema.previewBranchSchemaEdit({
1203
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1204
+ body: migration,
1205
+ ...this.extraProps
1206
+ });
1207
+ }
1208
+ applyBranchSchemaEdit(workspace, database, branch, edits) {
1209
+ return operationsByTag.branchSchema.applyBranchSchemaEdit({
1210
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1211
+ body: { edits },
1212
+ ...this.extraProps
1213
+ });
1214
+ }
1215
+ getBranchSchemaHistory(workspace, database, branch, options = {}) {
1216
+ return operationsByTag.branchSchema.getBranchSchemaHistory({
1217
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1218
+ body: options,
1219
+ ...this.extraProps
1220
+ });
1221
+ }
1222
+ }
908
1223
 
909
1224
  class XataApiPlugin {
910
1225
  async build(options) {
@@ -929,18 +1244,18 @@ var __privateAdd$6 = (obj, member, value) => {
929
1244
  throw TypeError("Cannot add the same private member more than once");
930
1245
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
931
1246
  };
932
- var __privateSet$5 = (obj, member, value, setter) => {
1247
+ var __privateSet$6 = (obj, member, value, setter) => {
933
1248
  __accessCheck$6(obj, member, "write to private field");
934
1249
  setter ? setter.call(obj, value) : member.set(obj, value);
935
1250
  return value;
936
1251
  };
937
- var _query;
1252
+ var _query, _page;
938
1253
  class Page {
939
1254
  constructor(query, meta, records = []) {
940
1255
  __privateAdd$6(this, _query, void 0);
941
- __privateSet$5(this, _query, query);
1256
+ __privateSet$6(this, _query, query);
942
1257
  this.meta = meta;
943
- this.records = records;
1258
+ this.records = new RecordArray(this, records);
944
1259
  }
945
1260
  async nextPage(size, offset) {
946
1261
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
@@ -960,9 +1275,56 @@ class Page {
960
1275
  }
961
1276
  _query = new WeakMap();
962
1277
  const PAGINATION_MAX_SIZE = 200;
963
- const PAGINATION_DEFAULT_SIZE = 200;
1278
+ const PAGINATION_DEFAULT_SIZE = 20;
964
1279
  const PAGINATION_MAX_OFFSET = 800;
965
1280
  const PAGINATION_DEFAULT_OFFSET = 0;
1281
+ function isCursorPaginationOptions(options) {
1282
+ return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
1283
+ }
1284
+ const _RecordArray = class extends Array {
1285
+ constructor(...args) {
1286
+ super(..._RecordArray.parseConstructorParams(...args));
1287
+ __privateAdd$6(this, _page, void 0);
1288
+ __privateSet$6(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
1289
+ }
1290
+ static parseConstructorParams(...args) {
1291
+ if (args.length === 1 && typeof args[0] === "number") {
1292
+ return new Array(args[0]);
1293
+ }
1294
+ if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
1295
+ const result = args[1] ?? args[0].records ?? [];
1296
+ return new Array(...result);
1297
+ }
1298
+ return new Array(...args);
1299
+ }
1300
+ toArray() {
1301
+ return new Array(...this);
1302
+ }
1303
+ map(callbackfn, thisArg) {
1304
+ return this.toArray().map(callbackfn, thisArg);
1305
+ }
1306
+ async nextPage(size, offset) {
1307
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1308
+ return new _RecordArray(newPage);
1309
+ }
1310
+ async previousPage(size, offset) {
1311
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1312
+ return new _RecordArray(newPage);
1313
+ }
1314
+ async firstPage(size, offset) {
1315
+ const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1316
+ return new _RecordArray(newPage);
1317
+ }
1318
+ async lastPage(size, offset) {
1319
+ const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1320
+ return new _RecordArray(newPage);
1321
+ }
1322
+ hasNextPage() {
1323
+ return __privateGet$6(this, _page).meta.page.more;
1324
+ }
1325
+ };
1326
+ let RecordArray = _RecordArray;
1327
+ _page = new WeakMap();
966
1328
 
967
1329
  var __accessCheck$5 = (obj, member, msg) => {
968
1330
  if (!member.has(obj))
@@ -977,25 +1339,26 @@ var __privateAdd$5 = (obj, member, value) => {
977
1339
  throw TypeError("Cannot add the same private member more than once");
978
1340
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
979
1341
  };
980
- var __privateSet$4 = (obj, member, value, setter) => {
1342
+ var __privateSet$5 = (obj, member, value, setter) => {
981
1343
  __accessCheck$5(obj, member, "write to private field");
982
1344
  setter ? setter.call(obj, value) : member.set(obj, value);
983
1345
  return value;
984
1346
  };
985
1347
  var _table$1, _repository, _data;
986
1348
  const _Query = class {
987
- constructor(repository, table, data, parent) {
1349
+ constructor(repository, table, data, rawParent) {
988
1350
  __privateAdd$5(this, _table$1, void 0);
989
1351
  __privateAdd$5(this, _repository, void 0);
990
1352
  __privateAdd$5(this, _data, { filter: {} });
991
1353
  this.meta = { page: { cursor: "start", more: true } };
992
- this.records = [];
993
- __privateSet$4(this, _table$1, table);
1354
+ this.records = new RecordArray(this, []);
1355
+ __privateSet$5(this, _table$1, table);
994
1356
  if (repository) {
995
- __privateSet$4(this, _repository, repository);
1357
+ __privateSet$5(this, _repository, repository);
996
1358
  } else {
997
- __privateSet$4(this, _repository, this);
1359
+ __privateSet$5(this, _repository, this);
998
1360
  }
1361
+ const parent = cleanParent(data, rawParent);
999
1362
  __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
1000
1363
  __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
1001
1364
  __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
@@ -1040,21 +1403,34 @@ const _Query = class {
1040
1403
  }
1041
1404
  filter(a, b) {
1042
1405
  if (arguments.length === 1) {
1043
- const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
1406
+ const constraints = Object.entries(a ?? {}).map(([column, constraint]) => ({ [column]: constraint }));
1044
1407
  const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1045
1408
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1046
1409
  } else {
1047
- const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
1410
+ const constraints = isDefined(a) && isDefined(b) ? [{ [a]: this.defaultFilter(a, b) }] : void 0;
1411
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1048
1412
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1049
1413
  }
1050
1414
  }
1051
- sort(column, direction) {
1415
+ defaultFilter(column, value) {
1416
+ const columnType = __privateGet$5(this, _table$1).schema?.columns.find(({ name }) => name === column)?.type;
1417
+ if (columnType === "multiple" && (isString(value) || isStringArray(value))) {
1418
+ return { $includes: value };
1419
+ }
1420
+ return value;
1421
+ }
1422
+ sort(column, direction = "asc") {
1052
1423
  const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
1053
1424
  const sort = [...originalSort, { column, direction }];
1054
1425
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
1055
1426
  }
1056
1427
  select(columns) {
1057
- return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { columns }, __privateGet$5(this, _data));
1428
+ return new _Query(
1429
+ __privateGet$5(this, _repository),
1430
+ __privateGet$5(this, _table$1),
1431
+ { columns },
1432
+ __privateGet$5(this, _data)
1433
+ );
1058
1434
  }
1059
1435
  getPaginated(options = {}) {
1060
1436
  const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
@@ -1067,18 +1443,21 @@ const _Query = class {
1067
1443
  }
1068
1444
  async *getIterator(options = {}) {
1069
1445
  const { batchSize = 1 } = options;
1070
- let offset = 0;
1071
- let end = false;
1072
- while (!end) {
1073
- const { records, meta } = await this.getPaginated({ ...options, pagination: { size: batchSize, offset } });
1074
- yield records;
1075
- offset += batchSize;
1076
- end = !meta.page.more;
1446
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
1447
+ let more = page.hasNextPage();
1448
+ yield page.records;
1449
+ while (more) {
1450
+ page = await page.nextPage();
1451
+ more = page.hasNextPage();
1452
+ yield page.records;
1077
1453
  }
1078
1454
  }
1079
1455
  async getMany(options = {}) {
1080
- const { records } = await this.getPaginated(options);
1081
- return records;
1456
+ const page = await this.getPaginated(options);
1457
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1458
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1459
+ }
1460
+ return page.records;
1082
1461
  }
1083
1462
  async getAll(options = {}) {
1084
1463
  const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
@@ -1115,12 +1494,20 @@ let Query = _Query;
1115
1494
  _table$1 = new WeakMap();
1116
1495
  _repository = new WeakMap();
1117
1496
  _data = new WeakMap();
1497
+ function cleanParent(data, parent) {
1498
+ if (isCursorPaginationOptions(data.pagination)) {
1499
+ return { ...parent, sorting: void 0, filter: void 0 };
1500
+ }
1501
+ return parent;
1502
+ }
1118
1503
 
1119
1504
  function isIdentifiable(x) {
1120
1505
  return isObject(x) && isString(x?.id);
1121
1506
  }
1122
1507
  function isXataRecord(x) {
1123
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1508
+ const record = x;
1509
+ const metadata = record?.getMetadata();
1510
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1124
1511
  }
1125
1512
 
1126
1513
  function isSortFilterString(value) {
@@ -1159,7 +1546,7 @@ var __privateAdd$4 = (obj, member, value) => {
1159
1546
  throw TypeError("Cannot add the same private member more than once");
1160
1547
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1161
1548
  };
1162
- var __privateSet$3 = (obj, member, value, setter) => {
1549
+ var __privateSet$4 = (obj, member, value, setter) => {
1163
1550
  __accessCheck$4(obj, member, "write to private field");
1164
1551
  setter ? setter.call(obj, value) : member.set(obj, value);
1165
1552
  return value;
@@ -1168,184 +1555,228 @@ var __privateMethod$2 = (obj, member, method) => {
1168
1555
  __accessCheck$4(obj, member, "access private method");
1169
1556
  return method;
1170
1557
  };
1171
- var _table, _getFetchProps, _cache, _schema$1, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _invalidateCache, invalidateCache_fn, _setCacheRecord, setCacheRecord_fn, _getCacheRecord, getCacheRecord_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchema$1, getSchema_fn$1;
1558
+ 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;
1172
1559
  class Repository extends Query {
1173
1560
  }
1174
1561
  class RestRepository extends Query {
1175
1562
  constructor(options) {
1176
- super(null, options.table, {});
1563
+ super(
1564
+ null,
1565
+ { name: options.table, schema: options.schemaTables?.find((table) => table.name === options.table) },
1566
+ {}
1567
+ );
1177
1568
  __privateAdd$4(this, _insertRecordWithoutId);
1178
1569
  __privateAdd$4(this, _insertRecordWithId);
1179
1570
  __privateAdd$4(this, _bulkInsertTableRecords);
1180
1571
  __privateAdd$4(this, _updateRecordWithID);
1181
1572
  __privateAdd$4(this, _upsertRecordWithID);
1182
1573
  __privateAdd$4(this, _deleteRecord);
1183
- __privateAdd$4(this, _invalidateCache);
1184
- __privateAdd$4(this, _setCacheRecord);
1185
- __privateAdd$4(this, _getCacheRecord);
1186
1574
  __privateAdd$4(this, _setCacheQuery);
1187
1575
  __privateAdd$4(this, _getCacheQuery);
1188
- __privateAdd$4(this, _getSchema$1);
1576
+ __privateAdd$4(this, _getSchemaTables$1);
1189
1577
  __privateAdd$4(this, _table, void 0);
1190
1578
  __privateAdd$4(this, _getFetchProps, void 0);
1579
+ __privateAdd$4(this, _db, void 0);
1191
1580
  __privateAdd$4(this, _cache, void 0);
1192
- __privateAdd$4(this, _schema$1, void 0);
1193
- __privateSet$3(this, _table, options.table);
1194
- __privateSet$3(this, _getFetchProps, options.pluginOptions.getFetchProps);
1195
- this.db = options.db;
1196
- __privateSet$3(this, _cache, options.pluginOptions.cache);
1197
- }
1198
- async create(a, b) {
1199
- if (Array.isArray(a)) {
1200
- const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1201
- await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1202
- return records;
1203
- }
1204
- if (isString(a) && isObject(b)) {
1205
- if (a === "")
1206
- throw new Error("The id can't be empty");
1207
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1208
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1209
- return record;
1210
- }
1211
- if (isObject(a) && isString(a.id)) {
1212
- if (a.id === "")
1213
- throw new Error("The id can't be empty");
1214
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1215
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1216
- return record;
1217
- }
1218
- if (isObject(a)) {
1219
- const record = await __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1220
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1221
- return record;
1222
- }
1223
- throw new Error("Invalid arguments for create method");
1224
- }
1225
- async read(recordId) {
1226
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, recordId);
1227
- if (cacheRecord)
1228
- return cacheRecord;
1229
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1230
- try {
1231
- const response = await getRecord({
1232
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1233
- ...fetchProps
1581
+ __privateAdd$4(this, _schemaTables$2, void 0);
1582
+ __privateAdd$4(this, _trace, void 0);
1583
+ __privateSet$4(this, _table, options.table);
1584
+ __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1585
+ __privateSet$4(this, _db, options.db);
1586
+ __privateSet$4(this, _cache, options.pluginOptions.cache);
1587
+ __privateSet$4(this, _schemaTables$2, options.schemaTables);
1588
+ const trace = options.pluginOptions.trace ?? defaultTrace;
1589
+ __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
1590
+ return trace(name, fn, {
1591
+ ...options2,
1592
+ [TraceAttributes.TABLE]: __privateGet$4(this, _table),
1593
+ [TraceAttributes.KIND]: "sdk-operation",
1594
+ [TraceAttributes.VERSION]: VERSION
1234
1595
  });
1235
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1236
- return initObject(this.db, schema, __privateGet$4(this, _table), response);
1237
- } catch (e) {
1238
- if (isObject(e) && e.status === 404) {
1239
- return null;
1596
+ });
1597
+ }
1598
+ async create(a, b, c) {
1599
+ return __privateGet$4(this, _trace).call(this, "create", async () => {
1600
+ if (Array.isArray(a)) {
1601
+ if (a.length === 0)
1602
+ return [];
1603
+ const columns = isStringArray(b) ? b : void 0;
1604
+ return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
1240
1605
  }
1241
- throw e;
1242
- }
1606
+ if (isString(a) && isObject(b)) {
1607
+ if (a === "")
1608
+ throw new Error("The id can't be empty");
1609
+ const columns = isStringArray(c) ? c : void 0;
1610
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns);
1611
+ }
1612
+ if (isObject(a) && isString(a.id)) {
1613
+ if (a.id === "")
1614
+ throw new Error("The id can't be empty");
1615
+ const columns = isStringArray(b) ? b : void 0;
1616
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1617
+ }
1618
+ if (isObject(a)) {
1619
+ const columns = isStringArray(b) ? b : void 0;
1620
+ return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
1621
+ }
1622
+ throw new Error("Invalid arguments for create method");
1623
+ });
1243
1624
  }
1244
- async update(a, b) {
1245
- if (Array.isArray(a)) {
1246
- if (a.length > 100) {
1247
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1625
+ async read(a, b) {
1626
+ return __privateGet$4(this, _trace).call(this, "read", async () => {
1627
+ const columns = isStringArray(b) ? b : ["*"];
1628
+ if (Array.isArray(a)) {
1629
+ if (a.length === 0)
1630
+ return [];
1631
+ const ids = a.map((item) => extractId(item));
1632
+ const finalObjects = await this.getAll({ filter: { id: { $any: compact(ids) } }, columns });
1633
+ const dictionary = finalObjects.reduce((acc, object) => {
1634
+ acc[object.id] = object;
1635
+ return acc;
1636
+ }, {});
1637
+ return ids.map((id2) => dictionary[id2 ?? ""] ?? null);
1248
1638
  }
1249
- return Promise.all(a.map((object) => this.update(object)));
1250
- }
1251
- if (isString(a) && isObject(b)) {
1252
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1253
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1254
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1255
- return record;
1256
- }
1257
- if (isObject(a) && isString(a.id)) {
1258
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1259
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1260
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1261
- return record;
1262
- }
1263
- throw new Error("Invalid arguments for update method");
1639
+ const id = extractId(a);
1640
+ if (id) {
1641
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1642
+ try {
1643
+ const response = await getRecord({
1644
+ pathParams: {
1645
+ workspace: "{workspaceId}",
1646
+ dbBranchName: "{dbBranch}",
1647
+ tableName: __privateGet$4(this, _table),
1648
+ recordId: id
1649
+ },
1650
+ queryParams: { columns },
1651
+ ...fetchProps
1652
+ });
1653
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1654
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1655
+ } catch (e) {
1656
+ if (isObject(e) && e.status === 404) {
1657
+ return null;
1658
+ }
1659
+ throw e;
1660
+ }
1661
+ }
1662
+ return null;
1663
+ });
1264
1664
  }
1265
- async createOrUpdate(a, b) {
1266
- if (Array.isArray(a)) {
1267
- if (a.length > 100) {
1268
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1665
+ async update(a, b, c) {
1666
+ return __privateGet$4(this, _trace).call(this, "update", async () => {
1667
+ if (Array.isArray(a)) {
1668
+ if (a.length === 0)
1669
+ return [];
1670
+ if (a.length > 100) {
1671
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1672
+ }
1673
+ const columns = isStringArray(b) ? b : ["*"];
1674
+ return Promise.all(a.map((object) => this.update(object, columns)));
1269
1675
  }
1270
- return Promise.all(a.map((object) => this.createOrUpdate(object)));
1271
- }
1272
- if (isString(a) && isObject(b)) {
1273
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1274
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1275
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1276
- return record;
1277
- }
1278
- if (isObject(a) && isString(a.id)) {
1279
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1280
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1281
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1282
- return record;
1283
- }
1284
- throw new Error("Invalid arguments for createOrUpdate method");
1676
+ if (isString(a) && isObject(b)) {
1677
+ const columns = isStringArray(c) ? c : void 0;
1678
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns);
1679
+ }
1680
+ if (isObject(a) && isString(a.id)) {
1681
+ const columns = isStringArray(b) ? b : void 0;
1682
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1683
+ }
1684
+ throw new Error("Invalid arguments for update method");
1685
+ });
1285
1686
  }
1286
- async delete(a) {
1287
- if (Array.isArray(a)) {
1288
- if (a.length > 100) {
1289
- console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1687
+ async createOrUpdate(a, b, c) {
1688
+ return __privateGet$4(this, _trace).call(this, "createOrUpdate", async () => {
1689
+ if (Array.isArray(a)) {
1690
+ if (a.length === 0)
1691
+ return [];
1692
+ if (a.length > 100) {
1693
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1694
+ }
1695
+ const columns = isStringArray(b) ? b : ["*"];
1696
+ return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
1290
1697
  }
1291
- await Promise.all(a.map((id) => this.delete(id)));
1292
- return;
1293
- }
1294
- if (isString(a)) {
1295
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1296
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1297
- return;
1298
- }
1299
- if (isObject(a) && isString(a.id)) {
1300
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1301
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1302
- return;
1303
- }
1304
- throw new Error("Invalid arguments for delete method");
1698
+ if (isString(a) && isObject(b)) {
1699
+ const columns = isStringArray(c) ? c : void 0;
1700
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns);
1701
+ }
1702
+ if (isObject(a) && isString(a.id)) {
1703
+ const columns = isStringArray(c) ? c : void 0;
1704
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1705
+ }
1706
+ throw new Error("Invalid arguments for createOrUpdate method");
1707
+ });
1708
+ }
1709
+ async delete(a, b) {
1710
+ return __privateGet$4(this, _trace).call(this, "delete", async () => {
1711
+ if (Array.isArray(a)) {
1712
+ if (a.length === 0)
1713
+ return [];
1714
+ if (a.length > 100) {
1715
+ console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1716
+ }
1717
+ return Promise.all(a.map((id) => this.delete(id, b)));
1718
+ }
1719
+ if (isString(a)) {
1720
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
1721
+ }
1722
+ if (isObject(a) && isString(a.id)) {
1723
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id, b);
1724
+ }
1725
+ throw new Error("Invalid arguments for delete method");
1726
+ });
1305
1727
  }
1306
1728
  async search(query, options = {}) {
1307
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1308
- const { records } = await searchTable({
1309
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1310
- body: {
1311
- query,
1312
- fuzziness: options.fuzziness,
1313
- filter: options.filter
1314
- },
1315
- ...fetchProps
1729
+ return __privateGet$4(this, _trace).call(this, "search", async () => {
1730
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1731
+ const { records } = await searchTable({
1732
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1733
+ body: {
1734
+ query,
1735
+ fuzziness: options.fuzziness,
1736
+ prefix: options.prefix,
1737
+ highlight: options.highlight,
1738
+ filter: options.filter,
1739
+ boosters: options.boosters
1740
+ },
1741
+ ...fetchProps
1742
+ });
1743
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1744
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1316
1745
  });
1317
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1318
- return records.map((item) => initObject(this.db, schema, __privateGet$4(this, _table), item));
1319
1746
  }
1320
1747
  async query(query) {
1321
- const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1322
- if (cacheQuery)
1323
- return new Page(query, cacheQuery.meta, cacheQuery.records);
1324
- const data = query.getQueryOptions();
1325
- const body = {
1326
- filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1327
- sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1328
- page: data.pagination,
1329
- columns: data.columns
1330
- };
1331
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1332
- const { meta, records: objects } = await queryTable({
1333
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1334
- body,
1335
- ...fetchProps
1748
+ return __privateGet$4(this, _trace).call(this, "query", async () => {
1749
+ const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1750
+ if (cacheQuery)
1751
+ return new Page(query, cacheQuery.meta, cacheQuery.records);
1752
+ const data = query.getQueryOptions();
1753
+ const body = {
1754
+ filter: cleanFilter(data.filter),
1755
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1756
+ page: data.pagination,
1757
+ columns: data.columns
1758
+ };
1759
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1760
+ const { meta, records: objects } = await queryTable({
1761
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1762
+ body,
1763
+ ...fetchProps
1764
+ });
1765
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1766
+ const records = objects.map((record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record));
1767
+ await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1768
+ return new Page(query, meta, records);
1336
1769
  });
1337
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1338
- const records = objects.map((record) => initObject(this.db, schema, __privateGet$4(this, _table), record));
1339
- await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1340
- return new Page(query, meta, records);
1341
1770
  }
1342
1771
  }
1343
1772
  _table = new WeakMap();
1344
1773
  _getFetchProps = new WeakMap();
1774
+ _db = new WeakMap();
1345
1775
  _cache = new WeakMap();
1346
- _schema$1 = new WeakMap();
1776
+ _schemaTables$2 = new WeakMap();
1777
+ _trace = new WeakMap();
1347
1778
  _insertRecordWithoutId = new WeakSet();
1348
- insertRecordWithoutId_fn = async function(object) {
1779
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1349
1780
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1350
1781
  const record = transformObjectLinks(object);
1351
1782
  const response = await insertRecord({
@@ -1354,17 +1785,15 @@ insertRecordWithoutId_fn = async function(object) {
1354
1785
  dbBranchName: "{dbBranch}",
1355
1786
  tableName: __privateGet$4(this, _table)
1356
1787
  },
1788
+ queryParams: { columns },
1357
1789
  body: record,
1358
1790
  ...fetchProps
1359
1791
  });
1360
- const finalObject = await this.read(response.id);
1361
- if (!finalObject) {
1362
- throw new Error("The server failed to save the record");
1363
- }
1364
- return finalObject;
1792
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1793
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1365
1794
  };
1366
1795
  _insertRecordWithId = new WeakSet();
1367
- insertRecordWithId_fn = async function(recordId, object) {
1796
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
1368
1797
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1369
1798
  const record = transformObjectLinks(object);
1370
1799
  const response = await insertRecordWithID({
@@ -1375,88 +1804,78 @@ insertRecordWithId_fn = async function(recordId, object) {
1375
1804
  recordId
1376
1805
  },
1377
1806
  body: record,
1378
- queryParams: { createOnly: true },
1807
+ queryParams: { createOnly: true, columns },
1379
1808
  ...fetchProps
1380
1809
  });
1381
- const finalObject = await this.read(response.id);
1382
- if (!finalObject) {
1383
- throw new Error("The server failed to save the record");
1384
- }
1385
- return finalObject;
1810
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1811
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1386
1812
  };
1387
1813
  _bulkInsertTableRecords = new WeakSet();
1388
- bulkInsertTableRecords_fn = async function(objects) {
1814
+ bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
1389
1815
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1390
1816
  const records = objects.map((object) => transformObjectLinks(object));
1391
1817
  const response = await bulkInsertTableRecords({
1392
1818
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1819
+ queryParams: { columns },
1393
1820
  body: { records },
1394
1821
  ...fetchProps
1395
1822
  });
1396
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1397
- if (finalObjects.length !== objects.length) {
1398
- throw new Error("The server failed to save some records");
1823
+ if (!isResponseWithRecords(response)) {
1824
+ throw new Error("Request included columns but server didn't include them");
1399
1825
  }
1400
- return finalObjects;
1826
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1827
+ return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1401
1828
  };
1402
1829
  _updateRecordWithID = new WeakSet();
1403
- updateRecordWithID_fn = async function(recordId, object) {
1830
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1404
1831
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1405
1832
  const record = transformObjectLinks(object);
1406
- const response = await updateRecordWithID({
1407
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1408
- body: record,
1409
- ...fetchProps
1410
- });
1411
- const item = await this.read(response.id);
1412
- if (!item)
1413
- throw new Error("The server failed to save the record");
1414
- return item;
1833
+ try {
1834
+ const response = await updateRecordWithID({
1835
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1836
+ queryParams: { columns },
1837
+ body: record,
1838
+ ...fetchProps
1839
+ });
1840
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1841
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1842
+ } catch (e) {
1843
+ if (isObject(e) && e.status === 404) {
1844
+ return null;
1845
+ }
1846
+ throw e;
1847
+ }
1415
1848
  };
1416
1849
  _upsertRecordWithID = new WeakSet();
1417
- upsertRecordWithID_fn = async function(recordId, object) {
1850
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1418
1851
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1419
1852
  const response = await upsertRecordWithID({
1420
1853
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1854
+ queryParams: { columns },
1421
1855
  body: object,
1422
1856
  ...fetchProps
1423
1857
  });
1424
- const item = await this.read(response.id);
1425
- if (!item)
1426
- throw new Error("The server failed to save the record");
1427
- return item;
1858
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1859
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1428
1860
  };
1429
1861
  _deleteRecord = new WeakSet();
1430
- deleteRecord_fn = async function(recordId) {
1862
+ deleteRecord_fn = async function(recordId, columns = ["*"]) {
1431
1863
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1432
- await deleteRecord({
1433
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1434
- ...fetchProps
1435
- });
1436
- };
1437
- _invalidateCache = new WeakSet();
1438
- invalidateCache_fn = async function(recordId) {
1439
- await __privateGet$4(this, _cache).delete(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1440
- const cacheItems = await __privateGet$4(this, _cache).getAll();
1441
- const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1442
- for (const [key, value] of queries) {
1443
- const ids = getIds(value);
1444
- if (ids.includes(recordId))
1445
- await __privateGet$4(this, _cache).delete(key);
1864
+ try {
1865
+ const response = await deleteRecord({
1866
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1867
+ queryParams: { columns },
1868
+ ...fetchProps
1869
+ });
1870
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1871
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1872
+ } catch (e) {
1873
+ if (isObject(e) && e.status === 404) {
1874
+ return null;
1875
+ }
1876
+ throw e;
1446
1877
  }
1447
1878
  };
1448
- _setCacheRecord = new WeakSet();
1449
- setCacheRecord_fn = async function(record) {
1450
- if (!__privateGet$4(this, _cache).cacheRecords)
1451
- return;
1452
- await __privateGet$4(this, _cache).set(`rec_${__privateGet$4(this, _table)}:${record.id}`, record);
1453
- };
1454
- _getCacheRecord = new WeakSet();
1455
- getCacheRecord_fn = async function(recordId) {
1456
- if (!__privateGet$4(this, _cache).cacheRecords)
1457
- return null;
1458
- return __privateGet$4(this, _cache).get(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1459
- };
1460
1879
  _setCacheQuery = new WeakSet();
1461
1880
  setCacheQuery_fn = async function(query, meta, records) {
1462
1881
  await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
@@ -1473,17 +1892,17 @@ getCacheQuery_fn = async function(query) {
1473
1892
  const hasExpired = result.date.getTime() + ttl < Date.now();
1474
1893
  return hasExpired ? null : result;
1475
1894
  };
1476
- _getSchema$1 = new WeakSet();
1477
- getSchema_fn$1 = async function() {
1478
- if (__privateGet$4(this, _schema$1))
1479
- return __privateGet$4(this, _schema$1);
1895
+ _getSchemaTables$1 = new WeakSet();
1896
+ getSchemaTables_fn$1 = async function() {
1897
+ if (__privateGet$4(this, _schemaTables$2))
1898
+ return __privateGet$4(this, _schemaTables$2);
1480
1899
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1481
1900
  const { schema } = await getBranchDetails({
1482
1901
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1483
1902
  ...fetchProps
1484
1903
  });
1485
- __privateSet$3(this, _schema$1, schema);
1486
- return schema;
1904
+ __privateSet$4(this, _schemaTables$2, schema.tables);
1905
+ return schema.tables;
1487
1906
  };
1488
1907
  const transformObjectLinks = (object) => {
1489
1908
  return Object.entries(object).reduce((acc, [key, value]) => {
@@ -1492,20 +1911,21 @@ const transformObjectLinks = (object) => {
1492
1911
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1493
1912
  }, {});
1494
1913
  };
1495
- const initObject = (db, schema, table, object) => {
1914
+ const initObject = (db, schemaTables, table, object) => {
1496
1915
  const result = {};
1497
- Object.assign(result, object);
1498
- const { columns } = schema.tables.find(({ name }) => name === table) ?? {};
1916
+ const { xata, ...rest } = object ?? {};
1917
+ Object.assign(result, rest);
1918
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
1499
1919
  if (!columns)
1500
1920
  console.error(`Table ${table} not found in schema`);
1501
1921
  for (const column of columns ?? []) {
1502
1922
  const value = result[column.name];
1503
1923
  switch (column.type) {
1504
1924
  case "datetime": {
1505
- const date = new Date(value);
1506
- if (isNaN(date.getTime())) {
1925
+ const date = value !== void 0 ? new Date(value) : void 0;
1926
+ if (date && isNaN(date.getTime())) {
1507
1927
  console.error(`Failed to parse date ${value} for field ${column.name}`);
1508
- } else {
1928
+ } else if (date) {
1509
1929
  result[column.name] = date;
1510
1930
  }
1511
1931
  break;
@@ -1515,35 +1935,45 @@ const initObject = (db, schema, table, object) => {
1515
1935
  if (!linkTable) {
1516
1936
  console.error(`Failed to parse link for field ${column.name}`);
1517
1937
  } else if (isObject(value)) {
1518
- result[column.name] = initObject(db, schema, linkTable, value);
1938
+ result[column.name] = initObject(db, schemaTables, linkTable, value);
1519
1939
  }
1520
1940
  break;
1521
1941
  }
1522
1942
  }
1523
1943
  }
1524
- result.read = function() {
1525
- return db[table].read(result["id"]);
1944
+ result.read = function(columns2) {
1945
+ return db[table].read(result["id"], columns2);
1526
1946
  };
1527
- result.update = function(data) {
1528
- return db[table].update(result["id"], data);
1947
+ result.update = function(data, columns2) {
1948
+ return db[table].update(result["id"], data, columns2);
1529
1949
  };
1530
1950
  result.delete = function() {
1531
1951
  return db[table].delete(result["id"]);
1532
1952
  };
1533
- for (const prop of ["read", "update", "delete"]) {
1953
+ result.getMetadata = function() {
1954
+ return xata;
1955
+ };
1956
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1534
1957
  Object.defineProperty(result, prop, { enumerable: false });
1535
1958
  }
1536
1959
  Object.freeze(result);
1537
1960
  return result;
1538
1961
  };
1539
- function getIds(value) {
1540
- if (Array.isArray(value)) {
1541
- return value.map((item) => getIds(item)).flat();
1542
- }
1543
- if (!isObject(value))
1544
- return [];
1545
- const nestedIds = Object.values(value).map((item) => getIds(item)).flat();
1546
- return isString(value.id) ? [value.id, ...nestedIds] : nestedIds;
1962
+ function isResponseWithRecords(value) {
1963
+ return isObject(value) && Array.isArray(value.records);
1964
+ }
1965
+ function extractId(value) {
1966
+ if (isString(value))
1967
+ return value;
1968
+ if (isObject(value) && isString(value.id))
1969
+ return value.id;
1970
+ return void 0;
1971
+ }
1972
+ function cleanFilter(filter) {
1973
+ if (!filter)
1974
+ return void 0;
1975
+ const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
1976
+ return values.length > 0 ? filter : void 0;
1547
1977
  }
1548
1978
 
1549
1979
  var __accessCheck$3 = (obj, member, msg) => {
@@ -1559,7 +1989,7 @@ var __privateAdd$3 = (obj, member, value) => {
1559
1989
  throw TypeError("Cannot add the same private member more than once");
1560
1990
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1561
1991
  };
1562
- var __privateSet$2 = (obj, member, value, setter) => {
1992
+ var __privateSet$3 = (obj, member, value, setter) => {
1563
1993
  __accessCheck$3(obj, member, "write to private field");
1564
1994
  setter ? setter.call(obj, value) : member.set(obj, value);
1565
1995
  return value;
@@ -1568,9 +1998,8 @@ var _map;
1568
1998
  class SimpleCache {
1569
1999
  constructor(options = {}) {
1570
2000
  __privateAdd$3(this, _map, void 0);
1571
- __privateSet$2(this, _map, /* @__PURE__ */ new Map());
2001
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1572
2002
  this.capacity = options.max ?? 500;
1573
- this.cacheRecords = options.cacheRecords ?? true;
1574
2003
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1575
2004
  }
1576
2005
  async getAll() {
@@ -1596,18 +2025,25 @@ class SimpleCache {
1596
2025
  }
1597
2026
  _map = new WeakMap();
1598
2027
 
1599
- const gt = (value) => ({ $gt: value });
1600
- const ge = (value) => ({ $ge: value });
1601
- const gte = (value) => ({ $ge: value });
1602
- const lt = (value) => ({ $lt: value });
1603
- const lte = (value) => ({ $le: value });
1604
- const le = (value) => ({ $le: value });
2028
+ const greaterThan = (value) => ({ $gt: value });
2029
+ const gt = greaterThan;
2030
+ const greaterThanEquals = (value) => ({ $ge: value });
2031
+ const greaterEquals = greaterThanEquals;
2032
+ const gte = greaterThanEquals;
2033
+ const ge = greaterThanEquals;
2034
+ const lessThan = (value) => ({ $lt: value });
2035
+ const lt = lessThan;
2036
+ const lessThanEquals = (value) => ({ $le: value });
2037
+ const lessEquals = lessThanEquals;
2038
+ const lte = lessThanEquals;
2039
+ const le = lessThanEquals;
1605
2040
  const exists = (column) => ({ $exists: column });
1606
2041
  const notExists = (column) => ({ $notExists: column });
1607
2042
  const startsWith = (value) => ({ $startsWith: value });
1608
2043
  const endsWith = (value) => ({ $endsWith: value });
1609
2044
  const pattern = (value) => ({ $pattern: value });
1610
2045
  const is = (value) => ({ $is: value });
2046
+ const equals = is;
1611
2047
  const isNot = (value) => ({ $isNot: value });
1612
2048
  const contains = (value) => ({ $contains: value });
1613
2049
  const includes = (value) => ({ $includes: value });
@@ -1628,31 +2064,42 @@ var __privateAdd$2 = (obj, member, value) => {
1628
2064
  throw TypeError("Cannot add the same private member more than once");
1629
2065
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1630
2066
  };
1631
- var _tables;
2067
+ var __privateSet$2 = (obj, member, value, setter) => {
2068
+ __accessCheck$2(obj, member, "write to private field");
2069
+ setter ? setter.call(obj, value) : member.set(obj, value);
2070
+ return value;
2071
+ };
2072
+ var _tables, _schemaTables$1;
1632
2073
  class SchemaPlugin extends XataPlugin {
1633
- constructor(tableNames) {
2074
+ constructor(schemaTables) {
1634
2075
  super();
1635
- this.tableNames = tableNames;
1636
2076
  __privateAdd$2(this, _tables, {});
2077
+ __privateAdd$2(this, _schemaTables$1, void 0);
2078
+ __privateSet$2(this, _schemaTables$1, schemaTables);
1637
2079
  }
1638
2080
  build(pluginOptions) {
1639
- const db = new Proxy({}, {
1640
- get: (_target, table) => {
1641
- if (!isString(table))
1642
- throw new Error("Invalid table name");
1643
- if (__privateGet$2(this, _tables)[table] === void 0) {
1644
- __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table });
2081
+ const db = new Proxy(
2082
+ {},
2083
+ {
2084
+ get: (_target, table) => {
2085
+ if (!isString(table))
2086
+ throw new Error("Invalid table name");
2087
+ if (__privateGet$2(this, _tables)[table] === void 0) {
2088
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
2089
+ }
2090
+ return __privateGet$2(this, _tables)[table];
1645
2091
  }
1646
- return __privateGet$2(this, _tables)[table];
1647
2092
  }
1648
- });
1649
- for (const table of this.tableNames ?? []) {
1650
- db[table] = new RestRepository({ db, pluginOptions, table });
2093
+ );
2094
+ const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
2095
+ for (const table of tableNames) {
2096
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1651
2097
  }
1652
2098
  return db;
1653
2099
  }
1654
2100
  }
1655
2101
  _tables = new WeakMap();
2102
+ _schemaTables$1 = new WeakMap();
1656
2103
 
1657
2104
  var __accessCheck$1 = (obj, member, msg) => {
1658
2105
  if (!member.has(obj))
@@ -1676,82 +2123,77 @@ var __privateMethod$1 = (obj, member, method) => {
1676
2123
  __accessCheck$1(obj, member, "access private method");
1677
2124
  return method;
1678
2125
  };
1679
- var _schema, _search, search_fn, _getSchema, getSchema_fn;
2126
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1680
2127
  class SearchPlugin extends XataPlugin {
1681
- constructor(db) {
2128
+ constructor(db, schemaTables) {
1682
2129
  super();
1683
2130
  this.db = db;
1684
2131
  __privateAdd$1(this, _search);
1685
- __privateAdd$1(this, _getSchema);
1686
- __privateAdd$1(this, _schema, void 0);
2132
+ __privateAdd$1(this, _getSchemaTables);
2133
+ __privateAdd$1(this, _schemaTables, void 0);
2134
+ __privateSet$1(this, _schemaTables, schemaTables);
1687
2135
  }
1688
2136
  build({ getFetchProps }) {
1689
2137
  return {
1690
2138
  all: async (query, options = {}) => {
1691
2139
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1692
- const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
2140
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1693
2141
  return records.map((record) => {
1694
2142
  const { table = "orphan" } = record.xata;
1695
- return { table, record: initObject(this.db, schema, table, record) };
2143
+ return { table, record: initObject(this.db, schemaTables, table, record) };
1696
2144
  });
1697
2145
  },
1698
2146
  byTable: async (query, options = {}) => {
1699
2147
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1700
- const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
2148
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1701
2149
  return records.reduce((acc, record) => {
1702
2150
  const { table = "orphan" } = record.xata;
1703
2151
  const items = acc[table] ?? [];
1704
- const item = initObject(this.db, schema, table, record);
2152
+ const item = initObject(this.db, schemaTables, table, record);
1705
2153
  return { ...acc, [table]: [...items, item] };
1706
2154
  }, {});
1707
2155
  }
1708
2156
  };
1709
2157
  }
1710
2158
  }
1711
- _schema = new WeakMap();
2159
+ _schemaTables = new WeakMap();
1712
2160
  _search = new WeakSet();
1713
2161
  search_fn = async function(query, options, getFetchProps) {
1714
2162
  const fetchProps = await getFetchProps();
1715
- const { tables, fuzziness } = options ?? {};
2163
+ const { tables, fuzziness, highlight, prefix } = options ?? {};
1716
2164
  const { records } = await searchBranch({
1717
2165
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1718
- body: { tables, query, fuzziness },
2166
+ body: { tables, query, fuzziness, prefix, highlight },
1719
2167
  ...fetchProps
1720
2168
  });
1721
2169
  return records;
1722
2170
  };
1723
- _getSchema = new WeakSet();
1724
- getSchema_fn = async function(getFetchProps) {
1725
- if (__privateGet$1(this, _schema))
1726
- return __privateGet$1(this, _schema);
2171
+ _getSchemaTables = new WeakSet();
2172
+ getSchemaTables_fn = async function(getFetchProps) {
2173
+ if (__privateGet$1(this, _schemaTables))
2174
+ return __privateGet$1(this, _schemaTables);
1727
2175
  const fetchProps = await getFetchProps();
1728
2176
  const { schema } = await getBranchDetails({
1729
2177
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1730
2178
  ...fetchProps
1731
2179
  });
1732
- __privateSet$1(this, _schema, schema);
1733
- return schema;
2180
+ __privateSet$1(this, _schemaTables, schema.tables);
2181
+ return schema.tables;
1734
2182
  };
1735
2183
 
1736
2184
  const isBranchStrategyBuilder = (strategy) => {
1737
2185
  return typeof strategy === "function";
1738
2186
  };
1739
2187
 
1740
- const envBranchNames = [
1741
- "XATA_BRANCH",
1742
- "VERCEL_GIT_COMMIT_REF",
1743
- "CF_PAGES_BRANCH",
1744
- "BRANCH"
1745
- ];
1746
2188
  async function getCurrentBranchName(options) {
1747
- const env = getBranchByEnvVariable();
1748
- if (env) {
1749
- const details = await getDatabaseBranch(env, options);
2189
+ const { branch, envBranch } = getEnvironment();
2190
+ if (branch) {
2191
+ const details = await getDatabaseBranch(branch, options);
1750
2192
  if (details)
1751
- return env;
1752
- console.warn(`Branch ${env} not found in Xata. Ignoring...`);
2193
+ return branch;
2194
+ console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
1753
2195
  }
1754
- const gitBranch = await getGitBranch();
2196
+ const gitBranch = envBranch || await getGitBranch();
1755
2197
  return resolveXataBranch(gitBranch, options);
1756
2198
  }
1757
2199
  async function getCurrentBranchDetails(options) {
@@ -1762,18 +2204,24 @@ async function resolveXataBranch(gitBranch, options) {
1762
2204
  const databaseURL = options?.databaseURL || getDatabaseURL();
1763
2205
  const apiKey = options?.apiKey || getAPIKey();
1764
2206
  if (!databaseURL)
1765
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
2207
+ throw new Error(
2208
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2209
+ );
1766
2210
  if (!apiKey)
1767
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
2211
+ throw new Error(
2212
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2213
+ );
1768
2214
  const [protocol, , host, , dbName] = databaseURL.split("/");
1769
2215
  const [workspace] = host.split(".");
2216
+ const { fallbackBranch } = getEnvironment();
1770
2217
  const { branch } = await resolveBranch({
1771
2218
  apiKey,
1772
2219
  apiUrl: databaseURL,
1773
2220
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1774
2221
  workspacesApiUrl: `${protocol}//${host}`,
1775
2222
  pathParams: { dbName, workspace },
1776
- queryParams: { gitBranch, fallbackBranch: getEnvVariable("XATA_FALLBACK_BRANCH") }
2223
+ queryParams: { gitBranch, fallbackBranch },
2224
+ trace: defaultTrace
1777
2225
  });
1778
2226
  return branch;
1779
2227
  }
@@ -1781,9 +2229,13 @@ async function getDatabaseBranch(branch, options) {
1781
2229
  const databaseURL = options?.databaseURL || getDatabaseURL();
1782
2230
  const apiKey = options?.apiKey || getAPIKey();
1783
2231
  if (!databaseURL)
1784
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
2232
+ throw new Error(
2233
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2234
+ );
1785
2235
  if (!apiKey)
1786
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
2236
+ throw new Error(
2237
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2238
+ );
1787
2239
  const [protocol, , host, , database] = databaseURL.split("/");
1788
2240
  const [workspace] = host.split(".");
1789
2241
  const dbBranchName = `${database}:${branch}`;
@@ -1793,10 +2245,8 @@ async function getDatabaseBranch(branch, options) {
1793
2245
  apiUrl: databaseURL,
1794
2246
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1795
2247
  workspacesApiUrl: `${protocol}//${host}`,
1796
- pathParams: {
1797
- dbBranchName,
1798
- workspace
1799
- }
2248
+ pathParams: { dbBranchName, workspace },
2249
+ trace: defaultTrace
1800
2250
  });
1801
2251
  } catch (err) {
1802
2252
  if (isObject(err) && err.status === 404)
@@ -1804,21 +2254,10 @@ async function getDatabaseBranch(branch, options) {
1804
2254
  throw err;
1805
2255
  }
1806
2256
  }
1807
- function getBranchByEnvVariable() {
1808
- for (const name of envBranchNames) {
1809
- const value = getEnvVariable(name);
1810
- if (value) {
1811
- return value;
1812
- }
1813
- }
1814
- try {
1815
- return XATA_BRANCH;
1816
- } catch (err) {
1817
- }
1818
- }
1819
2257
  function getDatabaseURL() {
1820
2258
  try {
1821
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
2259
+ const { databaseURL } = getEnvironment();
2260
+ return databaseURL;
1822
2261
  } catch (err) {
1823
2262
  return void 0;
1824
2263
  }
@@ -1847,20 +2286,23 @@ var __privateMethod = (obj, member, method) => {
1847
2286
  return method;
1848
2287
  };
1849
2288
  const buildClient = (plugins) => {
1850
- var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
2289
+ var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1851
2290
  return _a = class {
1852
- constructor(options = {}, tables) {
2291
+ constructor(options = {}, schemaTables) {
1853
2292
  __privateAdd(this, _parseOptions);
1854
2293
  __privateAdd(this, _getFetchProps);
1855
2294
  __privateAdd(this, _evaluateBranch);
1856
2295
  __privateAdd(this, _branch, void 0);
2296
+ __privateAdd(this, _options, void 0);
1857
2297
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
2298
+ __privateSet(this, _options, safeOptions);
1858
2299
  const pluginOptions = {
1859
2300
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1860
- cache: safeOptions.cache
2301
+ cache: safeOptions.cache,
2302
+ trace: safeOptions.trace
1861
2303
  };
1862
- const db = new SchemaPlugin(tables).build(pluginOptions);
1863
- const search = new SearchPlugin(db).build(pluginOptions);
2304
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2305
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1864
2306
  this.db = db;
1865
2307
  this.search = search;
1866
2308
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
@@ -1876,22 +2318,26 @@ const buildClient = (plugins) => {
1876
2318
  }
1877
2319
  }
1878
2320
  }
1879
- }, _branch = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
2321
+ async getConfig() {
2322
+ const databaseURL = __privateGet(this, _options).databaseURL;
2323
+ const branch = await __privateGet(this, _options).branch();
2324
+ return { databaseURL, branch };
2325
+ }
2326
+ }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
1880
2327
  const fetch = getFetchImplementation(options?.fetch);
1881
2328
  const databaseURL = options?.databaseURL || getDatabaseURL();
1882
2329
  const apiKey = options?.apiKey || getAPIKey();
1883
- const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
2330
+ const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
2331
+ const trace = options?.trace ?? defaultTrace;
1884
2332
  const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1885
- if (!databaseURL || !apiKey) {
1886
- throw new Error("Options databaseURL and apiKey are required");
2333
+ if (!apiKey) {
2334
+ throw new Error("Option apiKey is required");
1887
2335
  }
1888
- return { fetch, databaseURL, apiKey, branch, cache };
1889
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
1890
- fetch,
1891
- apiKey,
1892
- databaseURL,
1893
- branch
1894
- }) {
2336
+ if (!databaseURL) {
2337
+ throw new Error("Option databaseURL is required");
2338
+ }
2339
+ return { fetch, databaseURL, apiKey, branch, cache, trace };
2340
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace }) {
1895
2341
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
1896
2342
  if (!branchValue)
1897
2343
  throw new Error("Unable to resolve branch value");
@@ -1901,9 +2347,10 @@ const buildClient = (plugins) => {
1901
2347
  apiUrl: "",
1902
2348
  workspacesApiUrl: (path, params) => {
1903
2349
  const hasBranch = params.dbBranchName ?? params.branch;
1904
- const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branchValue}` : "");
2350
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branchValue}` : "");
1905
2351
  return databaseURL + newPath;
1906
- }
2352
+ },
2353
+ trace
1907
2354
  };
1908
2355
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1909
2356
  if (__privateGet(this, _branch))
@@ -1926,6 +2373,88 @@ const buildClient = (plugins) => {
1926
2373
  class BaseClient extends buildClient() {
1927
2374
  }
1928
2375
 
2376
+ const META = "__";
2377
+ const VALUE = "___";
2378
+ class Serializer {
2379
+ constructor() {
2380
+ this.classes = {};
2381
+ }
2382
+ add(clazz) {
2383
+ this.classes[clazz.name] = clazz;
2384
+ }
2385
+ toJSON(data) {
2386
+ function visit(obj) {
2387
+ if (Array.isArray(obj))
2388
+ return obj.map(visit);
2389
+ const type = typeof obj;
2390
+ if (type === "undefined")
2391
+ return { [META]: "undefined" };
2392
+ if (type === "bigint")
2393
+ return { [META]: "bigint", [VALUE]: obj.toString() };
2394
+ if (obj === null || type !== "object")
2395
+ return obj;
2396
+ const constructor = obj.constructor;
2397
+ const o = { [META]: constructor.name };
2398
+ for (const [key, value] of Object.entries(obj)) {
2399
+ o[key] = visit(value);
2400
+ }
2401
+ if (constructor === Date)
2402
+ o[VALUE] = obj.toISOString();
2403
+ if (constructor === Map)
2404
+ o[VALUE] = Object.fromEntries(obj);
2405
+ if (constructor === Set)
2406
+ o[VALUE] = [...obj];
2407
+ return o;
2408
+ }
2409
+ return JSON.stringify(visit(data));
2410
+ }
2411
+ fromJSON(json) {
2412
+ return JSON.parse(json, (key, value) => {
2413
+ if (value && typeof value === "object" && !Array.isArray(value)) {
2414
+ const { [META]: clazz, [VALUE]: val, ...rest } = value;
2415
+ const constructor = this.classes[clazz];
2416
+ if (constructor) {
2417
+ return Object.assign(Object.create(constructor.prototype), rest);
2418
+ }
2419
+ if (clazz === "Date")
2420
+ return new Date(val);
2421
+ if (clazz === "Set")
2422
+ return new Set(val);
2423
+ if (clazz === "Map")
2424
+ return new Map(Object.entries(val));
2425
+ if (clazz === "bigint")
2426
+ return BigInt(val);
2427
+ if (clazz === "undefined")
2428
+ return void 0;
2429
+ return rest;
2430
+ }
2431
+ return value;
2432
+ });
2433
+ }
2434
+ }
2435
+ const defaultSerializer = new Serializer();
2436
+ const serialize = (data) => {
2437
+ return defaultSerializer.toJSON(data);
2438
+ };
2439
+ const deserialize = (json) => {
2440
+ return defaultSerializer.fromJSON(json);
2441
+ };
2442
+
2443
+ function buildWorkerRunner(config) {
2444
+ return function xataWorker(name, _worker) {
2445
+ return async (...args) => {
2446
+ const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
2447
+ const result = await fetch(url, {
2448
+ method: "POST",
2449
+ headers: { "Content-Type": "application/json" },
2450
+ body: serialize({ args })
2451
+ });
2452
+ const text = await result.text();
2453
+ return deserialize(text);
2454
+ };
2455
+ };
2456
+ }
2457
+
1929
2458
  class XataError extends Error {
1930
2459
  constructor(message, status) {
1931
2460
  super(message);
@@ -1933,5 +2462,5 @@ class XataError extends Error {
1933
2462
  }
1934
2463
  }
1935
2464
 
1936
- export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, Repository, RestRepository, SchemaPlugin, SearchPlugin, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, buildClient, bulkInsertTableRecords, cancelWorkspaceMemberInvite, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, endsWith, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseURL, getGitBranchesMapping, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isIdentifiable, isNot, isXataRecord, le, lt, lte, notExists, operationsByTag, pattern, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberRole, upsertRecordWithID };
2465
+ export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, Serializer, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, applyBranchSchemaEdit, buildClient, buildWorkerRunner, bulkInsertTableRecords, cancelWorkspaceMemberInvite, compareBranchSchemas, compareBranchWithUserSchema, compareMigrationRequest, contains, createBranch, createDatabase, createMigrationRequest, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, deserialize, endsWith, equals, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchSchemaHistory, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseMetadata, getDatabaseURL, getGitBranchesMapping, getMigrationRequest, getMigrationRequestIsMerged, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, greaterEquals, greaterThan, greaterThanEquals, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isIdentifiable, isNot, isXataRecord, le, lessEquals, lessThan, lessThanEquals, listMigrationRequests, listMigrationRequestsCommits, lt, lte, mergeMigrationRequest, notExists, operationsByTag, patchDatabaseMetadata, pattern, previewBranchSchemaEdit, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, serialize, setTableSchema, startsWith, updateBranchMetadata, updateBranchSchema, updateColumn, updateMigrationRequest, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID };
1937
2466
  //# sourceMappingURL=index.mjs.map