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