@xata.io/client 0.0.0-alpha.vf170c2c → 0.0.0-alpha.vf1f4abe

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