@xata.io/client 0.0.0-alpha.vf4b92f1 → 0.0.0-alpha.vf5a6674

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,43 +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
- return require("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
117
+ if (typeof require === "function") {
118
+ return require(nodeModule).execSync(fullCmd, execOptions).trim();
119
+ }
120
+ const { execSync } = await import(nodeModule);
121
+ return execSync(fullCmd, execOptions).toString().trim();
38
122
  } catch (err) {
39
123
  }
40
124
  try {
41
125
  if (isObject(Deno)) {
42
- const process2 = Deno.run({
43
- cmd: ["git", "branch", "--show-current"],
44
- stdout: "piped",
45
- stderr: "piped"
46
- });
126
+ const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
47
127
  return new TextDecoder().decode(await process2.output()).trim();
48
128
  }
49
129
  } catch (err) {
@@ -52,7 +132,8 @@ async function getGitBranch() {
52
132
 
53
133
  function getAPIKey() {
54
134
  try {
55
- return getEnvVariable("XATA_API_KEY") ?? XATA_API_KEY;
135
+ const { apiKey } = getEnvironment();
136
+ return apiKey;
56
137
  } catch (err) {
57
138
  return void 0;
58
139
  }
@@ -62,21 +143,35 @@ function getFetchImplementation(userFetch) {
62
143
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
63
144
  const fetchImpl = userFetch ?? globalFetch;
64
145
  if (!fetchImpl) {
65
- throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
146
+ throw new Error(
147
+ `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
148
+ );
66
149
  }
67
150
  return fetchImpl;
68
151
  }
69
152
 
70
- class FetcherError extends Error {
71
- constructor(status, data) {
153
+ const VERSION = "0.0.0-alpha.vf5a6674";
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) {
72
162
  super(getMessage(data));
73
163
  this.status = status;
74
164
  this.errors = isBulkError(data) ? data.errors : void 0;
165
+ this.requestId = requestId;
75
166
  if (data instanceof Error) {
76
167
  this.stack = data.stack;
77
168
  this.cause = data.cause;
78
169
  }
79
170
  }
171
+ toString() {
172
+ const error = super.toString();
173
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
174
+ }
80
175
  }
81
176
  function isBulkError(error) {
82
177
  return isObject(error) && Array.isArray(error.errors);
@@ -99,9 +194,17 @@ function getMessage(data) {
99
194
  }
100
195
 
101
196
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
102
- 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();
103
203
  const queryString = query.length > 0 ? `?${query}` : "";
104
- 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;
105
208
  };
106
209
  function buildBaseUrl({
107
210
  path,
@@ -109,10 +212,10 @@ function buildBaseUrl({
109
212
  apiUrl,
110
213
  pathParams
111
214
  }) {
112
- if (!pathParams?.workspace)
215
+ if (pathParams?.workspace === void 0 || !path.startsWith("/db"))
113
216
  return `${apiUrl}${path}`;
114
217
  const url = typeof workspacesApiUrl === "string" ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
115
- return url.replace("{workspaceId}", pathParams.workspace);
218
+ return url.replace("{workspaceId}", String(pathParams.workspace));
116
219
  }
117
220
  function hostHeader(url) {
118
221
  const pattern = /.*:\/\/(?<host>[^/]+).*/;
@@ -129,254 +232,413 @@ async function fetch$1({
129
232
  fetchImpl,
130
233
  apiKey,
131
234
  apiUrl,
132
- workspacesApiUrl
235
+ workspacesApiUrl,
236
+ trace,
237
+ signal,
238
+ clientID,
239
+ sessionID
133
240
  }) {
134
- const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
135
- const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
136
- const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
137
- const response = await fetchImpl(url, {
138
- method: method.toUpperCase(),
139
- body: body ? JSON.stringify(body) : void 0,
140
- headers: {
141
- "Content-Type": "application/json",
142
- ...headers,
143
- ...hostHeader(fullUrl),
144
- Authorization: `Bearer ${apiKey}`
145
- }
146
- });
147
- if (response.status === 204) {
148
- return {};
149
- }
241
+ return trace(
242
+ `${method.toUpperCase()} ${path}`,
243
+ async ({ setAttributes }) => {
244
+ const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
245
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
246
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
247
+ setAttributes({
248
+ [TraceAttributes.HTTP_URL]: url,
249
+ [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
250
+ });
251
+ const response = await fetchImpl(url, {
252
+ method: method.toUpperCase(),
253
+ body: body ? JSON.stringify(body) : void 0,
254
+ headers: {
255
+ "Content-Type": "application/json",
256
+ "User-Agent": `Xata client-ts/${VERSION}`,
257
+ "X-Xata-Client-ID": clientID ?? "",
258
+ "X-Xata-Session-ID": sessionID ?? "",
259
+ ...headers,
260
+ ...hostHeader(fullUrl),
261
+ Authorization: `Bearer ${apiKey}`
262
+ },
263
+ signal
264
+ });
265
+ if (response.status === 204) {
266
+ return {};
267
+ }
268
+ const { host, protocol } = parseUrl(response.url);
269
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
270
+ setAttributes({
271
+ [TraceAttributes.KIND]: "http",
272
+ [TraceAttributes.HTTP_REQUEST_ID]: requestId,
273
+ [TraceAttributes.HTTP_STATUS_CODE]: response.status,
274
+ [TraceAttributes.HTTP_HOST]: host,
275
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
276
+ });
277
+ try {
278
+ const jsonResponse = await response.json();
279
+ if (response.ok) {
280
+ return jsonResponse;
281
+ }
282
+ throw new FetcherError(response.status, jsonResponse, requestId);
283
+ } catch (error) {
284
+ throw new FetcherError(response.status, error, requestId);
285
+ }
286
+ },
287
+ { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
288
+ );
289
+ }
290
+ function parseUrl(url) {
150
291
  try {
151
- const jsonResponse = await response.json();
152
- if (response.ok) {
153
- return jsonResponse;
154
- }
155
- throw new FetcherError(response.status, jsonResponse);
292
+ const { host, protocol } = new URL(url);
293
+ return { host, protocol };
156
294
  } catch (error) {
157
- throw new FetcherError(response.status, error);
295
+ return {};
158
296
  }
159
297
  }
160
298
 
161
- const getUser = (variables) => fetch$1({ url: "/user", method: "get", ...variables });
162
- const updateUser = (variables) => fetch$1({ url: "/user", method: "put", ...variables });
163
- const deleteUser = (variables) => fetch$1({ url: "/user", method: "delete", ...variables });
164
- const getUserAPIKeys = (variables) => fetch$1({
299
+ const getUser = (variables, signal) => fetch$1({ url: "/user", method: "get", ...variables, signal });
300
+ const updateUser = (variables, signal) => fetch$1({
301
+ url: "/user",
302
+ method: "put",
303
+ ...variables,
304
+ signal
305
+ });
306
+ const deleteUser = (variables, signal) => fetch$1({ url: "/user", method: "delete", ...variables, signal });
307
+ const getUserAPIKeys = (variables, signal) => fetch$1({
165
308
  url: "/user/keys",
166
309
  method: "get",
167
- ...variables
310
+ ...variables,
311
+ signal
168
312
  });
169
- const createUserAPIKey = (variables) => fetch$1({
313
+ const createUserAPIKey = (variables, signal) => fetch$1({
170
314
  url: "/user/keys/{keyName}",
171
315
  method: "post",
172
- ...variables
316
+ ...variables,
317
+ signal
173
318
  });
174
- const deleteUserAPIKey = (variables) => fetch$1({
319
+ const deleteUserAPIKey = (variables, signal) => fetch$1({
175
320
  url: "/user/keys/{keyName}",
176
321
  method: "delete",
177
- ...variables
322
+ ...variables,
323
+ signal
178
324
  });
179
- const createWorkspace = (variables) => fetch$1({
325
+ const getWorkspacesList = (variables, signal) => fetch$1({
180
326
  url: "/workspaces",
181
- method: "post",
182
- ...variables
327
+ method: "get",
328
+ ...variables,
329
+ signal
183
330
  });
184
- const getWorkspacesList = (variables) => fetch$1({
331
+ const createWorkspace = (variables, signal) => fetch$1({
185
332
  url: "/workspaces",
186
- method: "get",
187
- ...variables
333
+ method: "post",
334
+ ...variables,
335
+ signal
188
336
  });
189
- const getWorkspace = (variables) => fetch$1({
337
+ const getWorkspace = (variables, signal) => fetch$1({
190
338
  url: "/workspaces/{workspaceId}",
191
339
  method: "get",
192
- ...variables
340
+ ...variables,
341
+ signal
193
342
  });
194
- const updateWorkspace = (variables) => fetch$1({
343
+ const updateWorkspace = (variables, signal) => fetch$1({
195
344
  url: "/workspaces/{workspaceId}",
196
345
  method: "put",
197
- ...variables
346
+ ...variables,
347
+ signal
198
348
  });
199
- const deleteWorkspace = (variables) => fetch$1({
349
+ const deleteWorkspace = (variables, signal) => fetch$1({
200
350
  url: "/workspaces/{workspaceId}",
201
351
  method: "delete",
202
- ...variables
352
+ ...variables,
353
+ signal
203
354
  });
204
- const getWorkspaceMembersList = (variables) => fetch$1({
355
+ const getWorkspaceMembersList = (variables, signal) => fetch$1({
205
356
  url: "/workspaces/{workspaceId}/members",
206
357
  method: "get",
207
- ...variables
358
+ ...variables,
359
+ signal
208
360
  });
209
- const updateWorkspaceMemberRole = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/members/{userId}", method: "put", ...variables });
210
- const removeWorkspaceMember = (variables) => fetch$1({
361
+ const updateWorkspaceMemberRole = (variables, signal) => fetch$1({ url: "/workspaces/{workspaceId}/members/{userId}", method: "put", ...variables, signal });
362
+ const removeWorkspaceMember = (variables, signal) => fetch$1({
211
363
  url: "/workspaces/{workspaceId}/members/{userId}",
212
364
  method: "delete",
213
- ...variables
365
+ ...variables,
366
+ signal
214
367
  });
215
- const inviteWorkspaceMember = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables });
216
- const cancelWorkspaceMemberInvite = (variables) => fetch$1({
368
+ const inviteWorkspaceMember = (variables, signal) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables, signal });
369
+ const updateWorkspaceMemberInvite = (variables, signal) => fetch$1({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables, signal });
370
+ const cancelWorkspaceMemberInvite = (variables, signal) => fetch$1({
217
371
  url: "/workspaces/{workspaceId}/invites/{inviteId}",
218
372
  method: "delete",
219
- ...variables
373
+ ...variables,
374
+ signal
220
375
  });
221
- const resendWorkspaceMemberInvite = (variables) => fetch$1({
222
- url: "/workspaces/{workspaceId}/invites/{inviteId}/resend",
376
+ const acceptWorkspaceMemberInvite = (variables, signal) => fetch$1({
377
+ url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept",
223
378
  method: "post",
224
- ...variables
379
+ ...variables,
380
+ signal
225
381
  });
226
- const acceptWorkspaceMemberInvite = (variables) => fetch$1({
227
- url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept",
382
+ const resendWorkspaceMemberInvite = (variables, signal) => fetch$1({
383
+ url: "/workspaces/{workspaceId}/invites/{inviteId}/resend",
228
384
  method: "post",
229
- ...variables
385
+ ...variables,
386
+ signal
230
387
  });
231
- const getDatabaseList = (variables) => fetch$1({
388
+ const getDatabaseList = (variables, signal) => fetch$1({
232
389
  url: "/dbs",
233
390
  method: "get",
234
- ...variables
391
+ ...variables,
392
+ signal
235
393
  });
236
- const getBranchList = (variables) => fetch$1({
394
+ const getBranchList = (variables, signal) => fetch$1({
237
395
  url: "/dbs/{dbName}",
238
396
  method: "get",
239
- ...variables
397
+ ...variables,
398
+ signal
240
399
  });
241
- const createDatabase = (variables) => fetch$1({
400
+ const createDatabase = (variables, signal) => fetch$1({
242
401
  url: "/dbs/{dbName}",
243
402
  method: "put",
244
- ...variables
403
+ ...variables,
404
+ signal
245
405
  });
246
- const deleteDatabase = (variables) => fetch$1({
406
+ const deleteDatabase = (variables, signal) => fetch$1({
247
407
  url: "/dbs/{dbName}",
248
408
  method: "delete",
249
- ...variables
409
+ ...variables,
410
+ signal
250
411
  });
251
- const getBranchDetails = (variables) => fetch$1({
252
- url: "/db/{dbBranchName}",
412
+ const getDatabaseMetadata = (variables, signal) => fetch$1({
413
+ url: "/dbs/{dbName}/metadata",
253
414
  method: "get",
254
- ...variables
415
+ ...variables,
416
+ signal
255
417
  });
256
- const createBranch = (variables) => fetch$1({
418
+ const updateDatabaseMetadata = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/metadata", method: "patch", ...variables, signal });
419
+ const getBranchDetails = (variables, signal) => fetch$1({
257
420
  url: "/db/{dbBranchName}",
258
- method: "put",
259
- ...variables
421
+ method: "get",
422
+ ...variables,
423
+ signal
260
424
  });
261
- const deleteBranch = (variables) => fetch$1({
425
+ const createBranch = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}", method: "put", ...variables, signal });
426
+ const deleteBranch = (variables, signal) => fetch$1({
262
427
  url: "/db/{dbBranchName}",
263
428
  method: "delete",
264
- ...variables
429
+ ...variables,
430
+ signal
265
431
  });
266
- const updateBranchMetadata = (variables) => fetch$1({
432
+ const updateBranchMetadata = (variables, signal) => fetch$1({
267
433
  url: "/db/{dbBranchName}/metadata",
268
434
  method: "put",
269
- ...variables
435
+ ...variables,
436
+ signal
270
437
  });
271
- const getBranchMetadata = (variables) => fetch$1({
438
+ const getBranchMetadata = (variables, signal) => fetch$1({
272
439
  url: "/db/{dbBranchName}/metadata",
273
440
  method: "get",
274
- ...variables
441
+ ...variables,
442
+ signal
275
443
  });
276
- const getBranchMigrationHistory = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables });
277
- const executeBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables });
278
- const getBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables });
279
- const getBranchStats = (variables) => fetch$1({
444
+ const getBranchStats = (variables, signal) => fetch$1({
280
445
  url: "/db/{dbBranchName}/stats",
281
446
  method: "get",
282
- ...variables
447
+ ...variables,
448
+ signal
449
+ });
450
+ const getGitBranchesMapping = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables, signal });
451
+ const addGitBranchesEntry = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables, signal });
452
+ const removeGitBranchesEntry = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables, signal });
453
+ const resolveBranch = (variables, signal) => fetch$1({
454
+ url: "/dbs/{dbName}/resolveBranch",
455
+ method: "get",
456
+ ...variables,
457
+ signal
283
458
  });
284
- const createTable = (variables) => fetch$1({
459
+ const getBranchMigrationHistory = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables, signal });
460
+ const getBranchMigrationPlan = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables, signal });
461
+ const executeBranchMigrationPlan = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables, signal });
462
+ const queryMigrationRequests = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/migrations/query", method: "post", ...variables, signal });
463
+ const createMigrationRequest = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/migrations", method: "post", ...variables, signal });
464
+ const getMigrationRequest = (variables, signal) => fetch$1({
465
+ url: "/dbs/{dbName}/migrations/{mrNumber}",
466
+ method: "get",
467
+ ...variables,
468
+ signal
469
+ });
470
+ const updateMigrationRequest = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}", method: "patch", ...variables, signal });
471
+ const listMigrationRequestsCommits = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/commits", method: "post", ...variables, signal });
472
+ const compareMigrationRequest = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/compare", method: "post", ...variables, signal });
473
+ const getMigrationRequestIsMerged = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/merge", method: "get", ...variables, signal });
474
+ const mergeMigrationRequest = (variables, signal) => fetch$1({
475
+ url: "/dbs/{dbName}/migrations/{mrNumber}/merge",
476
+ method: "post",
477
+ ...variables,
478
+ signal
479
+ });
480
+ const getBranchSchemaHistory = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/schema/history", method: "post", ...variables, signal });
481
+ const compareBranchWithUserSchema = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/schema/compare", method: "post", ...variables, signal });
482
+ const compareBranchSchemas = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/schema/compare/{branchName}", method: "post", ...variables, signal });
483
+ const updateBranchSchema = (variables, signal) => fetch$1({
484
+ url: "/db/{dbBranchName}/schema/update",
485
+ method: "post",
486
+ ...variables,
487
+ signal
488
+ });
489
+ const previewBranchSchemaEdit = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables, signal });
490
+ const applyBranchSchemaEdit = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables, signal });
491
+ const createTable = (variables, signal) => fetch$1({
285
492
  url: "/db/{dbBranchName}/tables/{tableName}",
286
493
  method: "put",
287
- ...variables
494
+ ...variables,
495
+ signal
288
496
  });
289
- const deleteTable = (variables) => fetch$1({
497
+ const deleteTable = (variables, signal) => fetch$1({
290
498
  url: "/db/{dbBranchName}/tables/{tableName}",
291
499
  method: "delete",
292
- ...variables
500
+ ...variables,
501
+ signal
293
502
  });
294
- const updateTable = (variables) => fetch$1({
503
+ const updateTable = (variables, signal) => fetch$1({
295
504
  url: "/db/{dbBranchName}/tables/{tableName}",
296
505
  method: "patch",
297
- ...variables
506
+ ...variables,
507
+ signal
298
508
  });
299
- const getTableSchema = (variables) => fetch$1({
509
+ const getTableSchema = (variables, signal) => fetch$1({
300
510
  url: "/db/{dbBranchName}/tables/{tableName}/schema",
301
511
  method: "get",
302
- ...variables
512
+ ...variables,
513
+ signal
303
514
  });
304
- const setTableSchema = (variables) => fetch$1({
515
+ const setTableSchema = (variables, signal) => fetch$1({
305
516
  url: "/db/{dbBranchName}/tables/{tableName}/schema",
306
517
  method: "put",
307
- ...variables
518
+ ...variables,
519
+ signal
308
520
  });
309
- const getTableColumns = (variables) => fetch$1({
521
+ const getTableColumns = (variables, signal) => fetch$1({
310
522
  url: "/db/{dbBranchName}/tables/{tableName}/columns",
311
523
  method: "get",
312
- ...variables
524
+ ...variables,
525
+ signal
313
526
  });
314
- const addTableColumn = (variables) => fetch$1({
527
+ const addTableColumn = (variables, signal) => fetch$1({
315
528
  url: "/db/{dbBranchName}/tables/{tableName}/columns",
316
529
  method: "post",
317
- ...variables
530
+ ...variables,
531
+ signal
318
532
  });
319
- const getColumn = (variables) => fetch$1({
533
+ const getColumn = (variables, signal) => fetch$1({
320
534
  url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
321
535
  method: "get",
322
- ...variables
323
- });
324
- const deleteColumn = (variables) => fetch$1({
325
- url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
326
- method: "delete",
327
- ...variables
536
+ ...variables,
537
+ signal
328
538
  });
329
- const updateColumn = (variables) => fetch$1({
539
+ const updateColumn = (variables, signal) => fetch$1({
330
540
  url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
331
541
  method: "patch",
332
- ...variables
333
- });
334
- const insertRecord = (variables) => fetch$1({
335
- url: "/db/{dbBranchName}/tables/{tableName}/data",
336
- method: "post",
337
- ...variables
542
+ ...variables,
543
+ signal
338
544
  });
339
- const insertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables });
340
- const updateRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables });
341
- const upsertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables });
342
- const deleteRecord = (variables) => fetch$1({
343
- url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
545
+ const deleteColumn = (variables, signal) => fetch$1({
546
+ url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
344
547
  method: "delete",
345
- ...variables
548
+ ...variables,
549
+ signal
346
550
  });
347
- const getRecord = (variables) => fetch$1({
551
+ const insertRecord = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
552
+ const getRecord = (variables, signal) => fetch$1({
348
553
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
349
554
  method: "get",
350
- ...variables
555
+ ...variables,
556
+ signal
557
+ });
558
+ const insertRecordWithID = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables, signal });
559
+ const updateRecordWithID = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables, signal });
560
+ const upsertRecordWithID = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables, signal });
561
+ const deleteRecord = (variables, signal) => fetch$1({
562
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
563
+ method: "delete",
564
+ ...variables,
565
+ signal
351
566
  });
352
- const bulkInsertTableRecords = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/bulk", method: "post", ...variables });
353
- const queryTable = (variables) => fetch$1({
567
+ const bulkInsertTableRecords = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/bulk", method: "post", ...variables, signal });
568
+ const queryTable = (variables, signal) => fetch$1({
354
569
  url: "/db/{dbBranchName}/tables/{tableName}/query",
355
570
  method: "post",
356
- ...variables
571
+ ...variables,
572
+ signal
357
573
  });
358
- const searchBranch = (variables) => fetch$1({
574
+ const searchBranch = (variables, signal) => fetch$1({
359
575
  url: "/db/{dbBranchName}/search",
360
576
  method: "post",
361
- ...variables
577
+ ...variables,
578
+ signal
579
+ });
580
+ const searchTable = (variables, signal) => fetch$1({
581
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
582
+ method: "post",
583
+ ...variables,
584
+ signal
585
+ });
586
+ const summarizeTable = (variables, signal) => fetch$1({
587
+ url: "/db/{dbBranchName}/tables/{tableName}/summarize",
588
+ method: "post",
589
+ ...variables,
590
+ signal
591
+ });
592
+ const aggregateTable = (variables, signal) => fetch$1({
593
+ url: "/db/{dbBranchName}/tables/{tableName}/aggregate",
594
+ method: "post",
595
+ ...variables,
596
+ signal
597
+ });
598
+ const cPGetDatabaseList = (variables, signal) => fetch$1({
599
+ url: "/workspaces/{workspaceId}/dbs",
600
+ method: "get",
601
+ ...variables,
602
+ signal
603
+ });
604
+ const cPCreateDatabase = (variables, signal) => fetch$1({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "put", ...variables, signal });
605
+ const cPDeleteDatabase = (variables, signal) => fetch$1({
606
+ url: "/workspaces/{workspaceId}/dbs/{dbName}",
607
+ method: "delete",
608
+ ...variables,
609
+ signal
610
+ });
611
+ const cPGetCPDatabaseMetadata = (variables, signal) => fetch$1(
612
+ { url: "/workspaces/{workspaceId}/dbs/{dbName}/metadata", method: "get", ...variables, signal }
613
+ );
614
+ const cPUpdateCPDatabaseMetadata = (variables, signal) => fetch$1({ url: "/workspaces/{workspaceId}/dbs/{dbName}/metadata", method: "patch", ...variables, signal });
615
+ const listRegions = (variables, signal) => fetch$1({
616
+ url: "/workspaces/{workspaceId}/regions",
617
+ method: "get",
618
+ ...variables,
619
+ signal
362
620
  });
363
621
  const operationsByTag = {
364
- users: { getUser, updateUser, deleteUser, getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
622
+ users: { getUser, updateUser, deleteUser },
623
+ authentication: { getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
365
624
  workspaces: {
366
- createWorkspace,
367
625
  getWorkspacesList,
626
+ createWorkspace,
368
627
  getWorkspace,
369
628
  updateWorkspace,
370
629
  deleteWorkspace,
371
630
  getWorkspaceMembersList,
372
631
  updateWorkspaceMemberRole,
373
- removeWorkspaceMember,
632
+ removeWorkspaceMember
633
+ },
634
+ invites: {
374
635
  inviteWorkspaceMember,
636
+ updateWorkspaceMemberInvite,
375
637
  cancelWorkspaceMemberInvite,
376
- resendWorkspaceMemberInvite,
377
- acceptWorkspaceMemberInvite
638
+ acceptWorkspaceMemberInvite,
639
+ resendWorkspaceMemberInvite
378
640
  },
379
- database: { getDatabaseList, createDatabase, deleteDatabase },
641
+ database: { getDatabaseList, createDatabase, deleteDatabase, getDatabaseMetadata, updateDatabaseMetadata },
380
642
  branch: {
381
643
  getBranchList,
382
644
  getBranchDetails,
@@ -384,10 +646,32 @@ const operationsByTag = {
384
646
  deleteBranch,
385
647
  updateBranchMetadata,
386
648
  getBranchMetadata,
649
+ getBranchStats,
650
+ getGitBranchesMapping,
651
+ addGitBranchesEntry,
652
+ removeGitBranchesEntry,
653
+ resolveBranch
654
+ },
655
+ migrations: {
387
656
  getBranchMigrationHistory,
388
- executeBranchMigrationPlan,
389
657
  getBranchMigrationPlan,
390
- getBranchStats
658
+ executeBranchMigrationPlan,
659
+ getBranchSchemaHistory,
660
+ compareBranchWithUserSchema,
661
+ compareBranchSchemas,
662
+ updateBranchSchema,
663
+ previewBranchSchemaEdit,
664
+ applyBranchSchemaEdit
665
+ },
666
+ migrationRequests: {
667
+ queryMigrationRequests,
668
+ createMigrationRequest,
669
+ getMigrationRequest,
670
+ updateMigrationRequest,
671
+ listMigrationRequestsCommits,
672
+ compareMigrationRequest,
673
+ getMigrationRequestIsMerged,
674
+ mergeMigrationRequest
391
675
  },
392
676
  table: {
393
677
  createTable,
@@ -398,26 +682,33 @@ const operationsByTag = {
398
682
  getTableColumns,
399
683
  addTableColumn,
400
684
  getColumn,
401
- deleteColumn,
402
- updateColumn
685
+ updateColumn,
686
+ deleteColumn
403
687
  },
404
688
  records: {
405
689
  insertRecord,
690
+ getRecord,
406
691
  insertRecordWithID,
407
692
  updateRecordWithID,
408
693
  upsertRecordWithID,
409
694
  deleteRecord,
410
- getRecord,
411
- bulkInsertTableRecords,
412
- queryTable,
413
- searchBranch
695
+ bulkInsertTableRecords
696
+ },
697
+ searchAndFilter: { queryTable, searchBranch, searchTable, summarizeTable, aggregateTable },
698
+ databases: {
699
+ cPGetDatabaseList,
700
+ cPCreateDatabase,
701
+ cPDeleteDatabase,
702
+ cPGetCPDatabaseMetadata,
703
+ cPUpdateCPDatabaseMetadata,
704
+ listRegions
414
705
  }
415
706
  };
416
707
 
417
708
  function getHostUrl(provider, type) {
418
- if (isValidAlias(provider)) {
709
+ if (isHostProviderAlias(provider)) {
419
710
  return providers[provider][type];
420
- } else if (isValidBuilder(provider)) {
711
+ } else if (isHostProviderBuilder(provider)) {
421
712
  return provider[type];
422
713
  }
423
714
  throw new Error("Invalid API provider");
@@ -432,18 +723,27 @@ const providers = {
432
723
  workspaces: "https://{workspaceId}.staging.xatabase.co"
433
724
  }
434
725
  };
435
- function isValidAlias(alias) {
726
+ function isHostProviderAlias(alias) {
436
727
  return isString(alias) && Object.keys(providers).includes(alias);
437
728
  }
438
- function isValidBuilder(builder) {
729
+ function isHostProviderBuilder(builder) {
439
730
  return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
440
731
  }
732
+ function parseProviderString(provider = "production") {
733
+ if (isHostProviderAlias(provider)) {
734
+ return provider;
735
+ }
736
+ const [main, workspaces] = provider.split(",");
737
+ if (!main || !workspaces)
738
+ return null;
739
+ return { main, workspaces };
740
+ }
441
741
 
442
742
  var __accessCheck$7 = (obj, member, msg) => {
443
743
  if (!member.has(obj))
444
744
  throw TypeError("Cannot " + msg);
445
745
  };
446
- var __privateGet$6 = (obj, member, getter) => {
746
+ var __privateGet$7 = (obj, member, getter) => {
447
747
  __accessCheck$7(obj, member, "read from private field");
448
748
  return getter ? getter.call(obj) : member.get(obj);
449
749
  };
@@ -452,7 +752,7 @@ var __privateAdd$7 = (obj, member, value) => {
452
752
  throw TypeError("Cannot add the same private member more than once");
453
753
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
454
754
  };
455
- var __privateSet$5 = (obj, member, value, setter) => {
755
+ var __privateSet$7 = (obj, member, value, setter) => {
456
756
  __accessCheck$7(obj, member, "write to private field");
457
757
  setter ? setter.call(obj, value) : member.set(obj, value);
458
758
  return value;
@@ -463,46 +763,78 @@ class XataApiClient {
463
763
  __privateAdd$7(this, _extraProps, void 0);
464
764
  __privateAdd$7(this, _namespaces, {});
465
765
  const provider = options.host ?? "production";
466
- const apiKey = options?.apiKey ?? getAPIKey();
766
+ const apiKey = options.apiKey ?? getAPIKey();
767
+ const trace = options.trace ?? defaultTrace;
467
768
  if (!apiKey) {
468
769
  throw new Error("Could not resolve a valid apiKey");
469
770
  }
470
- __privateSet$5(this, _extraProps, {
771
+ __privateSet$7(this, _extraProps, {
471
772
  apiUrl: getHostUrl(provider, "main"),
472
773
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
473
774
  fetchImpl: getFetchImplementation(options.fetch),
474
- apiKey
775
+ apiKey,
776
+ trace
475
777
  });
476
778
  }
477
779
  get user() {
478
- if (!__privateGet$6(this, _namespaces).user)
479
- __privateGet$6(this, _namespaces).user = new UserApi(__privateGet$6(this, _extraProps));
480
- return __privateGet$6(this, _namespaces).user;
780
+ if (!__privateGet$7(this, _namespaces).user)
781
+ __privateGet$7(this, _namespaces).user = new UserApi(__privateGet$7(this, _extraProps));
782
+ return __privateGet$7(this, _namespaces).user;
783
+ }
784
+ get authentication() {
785
+ if (!__privateGet$7(this, _namespaces).authentication)
786
+ __privateGet$7(this, _namespaces).authentication = new AuthenticationApi(__privateGet$7(this, _extraProps));
787
+ return __privateGet$7(this, _namespaces).authentication;
481
788
  }
482
789
  get workspaces() {
483
- if (!__privateGet$6(this, _namespaces).workspaces)
484
- __privateGet$6(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$6(this, _extraProps));
485
- return __privateGet$6(this, _namespaces).workspaces;
790
+ if (!__privateGet$7(this, _namespaces).workspaces)
791
+ __privateGet$7(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$7(this, _extraProps));
792
+ return __privateGet$7(this, _namespaces).workspaces;
486
793
  }
487
- get databases() {
488
- if (!__privateGet$6(this, _namespaces).databases)
489
- __privateGet$6(this, _namespaces).databases = new DatabaseApi(__privateGet$6(this, _extraProps));
490
- return __privateGet$6(this, _namespaces).databases;
794
+ get invites() {
795
+ if (!__privateGet$7(this, _namespaces).invites)
796
+ __privateGet$7(this, _namespaces).invites = new InvitesApi(__privateGet$7(this, _extraProps));
797
+ return __privateGet$7(this, _namespaces).invites;
798
+ }
799
+ get database() {
800
+ if (!__privateGet$7(this, _namespaces).database)
801
+ __privateGet$7(this, _namespaces).database = new DatabaseApi(__privateGet$7(this, _extraProps));
802
+ return __privateGet$7(this, _namespaces).database;
491
803
  }
492
804
  get branches() {
493
- if (!__privateGet$6(this, _namespaces).branches)
494
- __privateGet$6(this, _namespaces).branches = new BranchApi(__privateGet$6(this, _extraProps));
495
- return __privateGet$6(this, _namespaces).branches;
805
+ if (!__privateGet$7(this, _namespaces).branches)
806
+ __privateGet$7(this, _namespaces).branches = new BranchApi(__privateGet$7(this, _extraProps));
807
+ return __privateGet$7(this, _namespaces).branches;
808
+ }
809
+ get migrations() {
810
+ if (!__privateGet$7(this, _namespaces).migrations)
811
+ __privateGet$7(this, _namespaces).migrations = new MigrationsApi(__privateGet$7(this, _extraProps));
812
+ return __privateGet$7(this, _namespaces).migrations;
813
+ }
814
+ get migrationRequests() {
815
+ if (!__privateGet$7(this, _namespaces).migrationRequests)
816
+ __privateGet$7(this, _namespaces).migrationRequests = new MigrationRequestsApi(__privateGet$7(this, _extraProps));
817
+ return __privateGet$7(this, _namespaces).migrationRequests;
496
818
  }
497
819
  get tables() {
498
- if (!__privateGet$6(this, _namespaces).tables)
499
- __privateGet$6(this, _namespaces).tables = new TableApi(__privateGet$6(this, _extraProps));
500
- return __privateGet$6(this, _namespaces).tables;
820
+ if (!__privateGet$7(this, _namespaces).tables)
821
+ __privateGet$7(this, _namespaces).tables = new TableApi(__privateGet$7(this, _extraProps));
822
+ return __privateGet$7(this, _namespaces).tables;
501
823
  }
502
824
  get records() {
503
- if (!__privateGet$6(this, _namespaces).records)
504
- __privateGet$6(this, _namespaces).records = new RecordsApi(__privateGet$6(this, _extraProps));
505
- return __privateGet$6(this, _namespaces).records;
825
+ if (!__privateGet$7(this, _namespaces).records)
826
+ __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
827
+ return __privateGet$7(this, _namespaces).records;
828
+ }
829
+ get searchAndFilter() {
830
+ if (!__privateGet$7(this, _namespaces).searchAndFilter)
831
+ __privateGet$7(this, _namespaces).searchAndFilter = new SearchAndFilterApi(__privateGet$7(this, _extraProps));
832
+ return __privateGet$7(this, _namespaces).searchAndFilter;
833
+ }
834
+ get databases() {
835
+ if (!__privateGet$7(this, _namespaces).databases)
836
+ __privateGet$7(this, _namespaces).databases = new DatabasesApi(__privateGet$7(this, _extraProps));
837
+ return __privateGet$7(this, _namespaces).databases;
506
838
  }
507
839
  }
508
840
  _extraProps = new WeakMap();
@@ -520,17 +852,22 @@ class UserApi {
520
852
  deleteUser() {
521
853
  return operationsByTag.users.deleteUser({ ...this.extraProps });
522
854
  }
855
+ }
856
+ class AuthenticationApi {
857
+ constructor(extraProps) {
858
+ this.extraProps = extraProps;
859
+ }
523
860
  getUserAPIKeys() {
524
- return operationsByTag.users.getUserAPIKeys({ ...this.extraProps });
861
+ return operationsByTag.authentication.getUserAPIKeys({ ...this.extraProps });
525
862
  }
526
863
  createUserAPIKey(keyName) {
527
- return operationsByTag.users.createUserAPIKey({
864
+ return operationsByTag.authentication.createUserAPIKey({
528
865
  pathParams: { keyName },
529
866
  ...this.extraProps
530
867
  });
531
868
  }
532
869
  deleteUserAPIKey(keyName) {
533
- return operationsByTag.users.deleteUserAPIKey({
870
+ return operationsByTag.authentication.deleteUserAPIKey({
534
871
  pathParams: { keyName },
535
872
  ...this.extraProps
536
873
  });
@@ -540,15 +877,15 @@ class WorkspaceApi {
540
877
  constructor(extraProps) {
541
878
  this.extraProps = extraProps;
542
879
  }
880
+ getWorkspacesList() {
881
+ return operationsByTag.workspaces.getWorkspacesList({ ...this.extraProps });
882
+ }
543
883
  createWorkspace(workspaceMeta) {
544
884
  return operationsByTag.workspaces.createWorkspace({
545
885
  body: workspaceMeta,
546
886
  ...this.extraProps
547
887
  });
548
888
  }
549
- getWorkspacesList() {
550
- return operationsByTag.workspaces.getWorkspacesList({ ...this.extraProps });
551
- }
552
889
  getWorkspace(workspaceId) {
553
890
  return operationsByTag.workspaces.getWorkspace({
554
891
  pathParams: { workspaceId },
@@ -587,31 +924,43 @@ class WorkspaceApi {
587
924
  ...this.extraProps
588
925
  });
589
926
  }
927
+ }
928
+ class InvitesApi {
929
+ constructor(extraProps) {
930
+ this.extraProps = extraProps;
931
+ }
590
932
  inviteWorkspaceMember(workspaceId, email, role) {
591
- return operationsByTag.workspaces.inviteWorkspaceMember({
933
+ return operationsByTag.invites.inviteWorkspaceMember({
592
934
  pathParams: { workspaceId },
593
935
  body: { email, role },
594
936
  ...this.extraProps
595
937
  });
596
938
  }
597
- cancelWorkspaceMemberInvite(workspaceId, inviteId) {
598
- return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
939
+ updateWorkspaceMemberInvite(workspaceId, inviteId, role) {
940
+ return operationsByTag.invites.updateWorkspaceMemberInvite({
599
941
  pathParams: { workspaceId, inviteId },
942
+ body: { role },
600
943
  ...this.extraProps
601
944
  });
602
945
  }
603
- resendWorkspaceMemberInvite(workspaceId, inviteId) {
604
- return operationsByTag.workspaces.resendWorkspaceMemberInvite({
946
+ cancelWorkspaceMemberInvite(workspaceId, inviteId) {
947
+ return operationsByTag.invites.cancelWorkspaceMemberInvite({
605
948
  pathParams: { workspaceId, inviteId },
606
949
  ...this.extraProps
607
950
  });
608
951
  }
609
952
  acceptWorkspaceMemberInvite(workspaceId, inviteKey) {
610
- return operationsByTag.workspaces.acceptWorkspaceMemberInvite({
953
+ return operationsByTag.invites.acceptWorkspaceMemberInvite({
611
954
  pathParams: { workspaceId, inviteKey },
612
955
  ...this.extraProps
613
956
  });
614
957
  }
958
+ resendWorkspaceMemberInvite(workspaceId, inviteId) {
959
+ return operationsByTag.invites.resendWorkspaceMemberInvite({
960
+ pathParams: { workspaceId, inviteId },
961
+ ...this.extraProps
962
+ });
963
+ }
615
964
  }
616
965
  class DatabaseApi {
617
966
  constructor(extraProps) {
@@ -636,6 +985,19 @@ class DatabaseApi {
636
985
  ...this.extraProps
637
986
  });
638
987
  }
988
+ getDatabaseMetadata(workspace, dbName) {
989
+ return operationsByTag.database.getDatabaseMetadata({
990
+ pathParams: { workspace, dbName },
991
+ ...this.extraProps
992
+ });
993
+ }
994
+ updateDatabaseMetadata(workspace, dbName, options = {}) {
995
+ return operationsByTag.database.updateDatabaseMetadata({
996
+ pathParams: { workspace, dbName },
997
+ body: options,
998
+ ...this.extraProps
999
+ });
1000
+ }
639
1001
  }
640
1002
  class BranchApi {
641
1003
  constructor(extraProps) {
@@ -653,10 +1015,10 @@ class BranchApi {
653
1015
  ...this.extraProps
654
1016
  });
655
1017
  }
656
- createBranch(workspace, database, branch, from = "", options = {}) {
1018
+ createBranch(workspace, database, branch, from, options = {}) {
657
1019
  return operationsByTag.branch.createBranch({
658
1020
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
659
- queryParams: { from },
1021
+ queryParams: isString(from) ? { from } : void 0,
660
1022
  body: options,
661
1023
  ...this.extraProps
662
1024
  });
@@ -680,30 +1042,36 @@ class BranchApi {
680
1042
  ...this.extraProps
681
1043
  });
682
1044
  }
683
- getBranchMigrationHistory(workspace, database, branch, options = {}) {
684
- return operationsByTag.branch.getBranchMigrationHistory({
1045
+ getBranchStats(workspace, database, branch) {
1046
+ return operationsByTag.branch.getBranchStats({
685
1047
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
686
- body: options,
687
1048
  ...this.extraProps
688
1049
  });
689
1050
  }
690
- executeBranchMigrationPlan(workspace, database, branch, migrationPlan) {
691
- return operationsByTag.branch.executeBranchMigrationPlan({
692
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
693
- body: migrationPlan,
1051
+ getGitBranchesMapping(workspace, dbName) {
1052
+ return operationsByTag.branch.getGitBranchesMapping({
1053
+ pathParams: { workspace, dbName },
694
1054
  ...this.extraProps
695
1055
  });
696
1056
  }
697
- getBranchMigrationPlan(workspace, database, branch, schema) {
698
- return operationsByTag.branch.getBranchMigrationPlan({
699
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
700
- body: schema,
1057
+ addGitBranchesEntry(workspace, dbName, body) {
1058
+ return operationsByTag.branch.addGitBranchesEntry({
1059
+ pathParams: { workspace, dbName },
1060
+ body,
701
1061
  ...this.extraProps
702
1062
  });
703
1063
  }
704
- getBranchStats(workspace, database, branch) {
705
- return operationsByTag.branch.getBranchStats({
706
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1064
+ removeGitBranchesEntry(workspace, dbName, gitBranch) {
1065
+ return operationsByTag.branch.removeGitBranchesEntry({
1066
+ pathParams: { workspace, dbName },
1067
+ queryParams: { gitBranch },
1068
+ ...this.extraProps
1069
+ });
1070
+ }
1071
+ resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
1072
+ return operationsByTag.branch.resolveBranch({
1073
+ pathParams: { workspace, dbName },
1074
+ queryParams: { gitBranch, fallbackBranch },
707
1075
  ...this.extraProps
708
1076
  });
709
1077
  }
@@ -763,16 +1131,16 @@ class TableApi {
763
1131
  ...this.extraProps
764
1132
  });
765
1133
  }
766
- deleteColumn(workspace, database, branch, tableName, columnName) {
767
- return operationsByTag.table.deleteColumn({
1134
+ updateColumn(workspace, database, branch, tableName, columnName, options) {
1135
+ return operationsByTag.table.updateColumn({
768
1136
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, columnName },
1137
+ body: options,
769
1138
  ...this.extraProps
770
1139
  });
771
1140
  }
772
- updateColumn(workspace, database, branch, tableName, columnName, options) {
773
- return operationsByTag.table.updateColumn({
1141
+ deleteColumn(workspace, database, branch, tableName, columnName) {
1142
+ return operationsByTag.table.deleteColumn({
774
1143
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, columnName },
775
- body: options,
776
1144
  ...this.extraProps
777
1145
  });
778
1146
  }
@@ -781,13 +1149,21 @@ class RecordsApi {
781
1149
  constructor(extraProps) {
782
1150
  this.extraProps = extraProps;
783
1151
  }
784
- insertRecord(workspace, database, branch, tableName, record) {
1152
+ insertRecord(workspace, database, branch, tableName, record, options = {}) {
785
1153
  return operationsByTag.records.insertRecord({
786
1154
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1155
+ queryParams: options,
787
1156
  body: record,
788
1157
  ...this.extraProps
789
1158
  });
790
1159
  }
1160
+ getRecord(workspace, database, branch, tableName, recordId, options = {}) {
1161
+ return operationsByTag.records.getRecord({
1162
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1163
+ queryParams: options,
1164
+ ...this.extraProps
1165
+ });
1166
+ }
791
1167
  insertRecordWithID(workspace, database, branch, tableName, recordId, record, options = {}) {
792
1168
  return operationsByTag.records.insertRecordWithID({
793
1169
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
@@ -812,88 +1188,292 @@ class RecordsApi {
812
1188
  ...this.extraProps
813
1189
  });
814
1190
  }
815
- deleteRecord(workspace, database, branch, tableName, recordId) {
1191
+ deleteRecord(workspace, database, branch, tableName, recordId, options = {}) {
816
1192
  return operationsByTag.records.deleteRecord({
817
1193
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1194
+ queryParams: options,
818
1195
  ...this.extraProps
819
1196
  });
820
1197
  }
821
- getRecord(workspace, database, branch, tableName, recordId, options = {}) {
822
- return operationsByTag.records.getRecord({
823
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
824
- ...this.extraProps
825
- });
826
- }
827
- bulkInsertTableRecords(workspace, database, branch, tableName, records) {
1198
+ bulkInsertTableRecords(workspace, database, branch, tableName, records, options = {}) {
828
1199
  return operationsByTag.records.bulkInsertTableRecords({
829
1200
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1201
+ queryParams: options,
830
1202
  body: { records },
831
1203
  ...this.extraProps
832
1204
  });
833
1205
  }
1206
+ }
1207
+ class SearchAndFilterApi {
1208
+ constructor(extraProps) {
1209
+ this.extraProps = extraProps;
1210
+ }
834
1211
  queryTable(workspace, database, branch, tableName, query) {
835
- return operationsByTag.records.queryTable({
1212
+ return operationsByTag.searchAndFilter.queryTable({
1213
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1214
+ body: query,
1215
+ ...this.extraProps
1216
+ });
1217
+ }
1218
+ searchTable(workspace, database, branch, tableName, query) {
1219
+ return operationsByTag.searchAndFilter.searchTable({
836
1220
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
837
1221
  body: query,
838
1222
  ...this.extraProps
839
1223
  });
840
1224
  }
841
1225
  searchBranch(workspace, database, branch, query) {
842
- return operationsByTag.records.searchBranch({
1226
+ return operationsByTag.searchAndFilter.searchBranch({
843
1227
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
844
1228
  body: query,
845
1229
  ...this.extraProps
846
1230
  });
847
1231
  }
848
- }
849
-
850
- class XataApiPlugin {
851
- async build(options) {
852
- const { fetchImpl, apiKey } = await options.getFetchProps();
853
- return new XataApiClient({ fetch: fetchImpl, apiKey });
1232
+ summarizeTable(workspace, database, branch, tableName, query) {
1233
+ return operationsByTag.searchAndFilter.summarizeTable({
1234
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1235
+ body: query,
1236
+ ...this.extraProps
1237
+ });
1238
+ }
1239
+ aggregateTable(workspace, database, branch, tableName, query) {
1240
+ return operationsByTag.searchAndFilter.aggregateTable({
1241
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1242
+ body: query,
1243
+ ...this.extraProps
1244
+ });
854
1245
  }
855
1246
  }
856
-
857
- class XataPlugin {
858
- }
859
-
860
- var __accessCheck$6 = (obj, member, msg) => {
861
- if (!member.has(obj))
862
- throw TypeError("Cannot " + msg);
863
- };
864
- var __privateGet$5 = (obj, member, getter) => {
865
- __accessCheck$6(obj, member, "read from private field");
866
- return getter ? getter.call(obj) : member.get(obj);
867
- };
868
- var __privateAdd$6 = (obj, member, value) => {
869
- if (member.has(obj))
870
- throw TypeError("Cannot add the same private member more than once");
871
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
872
- };
873
- var __privateSet$4 = (obj, member, value, setter) => {
874
- __accessCheck$6(obj, member, "write to private field");
875
- setter ? setter.call(obj, value) : member.set(obj, value);
876
- return value;
877
- };
878
- var _query;
879
- class Page {
880
- constructor(query, meta, records = []) {
881
- __privateAdd$6(this, _query, void 0);
882
- __privateSet$4(this, _query, query);
883
- this.meta = meta;
884
- this.records = records;
1247
+ class MigrationRequestsApi {
1248
+ constructor(extraProps) {
1249
+ this.extraProps = extraProps;
885
1250
  }
886
- async nextPage(size, offset) {
887
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, after: this.meta.page.cursor } });
1251
+ queryMigrationRequests(workspace, database, options = {}) {
1252
+ return operationsByTag.migrationRequests.queryMigrationRequests({
1253
+ pathParams: { workspace, dbName: database },
1254
+ body: options,
1255
+ ...this.extraProps
1256
+ });
1257
+ }
1258
+ createMigrationRequest(workspace, database, options) {
1259
+ return operationsByTag.migrationRequests.createMigrationRequest({
1260
+ pathParams: { workspace, dbName: database },
1261
+ body: options,
1262
+ ...this.extraProps
1263
+ });
1264
+ }
1265
+ getMigrationRequest(workspace, database, migrationRequest) {
1266
+ return operationsByTag.migrationRequests.getMigrationRequest({
1267
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1268
+ ...this.extraProps
1269
+ });
1270
+ }
1271
+ updateMigrationRequest(workspace, database, migrationRequest, options) {
1272
+ return operationsByTag.migrationRequests.updateMigrationRequest({
1273
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1274
+ body: options,
1275
+ ...this.extraProps
1276
+ });
1277
+ }
1278
+ listMigrationRequestsCommits(workspace, database, migrationRequest, options = {}) {
1279
+ return operationsByTag.migrationRequests.listMigrationRequestsCommits({
1280
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1281
+ body: options,
1282
+ ...this.extraProps
1283
+ });
1284
+ }
1285
+ compareMigrationRequest(workspace, database, migrationRequest) {
1286
+ return operationsByTag.migrationRequests.compareMigrationRequest({
1287
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1288
+ ...this.extraProps
1289
+ });
1290
+ }
1291
+ getMigrationRequestIsMerged(workspace, database, migrationRequest) {
1292
+ return operationsByTag.migrationRequests.getMigrationRequestIsMerged({
1293
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1294
+ ...this.extraProps
1295
+ });
1296
+ }
1297
+ mergeMigrationRequest(workspace, database, migrationRequest) {
1298
+ return operationsByTag.migrationRequests.mergeMigrationRequest({
1299
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1300
+ ...this.extraProps
1301
+ });
1302
+ }
1303
+ }
1304
+ class MigrationsApi {
1305
+ constructor(extraProps) {
1306
+ this.extraProps = extraProps;
1307
+ }
1308
+ getBranchMigrationHistory(workspace, database, branch, options = {}) {
1309
+ return operationsByTag.migrations.getBranchMigrationHistory({
1310
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1311
+ body: options,
1312
+ ...this.extraProps
1313
+ });
1314
+ }
1315
+ getBranchMigrationPlan(workspace, database, branch, schema) {
1316
+ return operationsByTag.migrations.getBranchMigrationPlan({
1317
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1318
+ body: schema,
1319
+ ...this.extraProps
1320
+ });
1321
+ }
1322
+ executeBranchMigrationPlan(workspace, database, branch, migrationPlan) {
1323
+ return operationsByTag.migrations.executeBranchMigrationPlan({
1324
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1325
+ body: migrationPlan,
1326
+ ...this.extraProps
1327
+ });
1328
+ }
1329
+ getBranchSchemaHistory(workspace, database, branch, options = {}) {
1330
+ return operationsByTag.migrations.getBranchSchemaHistory({
1331
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1332
+ body: options,
1333
+ ...this.extraProps
1334
+ });
1335
+ }
1336
+ compareBranchWithUserSchema(workspace, database, branch, schema) {
1337
+ return operationsByTag.migrations.compareBranchWithUserSchema({
1338
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1339
+ body: { schema },
1340
+ ...this.extraProps
1341
+ });
1342
+ }
1343
+ compareBranchSchemas(workspace, database, branch, branchName, schema) {
1344
+ return operationsByTag.migrations.compareBranchSchemas({
1345
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, branchName },
1346
+ body: { schema },
1347
+ ...this.extraProps
1348
+ });
1349
+ }
1350
+ updateBranchSchema(workspace, database, branch, migration) {
1351
+ return operationsByTag.migrations.updateBranchSchema({
1352
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1353
+ body: migration,
1354
+ ...this.extraProps
1355
+ });
1356
+ }
1357
+ previewBranchSchemaEdit(workspace, database, branch, migration) {
1358
+ return operationsByTag.migrations.previewBranchSchemaEdit({
1359
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1360
+ body: migration,
1361
+ ...this.extraProps
1362
+ });
1363
+ }
1364
+ applyBranchSchemaEdit(workspace, database, branch, edits) {
1365
+ return operationsByTag.migrations.applyBranchSchemaEdit({
1366
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1367
+ body: { edits },
1368
+ ...this.extraProps
1369
+ });
1370
+ }
1371
+ }
1372
+ class DatabasesApi {
1373
+ constructor(extraProps) {
1374
+ this.extraProps = extraProps;
1375
+ }
1376
+ getDatabaseList(workspaceId) {
1377
+ return operationsByTag.databases.cPGetDatabaseList({
1378
+ pathParams: { workspaceId },
1379
+ ...this.extraProps
1380
+ });
1381
+ }
1382
+ createDatabase(workspaceId, dbName, options) {
1383
+ return operationsByTag.databases.cPCreateDatabase({
1384
+ pathParams: { workspaceId, dbName },
1385
+ body: options,
1386
+ ...this.extraProps
1387
+ });
1388
+ }
1389
+ deleteDatabase(workspaceId, dbName) {
1390
+ return operationsByTag.databases.cPDeleteDatabase({
1391
+ pathParams: { workspaceId, dbName },
1392
+ ...this.extraProps
1393
+ });
1394
+ }
1395
+ getDatabaseMetadata(workspaceId, dbName) {
1396
+ return operationsByTag.databases.cPGetCPDatabaseMetadata({
1397
+ pathParams: { workspaceId, dbName },
1398
+ ...this.extraProps
1399
+ });
1400
+ }
1401
+ updateDatabaseMetadata(workspaceId, dbName, metadata) {
1402
+ return operationsByTag.databases.cPUpdateCPDatabaseMetadata({
1403
+ pathParams: { workspaceId, dbName },
1404
+ body: metadata,
1405
+ ...this.extraProps
1406
+ });
1407
+ }
1408
+ listRegions(workspaceId) {
1409
+ return operationsByTag.databases.listRegions({
1410
+ pathParams: { workspaceId },
1411
+ ...this.extraProps
1412
+ });
1413
+ }
1414
+ }
1415
+
1416
+ class XataApiPlugin {
1417
+ async build(options) {
1418
+ const { fetchImpl, apiKey } = await options.getFetchProps();
1419
+ return new XataApiClient({ fetch: fetchImpl, apiKey });
1420
+ }
1421
+ }
1422
+
1423
+ class XataPlugin {
1424
+ }
1425
+
1426
+ function generateUUID() {
1427
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
1428
+ const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
1429
+ return v.toString(16);
1430
+ });
1431
+ }
1432
+
1433
+ function cleanFilter(filter) {
1434
+ if (!filter)
1435
+ return void 0;
1436
+ const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
1437
+ return values.length > 0 ? filter : void 0;
1438
+ }
1439
+
1440
+ var __accessCheck$6 = (obj, member, msg) => {
1441
+ if (!member.has(obj))
1442
+ throw TypeError("Cannot " + msg);
1443
+ };
1444
+ var __privateGet$6 = (obj, member, getter) => {
1445
+ __accessCheck$6(obj, member, "read from private field");
1446
+ return getter ? getter.call(obj) : member.get(obj);
1447
+ };
1448
+ var __privateAdd$6 = (obj, member, value) => {
1449
+ if (member.has(obj))
1450
+ throw TypeError("Cannot add the same private member more than once");
1451
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1452
+ };
1453
+ var __privateSet$6 = (obj, member, value, setter) => {
1454
+ __accessCheck$6(obj, member, "write to private field");
1455
+ setter ? setter.call(obj, value) : member.set(obj, value);
1456
+ return value;
1457
+ };
1458
+ var _query, _page;
1459
+ class Page {
1460
+ constructor(query, meta, records = []) {
1461
+ __privateAdd$6(this, _query, void 0);
1462
+ __privateSet$6(this, _query, query);
1463
+ this.meta = meta;
1464
+ this.records = new RecordArray(this, records);
1465
+ }
1466
+ async nextPage(size, offset) {
1467
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
888
1468
  }
889
1469
  async previousPage(size, offset) {
890
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, before: this.meta.page.cursor } });
1470
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
891
1471
  }
892
1472
  async firstPage(size, offset) {
893
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, first: this.meta.page.cursor } });
1473
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
894
1474
  }
895
1475
  async lastPage(size, offset) {
896
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, last: this.meta.page.cursor } });
1476
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
897
1477
  }
898
1478
  hasNextPage() {
899
1479
  return this.meta.page.more;
@@ -901,15 +1481,62 @@ class Page {
901
1481
  }
902
1482
  _query = new WeakMap();
903
1483
  const PAGINATION_MAX_SIZE = 200;
904
- const PAGINATION_DEFAULT_SIZE = 200;
1484
+ const PAGINATION_DEFAULT_SIZE = 20;
905
1485
  const PAGINATION_MAX_OFFSET = 800;
906
1486
  const PAGINATION_DEFAULT_OFFSET = 0;
1487
+ function isCursorPaginationOptions(options) {
1488
+ return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
1489
+ }
1490
+ const _RecordArray = class extends Array {
1491
+ constructor(...args) {
1492
+ super(..._RecordArray.parseConstructorParams(...args));
1493
+ __privateAdd$6(this, _page, void 0);
1494
+ __privateSet$6(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
1495
+ }
1496
+ static parseConstructorParams(...args) {
1497
+ if (args.length === 1 && typeof args[0] === "number") {
1498
+ return new Array(args[0]);
1499
+ }
1500
+ if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
1501
+ const result = args[1] ?? args[0].records ?? [];
1502
+ return new Array(...result);
1503
+ }
1504
+ return new Array(...args);
1505
+ }
1506
+ toArray() {
1507
+ return new Array(...this);
1508
+ }
1509
+ map(callbackfn, thisArg) {
1510
+ return this.toArray().map(callbackfn, thisArg);
1511
+ }
1512
+ async nextPage(size, offset) {
1513
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1514
+ return new _RecordArray(newPage);
1515
+ }
1516
+ async previousPage(size, offset) {
1517
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1518
+ return new _RecordArray(newPage);
1519
+ }
1520
+ async firstPage(size, offset) {
1521
+ const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1522
+ return new _RecordArray(newPage);
1523
+ }
1524
+ async lastPage(size, offset) {
1525
+ const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1526
+ return new _RecordArray(newPage);
1527
+ }
1528
+ hasNextPage() {
1529
+ return __privateGet$6(this, _page).meta.page.more;
1530
+ }
1531
+ };
1532
+ let RecordArray = _RecordArray;
1533
+ _page = new WeakMap();
907
1534
 
908
1535
  var __accessCheck$5 = (obj, member, msg) => {
909
1536
  if (!member.has(obj))
910
1537
  throw TypeError("Cannot " + msg);
911
1538
  };
912
- var __privateGet$4 = (obj, member, getter) => {
1539
+ var __privateGet$5 = (obj, member, getter) => {
913
1540
  __accessCheck$5(obj, member, "read from private field");
914
1541
  return getter ? getter.call(obj) : member.get(obj);
915
1542
  };
@@ -918,34 +1545,40 @@ var __privateAdd$5 = (obj, member, value) => {
918
1545
  throw TypeError("Cannot add the same private member more than once");
919
1546
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
920
1547
  };
921
- var __privateSet$3 = (obj, member, value, setter) => {
1548
+ var __privateSet$5 = (obj, member, value, setter) => {
922
1549
  __accessCheck$5(obj, member, "write to private field");
923
1550
  setter ? setter.call(obj, value) : member.set(obj, value);
924
1551
  return value;
925
1552
  };
926
- var _table$1, _repository, _data;
1553
+ var __privateMethod$3 = (obj, member, method) => {
1554
+ __accessCheck$5(obj, member, "access private method");
1555
+ return method;
1556
+ };
1557
+ var _table$1, _repository, _data, _cleanFilterConstraint, cleanFilterConstraint_fn;
927
1558
  const _Query = class {
928
- constructor(repository, table, data, parent) {
1559
+ constructor(repository, table, data, rawParent) {
1560
+ __privateAdd$5(this, _cleanFilterConstraint);
929
1561
  __privateAdd$5(this, _table$1, void 0);
930
1562
  __privateAdd$5(this, _repository, void 0);
931
1563
  __privateAdd$5(this, _data, { filter: {} });
932
1564
  this.meta = { page: { cursor: "start", more: true } };
933
- this.records = [];
934
- __privateSet$3(this, _table$1, table);
1565
+ this.records = new RecordArray(this, []);
1566
+ __privateSet$5(this, _table$1, table);
935
1567
  if (repository) {
936
- __privateSet$3(this, _repository, repository);
1568
+ __privateSet$5(this, _repository, repository);
937
1569
  } else {
938
- __privateSet$3(this, _repository, this);
1570
+ __privateSet$5(this, _repository, this);
939
1571
  }
940
- __privateGet$4(this, _data).filter = data.filter ?? parent?.filter ?? {};
941
- __privateGet$4(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
942
- __privateGet$4(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
943
- __privateGet$4(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
944
- __privateGet$4(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
945
- __privateGet$4(this, _data).sort = data.sort ?? parent?.sort;
946
- __privateGet$4(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
947
- __privateGet$4(this, _data).page = data.page ?? parent?.page;
948
- __privateGet$4(this, _data).cache = data.cache ?? parent?.cache;
1572
+ const parent = cleanParent(data, rawParent);
1573
+ __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
1574
+ __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
1575
+ __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
1576
+ __privateGet$5(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
1577
+ __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1578
+ __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1579
+ __privateGet$5(this, _data).columns = data.columns ?? parent?.columns;
1580
+ __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1581
+ __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
949
1582
  this.any = this.any.bind(this);
950
1583
  this.all = this.all.bind(this);
951
1584
  this.not = this.not.bind(this);
@@ -956,83 +1589,121 @@ const _Query = class {
956
1589
  Object.defineProperty(this, "repository", { enumerable: false });
957
1590
  }
958
1591
  getQueryOptions() {
959
- return __privateGet$4(this, _data);
1592
+ return __privateGet$5(this, _data);
960
1593
  }
961
1594
  key() {
962
- const { columns = [], filter = {}, sort = [], page = {} } = __privateGet$4(this, _data);
963
- const key = JSON.stringify({ columns, filter, sort, page });
1595
+ const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$5(this, _data);
1596
+ const key = JSON.stringify({ columns, filter, sort, pagination });
964
1597
  return toBase64(key);
965
1598
  }
966
1599
  any(...queries) {
967
1600
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
968
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $any } }, __privateGet$4(this, _data));
1601
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
969
1602
  }
970
1603
  all(...queries) {
971
1604
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
972
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1605
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
973
1606
  }
974
1607
  not(...queries) {
975
1608
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
976
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $not } }, __privateGet$4(this, _data));
1609
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
977
1610
  }
978
1611
  none(...queries) {
979
1612
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
980
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $none } }, __privateGet$4(this, _data));
1613
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
981
1614
  }
982
1615
  filter(a, b) {
983
1616
  if (arguments.length === 1) {
984
- const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
985
- const $all = compact([__privateGet$4(this, _data).filter?.$all].flat().concat(constraints));
986
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1617
+ const constraints = Object.entries(a ?? {}).map(([column, constraint]) => ({
1618
+ [column]: __privateMethod$3(this, _cleanFilterConstraint, cleanFilterConstraint_fn).call(this, column, constraint)
1619
+ }));
1620
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1621
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
987
1622
  } else {
988
- const $all = compact([__privateGet$4(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
989
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { filter: { $all } }, __privateGet$4(this, _data));
1623
+ const constraints = isDefined(a) && isDefined(b) ? [{ [a]: __privateMethod$3(this, _cleanFilterConstraint, cleanFilterConstraint_fn).call(this, a, b) }] : void 0;
1624
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1625
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
990
1626
  }
991
1627
  }
992
- sort(column, direction) {
993
- const originalSort = [__privateGet$4(this, _data).sort ?? []].flat();
1628
+ sort(column, direction = "asc") {
1629
+ const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
994
1630
  const sort = [...originalSort, { column, direction }];
995
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { sort }, __privateGet$4(this, _data));
1631
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
996
1632
  }
997
1633
  select(columns) {
998
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { columns }, __privateGet$4(this, _data));
1634
+ return new _Query(
1635
+ __privateGet$5(this, _repository),
1636
+ __privateGet$5(this, _table$1),
1637
+ { columns },
1638
+ __privateGet$5(this, _data)
1639
+ );
999
1640
  }
1000
1641
  getPaginated(options = {}) {
1001
- const query = new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), options, __privateGet$4(this, _data));
1002
- return __privateGet$4(this, _repository).query(query);
1642
+ const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
1643
+ return __privateGet$5(this, _repository).query(query);
1003
1644
  }
1004
1645
  async *[Symbol.asyncIterator]() {
1005
- for await (const [record] of this.getIterator(1)) {
1646
+ for await (const [record] of this.getIterator({ batchSize: 1 })) {
1006
1647
  yield record;
1007
1648
  }
1008
1649
  }
1009
- async *getIterator(chunk, options = {}) {
1010
- let offset = 0;
1011
- let end = false;
1012
- while (!end) {
1013
- const { records, meta } = await this.getPaginated({ ...options, page: { size: chunk, offset } });
1014
- yield records;
1015
- offset += chunk;
1016
- end = !meta.page.more;
1650
+ async *getIterator(options = {}) {
1651
+ const { batchSize = 1 } = options;
1652
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
1653
+ let more = page.hasNextPage();
1654
+ yield page.records;
1655
+ while (more) {
1656
+ page = await page.nextPage();
1657
+ more = page.hasNextPage();
1658
+ yield page.records;
1017
1659
  }
1018
1660
  }
1019
1661
  async getMany(options = {}) {
1020
- const { records } = await this.getPaginated(options);
1021
- return records;
1662
+ const { pagination = {}, ...rest } = options;
1663
+ const { size = PAGINATION_DEFAULT_SIZE, offset } = pagination;
1664
+ const batchSize = size <= PAGINATION_MAX_SIZE ? size : PAGINATION_MAX_SIZE;
1665
+ let page = await this.getPaginated({ ...rest, pagination: { size: batchSize, offset } });
1666
+ const results = [...page.records];
1667
+ while (page.hasNextPage() && results.length < size) {
1668
+ page = await page.nextPage();
1669
+ results.push(...page.records);
1670
+ }
1671
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1672
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1673
+ }
1674
+ const array = new RecordArray(page, results.slice(0, size));
1675
+ return array;
1022
1676
  }
1023
- async getAll(chunk = PAGINATION_MAX_SIZE, options = {}) {
1677
+ async getAll(options = {}) {
1678
+ const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
1024
1679
  const results = [];
1025
- for await (const page of this.getIterator(chunk, options)) {
1680
+ for await (const page of this.getIterator({ ...rest, batchSize })) {
1026
1681
  results.push(...page);
1027
1682
  }
1028
1683
  return results;
1029
1684
  }
1030
1685
  async getFirst(options = {}) {
1031
- const records = await this.getMany({ ...options, page: { size: 1 } });
1032
- return records[0] || null;
1686
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1687
+ return records[0] ?? null;
1688
+ }
1689
+ async getFirstOrThrow(options = {}) {
1690
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1691
+ if (records[0] === void 0)
1692
+ throw new Error("No results found.");
1693
+ return records[0];
1694
+ }
1695
+ async summarize(params = {}) {
1696
+ const { summaries, summariesFilter, ...options } = params;
1697
+ const query = new _Query(
1698
+ __privateGet$5(this, _repository),
1699
+ __privateGet$5(this, _table$1),
1700
+ options,
1701
+ __privateGet$5(this, _data)
1702
+ );
1703
+ return __privateGet$5(this, _repository).summarizeTable(query, summaries, summariesFilter);
1033
1704
  }
1034
1705
  cache(ttl) {
1035
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { cache: ttl }, __privateGet$4(this, _data));
1706
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1036
1707
  }
1037
1708
  nextPage(size, offset) {
1038
1709
  return this.firstPage(size, offset);
@@ -1041,10 +1712,10 @@ const _Query = class {
1041
1712
  return this.firstPage(size, offset);
1042
1713
  }
1043
1714
  firstPage(size, offset) {
1044
- return this.getPaginated({ page: { size, offset } });
1715
+ return this.getPaginated({ pagination: { size, offset } });
1045
1716
  }
1046
1717
  lastPage(size, offset) {
1047
- return this.getPaginated({ page: { size, offset, before: "end" } });
1718
+ return this.getPaginated({ pagination: { size, offset, before: "end" } });
1048
1719
  }
1049
1720
  hasNextPage() {
1050
1721
  return this.meta.page.more;
@@ -1054,12 +1725,31 @@ let Query = _Query;
1054
1725
  _table$1 = new WeakMap();
1055
1726
  _repository = new WeakMap();
1056
1727
  _data = new WeakMap();
1728
+ _cleanFilterConstraint = new WeakSet();
1729
+ cleanFilterConstraint_fn = function(column, value) {
1730
+ const columnType = __privateGet$5(this, _table$1).schema?.columns.find(({ name }) => name === column)?.type;
1731
+ if (columnType === "multiple" && (isString(value) || isStringArray(value))) {
1732
+ return { $includes: value };
1733
+ }
1734
+ if (columnType === "link" && isObject(value) && isString(value.id)) {
1735
+ return value.id;
1736
+ }
1737
+ return value;
1738
+ };
1739
+ function cleanParent(data, parent) {
1740
+ if (isCursorPaginationOptions(data.pagination)) {
1741
+ return { ...parent, sorting: void 0, filter: void 0 };
1742
+ }
1743
+ return parent;
1744
+ }
1057
1745
 
1058
1746
  function isIdentifiable(x) {
1059
1747
  return isObject(x) && isString(x?.id);
1060
1748
  }
1061
1749
  function isXataRecord(x) {
1062
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1750
+ const record = x;
1751
+ const metadata = record?.getMetadata();
1752
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1063
1753
  }
1064
1754
 
1065
1755
  function isSortFilterString(value) {
@@ -1089,7 +1779,7 @@ var __accessCheck$4 = (obj, member, msg) => {
1089
1779
  if (!member.has(obj))
1090
1780
  throw TypeError("Cannot " + msg);
1091
1781
  };
1092
- var __privateGet$3 = (obj, member, getter) => {
1782
+ var __privateGet$4 = (obj, member, getter) => {
1093
1783
  __accessCheck$4(obj, member, "read from private field");
1094
1784
  return getter ? getter.call(obj) : member.get(obj);
1095
1785
  };
@@ -1098,7 +1788,7 @@ var __privateAdd$4 = (obj, member, value) => {
1098
1788
  throw TypeError("Cannot add the same private member more than once");
1099
1789
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1100
1790
  };
1101
- var __privateSet$2 = (obj, member, value, setter) => {
1791
+ var __privateSet$4 = (obj, member, value, setter) => {
1102
1792
  __accessCheck$4(obj, member, "write to private field");
1103
1793
  setter ? setter.call(obj, value) : member.set(obj, value);
1104
1794
  return value;
@@ -1107,304 +1797,444 @@ var __privateMethod$2 = (obj, member, method) => {
1107
1797
  __accessCheck$4(obj, member, "access private method");
1108
1798
  return method;
1109
1799
  };
1110
- var _table, _links, _getFetchProps, _cache, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _invalidateCache, invalidateCache_fn, _setCacheRecord, setCacheRecord_fn, _getCacheRecord, getCacheRecord_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn;
1800
+ var _table, _getFetchProps, _db, _cache, _schemaTables$2, _trace, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaTables$1, getSchemaTables_fn$1;
1111
1801
  class Repository extends Query {
1112
1802
  }
1113
1803
  class RestRepository extends Query {
1114
1804
  constructor(options) {
1115
- super(null, options.table, {});
1805
+ super(
1806
+ null,
1807
+ { name: options.table, schema: options.schemaTables?.find((table) => table.name === options.table) },
1808
+ {}
1809
+ );
1116
1810
  __privateAdd$4(this, _insertRecordWithoutId);
1117
1811
  __privateAdd$4(this, _insertRecordWithId);
1118
1812
  __privateAdd$4(this, _bulkInsertTableRecords);
1119
1813
  __privateAdd$4(this, _updateRecordWithID);
1120
1814
  __privateAdd$4(this, _upsertRecordWithID);
1121
1815
  __privateAdd$4(this, _deleteRecord);
1122
- __privateAdd$4(this, _invalidateCache);
1123
- __privateAdd$4(this, _setCacheRecord);
1124
- __privateAdd$4(this, _getCacheRecord);
1125
1816
  __privateAdd$4(this, _setCacheQuery);
1126
1817
  __privateAdd$4(this, _getCacheQuery);
1818
+ __privateAdd$4(this, _getSchemaTables$1);
1127
1819
  __privateAdd$4(this, _table, void 0);
1128
- __privateAdd$4(this, _links, void 0);
1129
1820
  __privateAdd$4(this, _getFetchProps, void 0);
1821
+ __privateAdd$4(this, _db, void 0);
1130
1822
  __privateAdd$4(this, _cache, void 0);
1131
- __privateSet$2(this, _table, options.table);
1132
- __privateSet$2(this, _links, options.links ?? {});
1133
- __privateSet$2(this, _getFetchProps, options.pluginOptions.getFetchProps);
1134
- this.db = options.db;
1135
- __privateSet$2(this, _cache, options.pluginOptions.cache);
1136
- }
1137
- async create(a, b) {
1138
- if (Array.isArray(a)) {
1139
- const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1140
- await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1141
- return records;
1142
- }
1143
- if (isString(a) && isObject(b)) {
1144
- if (a === "")
1145
- throw new Error("The id can't be empty");
1146
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1147
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1148
- return record;
1149
- }
1150
- if (isObject(a) && isString(a.id)) {
1151
- if (a.id === "")
1152
- throw new Error("The id can't be empty");
1153
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1154
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1155
- return record;
1156
- }
1157
- if (isObject(a)) {
1158
- const record = await __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1159
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1160
- return record;
1161
- }
1162
- throw new Error("Invalid arguments for create method");
1163
- }
1164
- async read(recordId) {
1165
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, recordId);
1166
- if (cacheRecord)
1167
- return cacheRecord;
1168
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1169
- try {
1170
- const response = await getRecord({
1171
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1172
- ...fetchProps
1823
+ __privateAdd$4(this, _schemaTables$2, void 0);
1824
+ __privateAdd$4(this, _trace, void 0);
1825
+ __privateSet$4(this, _table, options.table);
1826
+ __privateSet$4(this, _db, options.db);
1827
+ __privateSet$4(this, _cache, options.pluginOptions.cache);
1828
+ __privateSet$4(this, _schemaTables$2, options.schemaTables);
1829
+ __privateSet$4(this, _getFetchProps, async () => {
1830
+ const props = await options.pluginOptions.getFetchProps();
1831
+ return { ...props, sessionID: generateUUID() };
1832
+ });
1833
+ const trace = options.pluginOptions.trace ?? defaultTrace;
1834
+ __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
1835
+ return trace(name, fn, {
1836
+ ...options2,
1837
+ [TraceAttributes.TABLE]: __privateGet$4(this, _table),
1838
+ [TraceAttributes.KIND]: "sdk-operation",
1839
+ [TraceAttributes.VERSION]: VERSION
1173
1840
  });
1174
- return initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), response);
1175
- } catch (e) {
1176
- if (isObject(e) && e.status === 404) {
1177
- return null;
1841
+ });
1842
+ }
1843
+ async create(a, b, c) {
1844
+ return __privateGet$4(this, _trace).call(this, "create", async () => {
1845
+ if (Array.isArray(a)) {
1846
+ if (a.length === 0)
1847
+ return [];
1848
+ const columns = isStringArray(b) ? b : void 0;
1849
+ return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
1178
1850
  }
1179
- throw e;
1180
- }
1851
+ if (isString(a) && isObject(b)) {
1852
+ if (a === "")
1853
+ throw new Error("The id can't be empty");
1854
+ const columns = isStringArray(c) ? c : void 0;
1855
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns);
1856
+ }
1857
+ if (isObject(a) && isString(a.id)) {
1858
+ if (a.id === "")
1859
+ throw new Error("The id can't be empty");
1860
+ const columns = isStringArray(b) ? b : void 0;
1861
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1862
+ }
1863
+ if (isObject(a)) {
1864
+ const columns = isStringArray(b) ? b : void 0;
1865
+ return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
1866
+ }
1867
+ throw new Error("Invalid arguments for create method");
1868
+ });
1181
1869
  }
1182
- async update(a, b) {
1183
- if (Array.isArray(a)) {
1184
- if (a.length > 100) {
1185
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1870
+ async read(a, b) {
1871
+ return __privateGet$4(this, _trace).call(this, "read", async () => {
1872
+ const columns = isStringArray(b) ? b : ["*"];
1873
+ if (Array.isArray(a)) {
1874
+ if (a.length === 0)
1875
+ return [];
1876
+ const ids = a.map((item) => extractId(item));
1877
+ const finalObjects = await this.getAll({ filter: { id: { $any: compact(ids) } }, columns });
1878
+ const dictionary = finalObjects.reduce((acc, object) => {
1879
+ acc[object.id] = object;
1880
+ return acc;
1881
+ }, {});
1882
+ return ids.map((id2) => dictionary[id2 ?? ""] ?? null);
1186
1883
  }
1187
- return Promise.all(a.map((object) => this.update(object)));
1188
- }
1189
- if (isString(a) && isObject(b)) {
1190
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1191
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1192
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1193
- return record;
1194
- }
1195
- if (isObject(a) && isString(a.id)) {
1196
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1197
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1198
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1199
- return record;
1200
- }
1201
- throw new Error("Invalid arguments for update method");
1884
+ const id = extractId(a);
1885
+ if (id) {
1886
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1887
+ try {
1888
+ const response = await getRecord({
1889
+ pathParams: {
1890
+ workspace: "{workspaceId}",
1891
+ dbBranchName: "{dbBranch}",
1892
+ tableName: __privateGet$4(this, _table),
1893
+ recordId: id
1894
+ },
1895
+ queryParams: { columns },
1896
+ ...fetchProps
1897
+ });
1898
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1899
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
1900
+ } catch (e) {
1901
+ if (isObject(e) && e.status === 404) {
1902
+ return null;
1903
+ }
1904
+ throw e;
1905
+ }
1906
+ }
1907
+ return null;
1908
+ });
1202
1909
  }
1203
- async createOrUpdate(a, b) {
1204
- if (Array.isArray(a)) {
1205
- if (a.length > 100) {
1206
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1910
+ async readOrThrow(a, b) {
1911
+ return __privateGet$4(this, _trace).call(this, "readOrThrow", async () => {
1912
+ const result = await this.read(a, b);
1913
+ if (Array.isArray(result)) {
1914
+ const missingIds = compact(
1915
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
1916
+ );
1917
+ if (missingIds.length > 0) {
1918
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
1919
+ }
1920
+ return result;
1207
1921
  }
1208
- return Promise.all(a.map((object) => this.createOrUpdate(object)));
1209
- }
1210
- if (isString(a) && isObject(b)) {
1211
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1212
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1213
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1214
- return record;
1215
- }
1216
- if (isObject(a) && isString(a.id)) {
1217
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1218
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1219
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1220
- return record;
1221
- }
1222
- throw new Error("Invalid arguments for createOrUpdate method");
1922
+ if (result === null) {
1923
+ const id = extractId(a) ?? "unknown";
1924
+ throw new Error(`Record with id ${id} not found`);
1925
+ }
1926
+ return result;
1927
+ });
1223
1928
  }
1224
- async delete(a) {
1225
- if (Array.isArray(a)) {
1226
- if (a.length > 100) {
1227
- console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1929
+ async update(a, b, c) {
1930
+ return __privateGet$4(this, _trace).call(this, "update", async () => {
1931
+ if (Array.isArray(a)) {
1932
+ if (a.length === 0)
1933
+ return [];
1934
+ if (a.length > 100) {
1935
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1936
+ }
1937
+ const columns = isStringArray(b) ? b : ["*"];
1938
+ return Promise.all(a.map((object) => this.update(object, columns)));
1228
1939
  }
1229
- await Promise.all(a.map((id) => this.delete(id)));
1230
- return;
1231
- }
1232
- if (isString(a)) {
1233
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1234
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1235
- return;
1236
- }
1237
- if (isObject(a) && isString(a.id)) {
1238
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1239
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1240
- return;
1241
- }
1242
- throw new Error("Invalid arguments for delete method");
1940
+ if (isString(a) && isObject(b)) {
1941
+ const columns = isStringArray(c) ? c : void 0;
1942
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns);
1943
+ }
1944
+ if (isObject(a) && isString(a.id)) {
1945
+ const columns = isStringArray(b) ? b : void 0;
1946
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1947
+ }
1948
+ throw new Error("Invalid arguments for update method");
1949
+ });
1950
+ }
1951
+ async updateOrThrow(a, b, c) {
1952
+ return __privateGet$4(this, _trace).call(this, "updateOrThrow", async () => {
1953
+ const result = await this.update(a, b, c);
1954
+ if (Array.isArray(result)) {
1955
+ const missingIds = compact(
1956
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
1957
+ );
1958
+ if (missingIds.length > 0) {
1959
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
1960
+ }
1961
+ return result;
1962
+ }
1963
+ if (result === null) {
1964
+ const id = extractId(a) ?? "unknown";
1965
+ throw new Error(`Record with id ${id} not found`);
1966
+ }
1967
+ return result;
1968
+ });
1969
+ }
1970
+ async createOrUpdate(a, b, c) {
1971
+ return __privateGet$4(this, _trace).call(this, "createOrUpdate", async () => {
1972
+ if (Array.isArray(a)) {
1973
+ if (a.length === 0)
1974
+ return [];
1975
+ if (a.length > 100) {
1976
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1977
+ }
1978
+ const columns = isStringArray(b) ? b : ["*"];
1979
+ return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
1980
+ }
1981
+ if (isString(a) && isObject(b)) {
1982
+ const columns = isStringArray(c) ? c : void 0;
1983
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns);
1984
+ }
1985
+ if (isObject(a) && isString(a.id)) {
1986
+ const columns = isStringArray(c) ? c : void 0;
1987
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1988
+ }
1989
+ throw new Error("Invalid arguments for createOrUpdate method");
1990
+ });
1991
+ }
1992
+ async delete(a, b) {
1993
+ return __privateGet$4(this, _trace).call(this, "delete", async () => {
1994
+ if (Array.isArray(a)) {
1995
+ if (a.length === 0)
1996
+ return [];
1997
+ if (a.length > 100) {
1998
+ console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1999
+ }
2000
+ return Promise.all(a.map((id) => this.delete(id, b)));
2001
+ }
2002
+ if (isString(a)) {
2003
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
2004
+ }
2005
+ if (isObject(a) && isString(a.id)) {
2006
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id, b);
2007
+ }
2008
+ throw new Error("Invalid arguments for delete method");
2009
+ });
2010
+ }
2011
+ async deleteOrThrow(a, b) {
2012
+ return __privateGet$4(this, _trace).call(this, "deleteOrThrow", async () => {
2013
+ const result = await this.delete(a, b);
2014
+ if (Array.isArray(result)) {
2015
+ const missingIds = compact(
2016
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
2017
+ );
2018
+ if (missingIds.length > 0) {
2019
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
2020
+ }
2021
+ return result;
2022
+ } else if (result === null) {
2023
+ const id = extractId(a) ?? "unknown";
2024
+ throw new Error(`Record with id ${id} not found`);
2025
+ }
2026
+ return result;
2027
+ });
1243
2028
  }
1244
2029
  async search(query, options = {}) {
1245
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1246
- const { records } = await searchBranch({
1247
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1248
- body: { tables: [__privateGet$3(this, _table)], query, fuzziness: options.fuzziness },
1249
- ...fetchProps
2030
+ return __privateGet$4(this, _trace).call(this, "search", async () => {
2031
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2032
+ const { records } = await searchTable({
2033
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
2034
+ body: {
2035
+ query,
2036
+ fuzziness: options.fuzziness,
2037
+ prefix: options.prefix,
2038
+ highlight: options.highlight,
2039
+ filter: options.filter,
2040
+ boosters: options.boosters
2041
+ },
2042
+ ...fetchProps
2043
+ });
2044
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2045
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
2046
+ });
2047
+ }
2048
+ async aggregate(aggs, filter) {
2049
+ return __privateGet$4(this, _trace).call(this, "aggregate", async () => {
2050
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2051
+ const result = await aggregateTable({
2052
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
2053
+ body: { aggs, filter },
2054
+ ...fetchProps
2055
+ });
2056
+ return result;
1250
2057
  });
1251
- return records.map((item) => initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), item));
1252
2058
  }
1253
2059
  async query(query) {
1254
- const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1255
- if (cacheQuery)
1256
- return new Page(query, cacheQuery.meta, cacheQuery.records);
1257
- const data = query.getQueryOptions();
1258
- const body = {
1259
- filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1260
- sort: data.sort ? buildSortFilter(data.sort) : void 0,
1261
- page: data.page,
1262
- columns: data.columns
1263
- };
1264
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1265
- const { meta, records: objects } = await queryTable({
1266
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table) },
1267
- body,
1268
- ...fetchProps
2060
+ return __privateGet$4(this, _trace).call(this, "query", async () => {
2061
+ const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
2062
+ if (cacheQuery)
2063
+ return new Page(query, cacheQuery.meta, cacheQuery.records);
2064
+ const data = query.getQueryOptions();
2065
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2066
+ const { meta, records: objects } = await queryTable({
2067
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
2068
+ body: {
2069
+ filter: cleanFilter(data.filter),
2070
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2071
+ page: data.pagination,
2072
+ columns: data.columns ?? ["*"]
2073
+ },
2074
+ ...fetchProps
2075
+ });
2076
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2077
+ const records = objects.map(
2078
+ (record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record, data.columns ?? ["*"])
2079
+ );
2080
+ await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
2081
+ return new Page(query, meta, records);
2082
+ });
2083
+ }
2084
+ async summarizeTable(query, summaries, summariesFilter) {
2085
+ return __privateGet$4(this, _trace).call(this, "summarize", async () => {
2086
+ const data = query.getQueryOptions();
2087
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2088
+ const result = await summarizeTable({
2089
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
2090
+ body: {
2091
+ filter: cleanFilter(data.filter),
2092
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2093
+ columns: data.columns,
2094
+ summaries,
2095
+ summariesFilter
2096
+ },
2097
+ ...fetchProps
2098
+ });
2099
+ return result;
1269
2100
  });
1270
- const records = objects.map((record) => initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), record));
1271
- await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1272
- return new Page(query, meta, records);
1273
2101
  }
1274
2102
  }
1275
2103
  _table = new WeakMap();
1276
- _links = new WeakMap();
1277
2104
  _getFetchProps = new WeakMap();
2105
+ _db = new WeakMap();
1278
2106
  _cache = new WeakMap();
2107
+ _schemaTables$2 = new WeakMap();
2108
+ _trace = new WeakMap();
1279
2109
  _insertRecordWithoutId = new WeakSet();
1280
- insertRecordWithoutId_fn = async function(object) {
1281
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
2110
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
2111
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1282
2112
  const record = transformObjectLinks(object);
1283
2113
  const response = await insertRecord({
1284
2114
  pathParams: {
1285
2115
  workspace: "{workspaceId}",
1286
2116
  dbBranchName: "{dbBranch}",
1287
- tableName: __privateGet$3(this, _table)
2117
+ tableName: __privateGet$4(this, _table)
1288
2118
  },
2119
+ queryParams: { columns },
1289
2120
  body: record,
1290
2121
  ...fetchProps
1291
2122
  });
1292
- const finalObject = await this.read(response.id);
1293
- if (!finalObject) {
1294
- throw new Error("The server failed to save the record");
1295
- }
1296
- return finalObject;
2123
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2124
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
1297
2125
  };
1298
2126
  _insertRecordWithId = new WeakSet();
1299
- insertRecordWithId_fn = async function(recordId, object) {
1300
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
2127
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
2128
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1301
2129
  const record = transformObjectLinks(object);
1302
2130
  const response = await insertRecordWithID({
1303
2131
  pathParams: {
1304
2132
  workspace: "{workspaceId}",
1305
2133
  dbBranchName: "{dbBranch}",
1306
- tableName: __privateGet$3(this, _table),
2134
+ tableName: __privateGet$4(this, _table),
1307
2135
  recordId
1308
2136
  },
1309
2137
  body: record,
1310
- queryParams: { createOnly: true },
2138
+ queryParams: { createOnly: true, columns },
1311
2139
  ...fetchProps
1312
2140
  });
1313
- const finalObject = await this.read(response.id);
1314
- if (!finalObject) {
1315
- throw new Error("The server failed to save the record");
1316
- }
1317
- return finalObject;
2141
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2142
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
1318
2143
  };
1319
2144
  _bulkInsertTableRecords = new WeakSet();
1320
- bulkInsertTableRecords_fn = async function(objects) {
1321
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
2145
+ bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
2146
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1322
2147
  const records = objects.map((object) => transformObjectLinks(object));
1323
2148
  const response = await bulkInsertTableRecords({
1324
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table) },
2149
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
2150
+ queryParams: { columns },
1325
2151
  body: { records },
1326
2152
  ...fetchProps
1327
2153
  });
1328
- const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1329
- if (finalObjects.length !== objects.length) {
1330
- throw new Error("The server failed to save some records");
2154
+ if (!isResponseWithRecords(response)) {
2155
+ throw new Error("Request included columns but server didn't include them");
1331
2156
  }
1332
- return finalObjects;
2157
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2158
+ return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, columns));
1333
2159
  };
1334
2160
  _updateRecordWithID = new WeakSet();
1335
- updateRecordWithID_fn = async function(recordId, object) {
1336
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
2161
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
2162
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1337
2163
  const record = transformObjectLinks(object);
1338
- const response = await updateRecordWithID({
1339
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1340
- body: record,
1341
- ...fetchProps
1342
- });
1343
- const item = await this.read(response.id);
1344
- if (!item)
1345
- throw new Error("The server failed to save the record");
1346
- return item;
2164
+ try {
2165
+ const response = await updateRecordWithID({
2166
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
2167
+ queryParams: { columns },
2168
+ body: record,
2169
+ ...fetchProps
2170
+ });
2171
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2172
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2173
+ } catch (e) {
2174
+ if (isObject(e) && e.status === 404) {
2175
+ return null;
2176
+ }
2177
+ throw e;
2178
+ }
1347
2179
  };
1348
2180
  _upsertRecordWithID = new WeakSet();
1349
- upsertRecordWithID_fn = async function(recordId, object) {
1350
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
2181
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
2182
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1351
2183
  const response = await upsertRecordWithID({
1352
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
2184
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
2185
+ queryParams: { columns },
1353
2186
  body: object,
1354
2187
  ...fetchProps
1355
2188
  });
1356
- const item = await this.read(response.id);
1357
- if (!item)
1358
- throw new Error("The server failed to save the record");
1359
- return item;
2189
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2190
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
1360
2191
  };
1361
2192
  _deleteRecord = new WeakSet();
1362
- deleteRecord_fn = async function(recordId) {
1363
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1364
- await deleteRecord({
1365
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1366
- ...fetchProps
1367
- });
1368
- };
1369
- _invalidateCache = new WeakSet();
1370
- invalidateCache_fn = async function(recordId) {
1371
- await __privateGet$3(this, _cache).delete(`rec_${__privateGet$3(this, _table)}:${recordId}`);
1372
- const cacheItems = await __privateGet$3(this, _cache).getAll();
1373
- const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1374
- for (const [key, value] of queries) {
1375
- const ids = getIds(value);
1376
- if (ids.includes(recordId))
1377
- await __privateGet$3(this, _cache).delete(key);
2193
+ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2194
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2195
+ try {
2196
+ const response = await deleteRecord({
2197
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
2198
+ queryParams: { columns },
2199
+ ...fetchProps
2200
+ });
2201
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2202
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2203
+ } catch (e) {
2204
+ if (isObject(e) && e.status === 404) {
2205
+ return null;
2206
+ }
2207
+ throw e;
1378
2208
  }
1379
2209
  };
1380
- _setCacheRecord = new WeakSet();
1381
- setCacheRecord_fn = async function(record) {
1382
- if (!__privateGet$3(this, _cache).cacheRecords)
1383
- return;
1384
- await __privateGet$3(this, _cache).set(`rec_${__privateGet$3(this, _table)}:${record.id}`, record);
1385
- };
1386
- _getCacheRecord = new WeakSet();
1387
- getCacheRecord_fn = async function(recordId) {
1388
- if (!__privateGet$3(this, _cache).cacheRecords)
1389
- return null;
1390
- return __privateGet$3(this, _cache).get(`rec_${__privateGet$3(this, _table)}:${recordId}`);
1391
- };
1392
2210
  _setCacheQuery = new WeakSet();
1393
2211
  setCacheQuery_fn = async function(query, meta, records) {
1394
- await __privateGet$3(this, _cache).set(`query_${__privateGet$3(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
2212
+ await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1395
2213
  };
1396
2214
  _getCacheQuery = new WeakSet();
1397
2215
  getCacheQuery_fn = async function(query) {
1398
- const key = `query_${__privateGet$3(this, _table)}:${query.key()}`;
1399
- const result = await __privateGet$3(this, _cache).get(key);
2216
+ const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
2217
+ const result = await __privateGet$4(this, _cache).get(key);
1400
2218
  if (!result)
1401
2219
  return null;
1402
- const { cache: ttl = __privateGet$3(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1403
- if (!ttl || ttl < 0)
1404
- return result;
2220
+ const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
2221
+ if (ttl < 0)
2222
+ return null;
1405
2223
  const hasExpired = result.date.getTime() + ttl < Date.now();
1406
2224
  return hasExpired ? null : result;
1407
2225
  };
2226
+ _getSchemaTables$1 = new WeakSet();
2227
+ getSchemaTables_fn$1 = async function() {
2228
+ if (__privateGet$4(this, _schemaTables$2))
2229
+ return __privateGet$4(this, _schemaTables$2);
2230
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2231
+ const { schema } = await getBranchDetails({
2232
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
2233
+ ...fetchProps
2234
+ });
2235
+ __privateSet$4(this, _schemaTables$2, schema.tables);
2236
+ return schema.tables;
2237
+ };
1408
2238
  const transformObjectLinks = (object) => {
1409
2239
  return Object.entries(object).reduce((acc, [key, value]) => {
1410
2240
  if (key === "xata")
@@ -1412,47 +2242,99 @@ const transformObjectLinks = (object) => {
1412
2242
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1413
2243
  }, {});
1414
2244
  };
1415
- const initObject = (db, links, table, object) => {
2245
+ const initObject = (db, schemaTables, table, object, selectedColumns) => {
1416
2246
  const result = {};
1417
- Object.assign(result, object);
1418
- const tableLinks = links[table] || [];
1419
- for (const link of tableLinks) {
1420
- const [field, linkTable] = link;
1421
- const value = result[field];
1422
- if (value && isObject(value)) {
1423
- result[field] = initObject(db, links, linkTable, value);
2247
+ const { xata, ...rest } = object ?? {};
2248
+ Object.assign(result, rest);
2249
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
2250
+ if (!columns)
2251
+ console.error(`Table ${table} not found in schema`);
2252
+ for (const column of columns ?? []) {
2253
+ if (!isValidColumn(selectedColumns, column))
2254
+ continue;
2255
+ const value = result[column.name];
2256
+ switch (column.type) {
2257
+ case "datetime": {
2258
+ const date = value !== void 0 ? new Date(value) : void 0;
2259
+ if (date && isNaN(date.getTime())) {
2260
+ console.error(`Failed to parse date ${value} for field ${column.name}`);
2261
+ } else if (date) {
2262
+ result[column.name] = date;
2263
+ }
2264
+ break;
2265
+ }
2266
+ case "link": {
2267
+ const linkTable = column.link?.table;
2268
+ if (!linkTable) {
2269
+ console.error(`Failed to parse link for field ${column.name}`);
2270
+ } else if (isObject(value)) {
2271
+ const selectedLinkColumns = selectedColumns.reduce((acc, item) => {
2272
+ if (item === column.name) {
2273
+ return [...acc, "*"];
2274
+ }
2275
+ if (item.startsWith(`${column.name}.`)) {
2276
+ const [, ...path] = item.split(".");
2277
+ return [...acc, path.join(".")];
2278
+ }
2279
+ return acc;
2280
+ }, []);
2281
+ result[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
2282
+ } else {
2283
+ result[column.name] = null;
2284
+ }
2285
+ break;
2286
+ }
2287
+ default:
2288
+ result[column.name] = value ?? null;
2289
+ if (column.notNull === true && value === null) {
2290
+ console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
2291
+ }
2292
+ break;
1424
2293
  }
1425
2294
  }
1426
- result.read = function() {
1427
- return db[table].read(result["id"]);
2295
+ result.read = function(columns2) {
2296
+ return db[table].read(result["id"], columns2);
1428
2297
  };
1429
- result.update = function(data) {
1430
- return db[table].update(result["id"], data);
2298
+ result.update = function(data, columns2) {
2299
+ return db[table].update(result["id"], data, columns2);
1431
2300
  };
1432
2301
  result.delete = function() {
1433
2302
  return db[table].delete(result["id"]);
1434
2303
  };
1435
- for (const prop of ["read", "update", "delete"]) {
2304
+ result.getMetadata = function() {
2305
+ return xata;
2306
+ };
2307
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1436
2308
  Object.defineProperty(result, prop, { enumerable: false });
1437
2309
  }
1438
2310
  Object.freeze(result);
1439
2311
  return result;
1440
2312
  };
1441
- function getIds(value) {
1442
- if (Array.isArray(value)) {
1443
- return value.map((item) => getIds(item)).flat();
1444
- }
1445
- if (!isObject(value))
1446
- return [];
1447
- const nestedIds = Object.values(value).map((item) => getIds(item)).flat();
1448
- return isString(value.id) ? [value.id, ...nestedIds] : nestedIds;
2313
+ function isResponseWithRecords(value) {
2314
+ return isObject(value) && Array.isArray(value.records);
2315
+ }
2316
+ function extractId(value) {
2317
+ if (isString(value))
2318
+ return value;
2319
+ if (isObject(value) && isString(value.id))
2320
+ return value.id;
2321
+ return void 0;
2322
+ }
2323
+ function isValidColumn(columns, column) {
2324
+ if (columns.includes("*"))
2325
+ return true;
2326
+ if (column.type === "link") {
2327
+ const linkColumns = columns.filter((item) => item.startsWith(column.name));
2328
+ return linkColumns.length > 0;
2329
+ }
2330
+ return columns.includes(column.name);
1449
2331
  }
1450
2332
 
1451
2333
  var __accessCheck$3 = (obj, member, msg) => {
1452
2334
  if (!member.has(obj))
1453
2335
  throw TypeError("Cannot " + msg);
1454
2336
  };
1455
- var __privateGet$2 = (obj, member, getter) => {
2337
+ var __privateGet$3 = (obj, member, getter) => {
1456
2338
  __accessCheck$3(obj, member, "read from private field");
1457
2339
  return getter ? getter.call(obj) : member.get(obj);
1458
2340
  };
@@ -1461,7 +2343,7 @@ var __privateAdd$3 = (obj, member, value) => {
1461
2343
  throw TypeError("Cannot add the same private member more than once");
1462
2344
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1463
2345
  };
1464
- var __privateSet$1 = (obj, member, value, setter) => {
2346
+ var __privateSet$3 = (obj, member, value, setter) => {
1465
2347
  __accessCheck$3(obj, member, "write to private field");
1466
2348
  setter ? setter.call(obj, value) : member.set(obj, value);
1467
2349
  return value;
@@ -1470,46 +2352,52 @@ var _map;
1470
2352
  class SimpleCache {
1471
2353
  constructor(options = {}) {
1472
2354
  __privateAdd$3(this, _map, void 0);
1473
- __privateSet$1(this, _map, /* @__PURE__ */ new Map());
2355
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1474
2356
  this.capacity = options.max ?? 500;
1475
- this.cacheRecords = options.cacheRecords ?? true;
1476
2357
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1477
2358
  }
1478
2359
  async getAll() {
1479
- return Object.fromEntries(__privateGet$2(this, _map));
2360
+ return Object.fromEntries(__privateGet$3(this, _map));
1480
2361
  }
1481
2362
  async get(key) {
1482
- return __privateGet$2(this, _map).get(key) ?? null;
2363
+ return __privateGet$3(this, _map).get(key) ?? null;
1483
2364
  }
1484
2365
  async set(key, value) {
1485
2366
  await this.delete(key);
1486
- __privateGet$2(this, _map).set(key, value);
1487
- if (__privateGet$2(this, _map).size > this.capacity) {
1488
- const leastRecentlyUsed = __privateGet$2(this, _map).keys().next().value;
2367
+ __privateGet$3(this, _map).set(key, value);
2368
+ if (__privateGet$3(this, _map).size > this.capacity) {
2369
+ const leastRecentlyUsed = __privateGet$3(this, _map).keys().next().value;
1489
2370
  await this.delete(leastRecentlyUsed);
1490
2371
  }
1491
2372
  }
1492
2373
  async delete(key) {
1493
- __privateGet$2(this, _map).delete(key);
2374
+ __privateGet$3(this, _map).delete(key);
1494
2375
  }
1495
2376
  async clear() {
1496
- return __privateGet$2(this, _map).clear();
2377
+ return __privateGet$3(this, _map).clear();
1497
2378
  }
1498
2379
  }
1499
2380
  _map = new WeakMap();
1500
2381
 
1501
- const gt = (value) => ({ $gt: value });
1502
- const ge = (value) => ({ $ge: value });
1503
- const gte = (value) => ({ $ge: value });
1504
- const lt = (value) => ({ $lt: value });
1505
- const lte = (value) => ({ $le: value });
1506
- const le = (value) => ({ $le: value });
2382
+ const greaterThan = (value) => ({ $gt: value });
2383
+ const gt = greaterThan;
2384
+ const greaterThanEquals = (value) => ({ $ge: value });
2385
+ const greaterEquals = greaterThanEquals;
2386
+ const gte = greaterThanEquals;
2387
+ const ge = greaterThanEquals;
2388
+ const lessThan = (value) => ({ $lt: value });
2389
+ const lt = lessThan;
2390
+ const lessThanEquals = (value) => ({ $le: value });
2391
+ const lessEquals = lessThanEquals;
2392
+ const lte = lessThanEquals;
2393
+ const le = lessThanEquals;
1507
2394
  const exists = (column) => ({ $exists: column });
1508
2395
  const notExists = (column) => ({ $notExists: column });
1509
2396
  const startsWith = (value) => ({ $startsWith: value });
1510
2397
  const endsWith = (value) => ({ $endsWith: value });
1511
2398
  const pattern = (value) => ({ $pattern: value });
1512
2399
  const is = (value) => ({ $is: value });
2400
+ const equals = is;
1513
2401
  const isNot = (value) => ({ $isNot: value });
1514
2402
  const contains = (value) => ({ $contains: value });
1515
2403
  const includes = (value) => ({ $includes: value });
@@ -1521,7 +2409,7 @@ var __accessCheck$2 = (obj, member, msg) => {
1521
2409
  if (!member.has(obj))
1522
2410
  throw TypeError("Cannot " + msg);
1523
2411
  };
1524
- var __privateGet$1 = (obj, member, getter) => {
2412
+ var __privateGet$2 = (obj, member, getter) => {
1525
2413
  __accessCheck$2(obj, member, "read from private field");
1526
2414
  return getter ? getter.call(obj) : member.get(obj);
1527
2415
  };
@@ -1530,130 +2418,178 @@ var __privateAdd$2 = (obj, member, value) => {
1530
2418
  throw TypeError("Cannot add the same private member more than once");
1531
2419
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1532
2420
  };
1533
- var _tables;
2421
+ var __privateSet$2 = (obj, member, value, setter) => {
2422
+ __accessCheck$2(obj, member, "write to private field");
2423
+ setter ? setter.call(obj, value) : member.set(obj, value);
2424
+ return value;
2425
+ };
2426
+ var _tables, _schemaTables$1;
1534
2427
  class SchemaPlugin extends XataPlugin {
1535
- constructor(links, tableNames) {
2428
+ constructor(schemaTables) {
1536
2429
  super();
1537
- this.links = links;
1538
- this.tableNames = tableNames;
1539
2430
  __privateAdd$2(this, _tables, {});
2431
+ __privateAdd$2(this, _schemaTables$1, void 0);
2432
+ __privateSet$2(this, _schemaTables$1, schemaTables);
1540
2433
  }
1541
2434
  build(pluginOptions) {
1542
- const links = this.links;
1543
- const db = new Proxy({}, {
1544
- get: (_target, table) => {
1545
- if (!isString(table))
1546
- throw new Error("Invalid table name");
1547
- if (!__privateGet$1(this, _tables)[table]) {
1548
- __privateGet$1(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, links });
2435
+ const db = new Proxy(
2436
+ {},
2437
+ {
2438
+ get: (_target, table) => {
2439
+ if (!isString(table))
2440
+ throw new Error("Invalid table name");
2441
+ if (__privateGet$2(this, _tables)[table] === void 0) {
2442
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
2443
+ }
2444
+ return __privateGet$2(this, _tables)[table];
1549
2445
  }
1550
- return __privateGet$1(this, _tables)[table];
1551
2446
  }
1552
- });
1553
- for (const table of this.tableNames ?? []) {
1554
- db[table] = new RestRepository({ db, pluginOptions, table, links });
2447
+ );
2448
+ const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
2449
+ for (const table of tableNames) {
2450
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1555
2451
  }
1556
2452
  return db;
1557
2453
  }
1558
2454
  }
1559
2455
  _tables = new WeakMap();
2456
+ _schemaTables$1 = new WeakMap();
1560
2457
 
1561
2458
  var __accessCheck$1 = (obj, member, msg) => {
1562
2459
  if (!member.has(obj))
1563
2460
  throw TypeError("Cannot " + msg);
1564
2461
  };
2462
+ var __privateGet$1 = (obj, member, getter) => {
2463
+ __accessCheck$1(obj, member, "read from private field");
2464
+ return getter ? getter.call(obj) : member.get(obj);
2465
+ };
1565
2466
  var __privateAdd$1 = (obj, member, value) => {
1566
2467
  if (member.has(obj))
1567
2468
  throw TypeError("Cannot add the same private member more than once");
1568
2469
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1569
2470
  };
2471
+ var __privateSet$1 = (obj, member, value, setter) => {
2472
+ __accessCheck$1(obj, member, "write to private field");
2473
+ setter ? setter.call(obj, value) : member.set(obj, value);
2474
+ return value;
2475
+ };
1570
2476
  var __privateMethod$1 = (obj, member, method) => {
1571
2477
  __accessCheck$1(obj, member, "access private method");
1572
2478
  return method;
1573
2479
  };
1574
- var _search, search_fn;
2480
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1575
2481
  class SearchPlugin extends XataPlugin {
1576
- constructor(db, links) {
2482
+ constructor(db, schemaTables) {
1577
2483
  super();
1578
2484
  this.db = db;
1579
- this.links = links;
1580
2485
  __privateAdd$1(this, _search);
2486
+ __privateAdd$1(this, _getSchemaTables);
2487
+ __privateAdd$1(this, _schemaTables, void 0);
2488
+ __privateSet$1(this, _schemaTables, schemaTables);
1581
2489
  }
1582
2490
  build({ getFetchProps }) {
1583
2491
  return {
1584
2492
  all: async (query, options = {}) => {
1585
2493
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
2494
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1586
2495
  return records.map((record) => {
1587
2496
  const { table = "orphan" } = record.xata;
1588
- return { table, record: initObject(this.db, this.links, table, record) };
2497
+ return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
1589
2498
  });
1590
2499
  },
1591
2500
  byTable: async (query, options = {}) => {
1592
2501
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
2502
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1593
2503
  return records.reduce((acc, record) => {
1594
2504
  const { table = "orphan" } = record.xata;
1595
2505
  const items = acc[table] ?? [];
1596
- const item = initObject(this.db, this.links, table, record);
2506
+ const item = initObject(this.db, schemaTables, table, record, ["*"]);
1597
2507
  return { ...acc, [table]: [...items, item] };
1598
2508
  }, {});
1599
2509
  }
1600
2510
  };
1601
2511
  }
1602
2512
  }
2513
+ _schemaTables = new WeakMap();
1603
2514
  _search = new WeakSet();
1604
2515
  search_fn = async function(query, options, getFetchProps) {
1605
2516
  const fetchProps = await getFetchProps();
1606
- const { tables, fuzziness } = options ?? {};
2517
+ const { tables, fuzziness, highlight, prefix } = options ?? {};
1607
2518
  const { records } = await searchBranch({
1608
2519
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1609
- body: { tables, query, fuzziness },
2520
+ body: { tables, query, fuzziness, prefix, highlight },
1610
2521
  ...fetchProps
1611
2522
  });
1612
2523
  return records;
1613
2524
  };
2525
+ _getSchemaTables = new WeakSet();
2526
+ getSchemaTables_fn = async function(getFetchProps) {
2527
+ if (__privateGet$1(this, _schemaTables))
2528
+ return __privateGet$1(this, _schemaTables);
2529
+ const fetchProps = await getFetchProps();
2530
+ const { schema } = await getBranchDetails({
2531
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
2532
+ ...fetchProps
2533
+ });
2534
+ __privateSet$1(this, _schemaTables, schema.tables);
2535
+ return schema.tables;
2536
+ };
1614
2537
 
1615
2538
  const isBranchStrategyBuilder = (strategy) => {
1616
2539
  return typeof strategy === "function";
1617
2540
  };
1618
2541
 
1619
- const envBranchNames = [
1620
- "XATA_BRANCH",
1621
- "VERCEL_GIT_COMMIT_REF",
1622
- "CF_PAGES_BRANCH",
1623
- "BRANCH"
1624
- ];
1625
- const defaultBranch = "main";
1626
2542
  async function getCurrentBranchName(options) {
1627
- const env = await getBranchByEnvVariable();
1628
- if (env)
1629
- return env;
1630
- const branch = await getGitBranch();
1631
- if (!branch)
1632
- return defaultBranch;
1633
- const details = await getDatabaseBranch(branch, options);
1634
- if (details)
1635
- return branch;
1636
- return defaultBranch;
2543
+ const { branch, envBranch } = getEnvironment();
2544
+ if (branch) {
2545
+ const details = await getDatabaseBranch(branch, options);
2546
+ if (details)
2547
+ return branch;
2548
+ console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
2549
+ }
2550
+ const gitBranch = envBranch || await getGitBranch();
2551
+ return resolveXataBranch(gitBranch, options);
1637
2552
  }
1638
2553
  async function getCurrentBranchDetails(options) {
1639
- const env = await getBranchByEnvVariable();
1640
- if (env)
1641
- return getDatabaseBranch(env, options);
1642
- const branch = await getGitBranch();
1643
- if (!branch)
1644
- return getDatabaseBranch(defaultBranch, options);
1645
- const details = await getDatabaseBranch(branch, options);
1646
- if (details)
1647
- return details;
1648
- return getDatabaseBranch(defaultBranch, options);
2554
+ const branch = await getCurrentBranchName(options);
2555
+ return getDatabaseBranch(branch, options);
2556
+ }
2557
+ async function resolveXataBranch(gitBranch, options) {
2558
+ const databaseURL = options?.databaseURL || getDatabaseURL();
2559
+ const apiKey = options?.apiKey || getAPIKey();
2560
+ if (!databaseURL)
2561
+ throw new Error(
2562
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2563
+ );
2564
+ if (!apiKey)
2565
+ throw new Error(
2566
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2567
+ );
2568
+ const [protocol, , host, , dbName] = databaseURL.split("/");
2569
+ const [workspace] = host.split(".");
2570
+ const { fallbackBranch } = getEnvironment();
2571
+ const { branch } = await resolveBranch({
2572
+ apiKey,
2573
+ apiUrl: databaseURL,
2574
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
2575
+ workspacesApiUrl: `${protocol}//${host}`,
2576
+ pathParams: { dbName, workspace },
2577
+ queryParams: { gitBranch, fallbackBranch },
2578
+ trace: defaultTrace
2579
+ });
2580
+ return branch;
1649
2581
  }
1650
2582
  async function getDatabaseBranch(branch, options) {
1651
2583
  const databaseURL = options?.databaseURL || getDatabaseURL();
1652
2584
  const apiKey = options?.apiKey || getAPIKey();
1653
2585
  if (!databaseURL)
1654
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
2586
+ throw new Error(
2587
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2588
+ );
1655
2589
  if (!apiKey)
1656
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
2590
+ throw new Error(
2591
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2592
+ );
1657
2593
  const [protocol, , host, , database] = databaseURL.split("/");
1658
2594
  const [workspace] = host.split(".");
1659
2595
  const dbBranchName = `${database}:${branch}`;
@@ -1663,10 +2599,8 @@ async function getDatabaseBranch(branch, options) {
1663
2599
  apiUrl: databaseURL,
1664
2600
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1665
2601
  workspacesApiUrl: `${protocol}//${host}`,
1666
- pathParams: {
1667
- dbBranchName,
1668
- workspace
1669
- }
2602
+ pathParams: { dbBranchName, workspace },
2603
+ trace: defaultTrace
1670
2604
  });
1671
2605
  } catch (err) {
1672
2606
  if (isObject(err) && err.status === 404)
@@ -1674,21 +2608,10 @@ async function getDatabaseBranch(branch, options) {
1674
2608
  throw err;
1675
2609
  }
1676
2610
  }
1677
- function getBranchByEnvVariable() {
1678
- for (const name of envBranchNames) {
1679
- const value = getEnvVariable(name);
1680
- if (value) {
1681
- return value;
1682
- }
1683
- }
1684
- try {
1685
- return XATA_BRANCH;
1686
- } catch (err) {
1687
- }
1688
- }
1689
2611
  function getDatabaseURL() {
1690
2612
  try {
1691
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
2613
+ const { databaseURL } = getEnvironment();
2614
+ return databaseURL;
1692
2615
  } catch (err) {
1693
2616
  return void 0;
1694
2617
  }
@@ -1717,24 +2640,27 @@ var __privateMethod = (obj, member, method) => {
1717
2640
  return method;
1718
2641
  };
1719
2642
  const buildClient = (plugins) => {
1720
- var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
2643
+ var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1721
2644
  return _a = class {
1722
- constructor(options = {}, links, tables) {
2645
+ constructor(options = {}, schemaTables) {
1723
2646
  __privateAdd(this, _parseOptions);
1724
2647
  __privateAdd(this, _getFetchProps);
1725
2648
  __privateAdd(this, _evaluateBranch);
1726
2649
  __privateAdd(this, _branch, void 0);
2650
+ __privateAdd(this, _options, void 0);
1727
2651
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
2652
+ __privateSet(this, _options, safeOptions);
1728
2653
  const pluginOptions = {
1729
2654
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1730
- cache: safeOptions.cache
2655
+ cache: safeOptions.cache,
2656
+ trace: safeOptions.trace
1731
2657
  };
1732
- const db = new SchemaPlugin(links, tables).build(pluginOptions);
1733
- const search = new SearchPlugin(db, links ?? {}).build(pluginOptions);
2658
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2659
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1734
2660
  this.db = db;
1735
2661
  this.search = search;
1736
2662
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
1737
- if (!namespace)
2663
+ if (namespace === void 0)
1738
2664
  continue;
1739
2665
  const result = namespace.build(pluginOptions);
1740
2666
  if (result instanceof Promise) {
@@ -1746,21 +2672,32 @@ const buildClient = (plugins) => {
1746
2672
  }
1747
2673
  }
1748
2674
  }
1749
- }, _branch = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
2675
+ async getConfig() {
2676
+ const databaseURL = __privateGet(this, _options).databaseURL;
2677
+ const branch = await __privateGet(this, _options).branch();
2678
+ return { databaseURL, branch };
2679
+ }
2680
+ }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
1750
2681
  const fetch = getFetchImplementation(options?.fetch);
1751
2682
  const databaseURL = options?.databaseURL || getDatabaseURL();
1752
2683
  const apiKey = options?.apiKey || getAPIKey();
1753
- const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
1754
- const branch = async () => options?.branch ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1755
- if (!databaseURL || !apiKey) {
1756
- throw new Error("Options databaseURL and apiKey are required");
2684
+ const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
2685
+ const trace = options?.trace ?? defaultTrace;
2686
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
2687
+ if (!apiKey) {
2688
+ throw new Error("Option apiKey is required");
2689
+ }
2690
+ if (!databaseURL) {
2691
+ throw new Error("Option databaseURL is required");
1757
2692
  }
1758
- return { fetch, databaseURL, apiKey, branch, cache };
2693
+ return { fetch, databaseURL, apiKey, branch, cache, trace, clientID: generateUUID() };
1759
2694
  }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
1760
2695
  fetch,
1761
2696
  apiKey,
1762
2697
  databaseURL,
1763
- branch
2698
+ branch,
2699
+ trace,
2700
+ clientID
1764
2701
  }) {
1765
2702
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
1766
2703
  if (!branchValue)
@@ -1771,14 +2708,16 @@ const buildClient = (plugins) => {
1771
2708
  apiUrl: "",
1772
2709
  workspacesApiUrl: (path, params) => {
1773
2710
  const hasBranch = params.dbBranchName ?? params.branch;
1774
- const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branchValue}` : "");
2711
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branchValue}` : "");
1775
2712
  return databaseURL + newPath;
1776
- }
2713
+ },
2714
+ trace,
2715
+ clientID
1777
2716
  };
1778
2717
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1779
2718
  if (__privateGet(this, _branch))
1780
2719
  return __privateGet(this, _branch);
1781
- if (!param)
2720
+ if (param === void 0)
1782
2721
  return void 0;
1783
2722
  const strategies = Array.isArray(param) ? [...param] : [param];
1784
2723
  const evaluateBranch = async (strategy) => {
@@ -1796,6 +2735,88 @@ const buildClient = (plugins) => {
1796
2735
  class BaseClient extends buildClient() {
1797
2736
  }
1798
2737
 
2738
+ const META = "__";
2739
+ const VALUE = "___";
2740
+ class Serializer {
2741
+ constructor() {
2742
+ this.classes = {};
2743
+ }
2744
+ add(clazz) {
2745
+ this.classes[clazz.name] = clazz;
2746
+ }
2747
+ toJSON(data) {
2748
+ function visit(obj) {
2749
+ if (Array.isArray(obj))
2750
+ return obj.map(visit);
2751
+ const type = typeof obj;
2752
+ if (type === "undefined")
2753
+ return { [META]: "undefined" };
2754
+ if (type === "bigint")
2755
+ return { [META]: "bigint", [VALUE]: obj.toString() };
2756
+ if (obj === null || type !== "object")
2757
+ return obj;
2758
+ const constructor = obj.constructor;
2759
+ const o = { [META]: constructor.name };
2760
+ for (const [key, value] of Object.entries(obj)) {
2761
+ o[key] = visit(value);
2762
+ }
2763
+ if (constructor === Date)
2764
+ o[VALUE] = obj.toISOString();
2765
+ if (constructor === Map)
2766
+ o[VALUE] = Object.fromEntries(obj);
2767
+ if (constructor === Set)
2768
+ o[VALUE] = [...obj];
2769
+ return o;
2770
+ }
2771
+ return JSON.stringify(visit(data));
2772
+ }
2773
+ fromJSON(json) {
2774
+ return JSON.parse(json, (key, value) => {
2775
+ if (value && typeof value === "object" && !Array.isArray(value)) {
2776
+ const { [META]: clazz, [VALUE]: val, ...rest } = value;
2777
+ const constructor = this.classes[clazz];
2778
+ if (constructor) {
2779
+ return Object.assign(Object.create(constructor.prototype), rest);
2780
+ }
2781
+ if (clazz === "Date")
2782
+ return new Date(val);
2783
+ if (clazz === "Set")
2784
+ return new Set(val);
2785
+ if (clazz === "Map")
2786
+ return new Map(Object.entries(val));
2787
+ if (clazz === "bigint")
2788
+ return BigInt(val);
2789
+ if (clazz === "undefined")
2790
+ return void 0;
2791
+ return rest;
2792
+ }
2793
+ return value;
2794
+ });
2795
+ }
2796
+ }
2797
+ const defaultSerializer = new Serializer();
2798
+ const serialize = (data) => {
2799
+ return defaultSerializer.toJSON(data);
2800
+ };
2801
+ const deserialize = (json) => {
2802
+ return defaultSerializer.fromJSON(json);
2803
+ };
2804
+
2805
+ function buildWorkerRunner(config) {
2806
+ return function xataWorker(name, _worker) {
2807
+ return async (...args) => {
2808
+ const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
2809
+ const result = await fetch(url, {
2810
+ method: "POST",
2811
+ headers: { "Content-Type": "application/json" },
2812
+ body: serialize({ args })
2813
+ });
2814
+ const text = await result.text();
2815
+ return deserialize(text);
2816
+ };
2817
+ };
2818
+ }
2819
+
1799
2820
  class XataError extends Error {
1800
2821
  constructor(message, status) {
1801
2822
  super(message);
@@ -1803,5 +2824,5 @@ class XataError extends Error {
1803
2824
  }
1804
2825
  }
1805
2826
 
1806
- export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, Repository, RestRepository, SchemaPlugin, SearchPlugin, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addTableColumn, buildClient, bulkInsertTableRecords, cancelWorkspaceMemberInvite, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, endsWith, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseURL, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isIdentifiable, isNot, isXataRecord, le, lt, lte, notExists, operationsByTag, pattern, queryTable, removeWorkspaceMember, resendWorkspaceMemberInvite, searchBranch, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberRole, upsertRecordWithID };
2827
+ 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, aggregateTable, applyBranchSchemaEdit, buildClient, buildWorkerRunner, bulkInsertTableRecords, cPCreateDatabase, cPDeleteDatabase, cPGetCPDatabaseMetadata, cPGetDatabaseList, cPUpdateCPDatabaseMetadata, 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, getHostUrl, getMigrationRequest, getMigrationRequestIsMerged, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, greaterEquals, greaterThan, greaterThanEquals, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isHostProviderAlias, isHostProviderBuilder, isIdentifiable, isNot, isXataRecord, le, lessEquals, lessThan, lessThanEquals, listMigrationRequestsCommits, listRegions, lt, lte, mergeMigrationRequest, notExists, operationsByTag, parseProviderString, pattern, previewBranchSchemaEdit, queryMigrationRequests, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, serialize, setTableSchema, startsWith, summarizeTable, updateBranchMetadata, updateBranchSchema, updateColumn, updateDatabaseMetadata, updateMigrationRequest, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID };
1807
2828
  //# sourceMappingURL=index.mjs.map