@xata.io/client 0.0.0-alpha.vebf0406 → 0.0.0-alpha.vec26c56

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