@xata.io/client 0.0.0-alpha.vf9819fa → 0.0.0-alpha.vf9a4972

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