@xata.io/client 0.0.0-alpha.vf481c73 → 0.0.0-alpha.vf54f8ba

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -2,6 +2,46 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
+ function _interopNamespace(e) {
6
+ if (e && e.__esModule) return e;
7
+ var n = Object.create(null);
8
+ if (e) {
9
+ Object.keys(e).forEach(function (k) {
10
+ if (k !== 'default') {
11
+ var d = Object.getOwnPropertyDescriptor(e, k);
12
+ Object.defineProperty(n, k, d.get ? d : {
13
+ enumerable: true,
14
+ get: function () { return e[k]; }
15
+ });
16
+ }
17
+ });
18
+ }
19
+ n["default"] = e;
20
+ return Object.freeze(n);
21
+ }
22
+
23
+ const defaultTrace = async (_name, fn, _options) => {
24
+ return await fn({
25
+ setAttributes: () => {
26
+ return;
27
+ }
28
+ });
29
+ };
30
+ const TraceAttributes = {
31
+ KIND: "xata.trace.kind",
32
+ VERSION: "xata.sdk.version",
33
+ TABLE: "xata.table",
34
+ HTTP_REQUEST_ID: "http.request_id",
35
+ HTTP_STATUS_CODE: "http.status_code",
36
+ HTTP_HOST: "http.host",
37
+ HTTP_SCHEME: "http.scheme",
38
+ HTTP_USER_AGENT: "http.user_agent",
39
+ HTTP_METHOD: "http.method",
40
+ HTTP_URL: "http.url",
41
+ HTTP_ROUTE: "http.route",
42
+ HTTP_TARGET: "http.target"
43
+ };
44
+
5
45
  function notEmpty(value) {
6
46
  return value !== null && value !== void 0;
7
47
  }
@@ -17,6 +57,9 @@ function isDefined(value) {
17
57
  function isString(value) {
18
58
  return isDefined(value) && typeof value === "string";
19
59
  }
60
+ function isStringArray(value) {
61
+ return isDefined(value) && Array.isArray(value) && value.every(isString);
62
+ }
20
63
  function toBase64(value) {
21
64
  try {
22
65
  return btoa(value);
@@ -32,7 +75,7 @@ function getEnvironment() {
32
75
  return {
33
76
  apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
34
77
  databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
35
- branch: process.env.XATA_BRANCH,
78
+ branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
36
79
  envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
37
80
  fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
38
81
  };
@@ -44,7 +87,7 @@ function getEnvironment() {
44
87
  return {
45
88
  apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
46
89
  databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
47
- branch: Deno.env.get("XATA_BRANCH"),
90
+ branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
48
91
  envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
49
92
  fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
50
93
  };
@@ -88,20 +131,21 @@ function getGlobalFallbackBranch() {
88
131
  }
89
132
  }
90
133
  async function getGitBranch() {
134
+ const cmd = ["git", "branch", "--show-current"];
135
+ const fullCmd = cmd.join(" ");
136
+ const nodeModule = ["child", "process"].join("_");
137
+ const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
91
138
  try {
92
139
  if (typeof require === "function") {
93
- const req = require;
94
- return req("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
140
+ return require(nodeModule).execSync(fullCmd, execOptions).trim();
95
141
  }
142
+ const { execSync } = await (function (t) { return Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require(t)); }); })(nodeModule);
143
+ return execSync(fullCmd, execOptions).toString().trim();
96
144
  } catch (err) {
97
145
  }
98
146
  try {
99
147
  if (isObject(Deno)) {
100
- const process2 = Deno.run({
101
- cmd: ["git", "branch", "--show-current"],
102
- stdout: "piped",
103
- stderr: "piped"
104
- });
148
+ const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
105
149
  return new TextDecoder().decode(await process2.output()).trim();
106
150
  }
107
151
  } catch (err) {
@@ -121,12 +165,14 @@ function getFetchImplementation(userFetch) {
121
165
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
122
166
  const fetchImpl = userFetch ?? globalFetch;
123
167
  if (!fetchImpl) {
124
- throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
168
+ throw new Error(
169
+ `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
170
+ );
125
171
  }
126
172
  return fetchImpl;
127
173
  }
128
174
 
129
- const VERSION = "0.0.0-alpha.vf481c73";
175
+ const VERSION = "0.0.0-alpha.vf54f8ba";
130
176
 
131
177
  class ErrorWithCause extends Error {
132
178
  constructor(message, options) {
@@ -177,7 +223,10 @@ const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
177
223
  }, {});
178
224
  const query = new URLSearchParams(cleanQueryParams).toString();
179
225
  const queryString = query.length > 0 ? `?${query}` : "";
180
- return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
226
+ const cleanPathParams = Object.entries(pathParams).reduce((acc, [key, value]) => {
227
+ return { ...acc, [key]: encodeURIComponent(String(value ?? "")).replace("%3A", ":") };
228
+ }, {});
229
+ return url.replace(/\{\w*\}/g, (key) => cleanPathParams[key.slice(1, -1)]) + queryString;
181
230
  };
182
231
  function buildBaseUrl({
183
232
  path,
@@ -185,10 +234,10 @@ function buildBaseUrl({
185
234
  apiUrl,
186
235
  pathParams
187
236
  }) {
188
- if (!pathParams?.workspace)
237
+ if (pathParams?.workspace === void 0 || !path.startsWith("/db"))
189
238
  return `${apiUrl}${path}`;
190
239
  const url = typeof workspacesApiUrl === "string" ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
191
- return url.replace("{workspaceId}", pathParams.workspace);
240
+ return url.replace("{workspaceId}", String(pathParams.workspace));
192
241
  }
193
242
  function hostHeader(url) {
194
243
  const pattern = /.*:\/\/(?<host>[^/]+).*/;
@@ -205,252 +254,382 @@ async function fetch$1({
205
254
  fetchImpl,
206
255
  apiKey,
207
256
  apiUrl,
208
- workspacesApiUrl
257
+ workspacesApiUrl,
258
+ trace,
259
+ signal
209
260
  }) {
210
- const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
211
- const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
212
- const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
213
- const response = await fetchImpl(url, {
214
- method: method.toUpperCase(),
215
- body: body ? JSON.stringify(body) : void 0,
216
- headers: {
217
- "Content-Type": "application/json",
218
- "User-Agent": `Xata client-ts/${VERSION}`,
219
- ...headers,
220
- ...hostHeader(fullUrl),
221
- Authorization: `Bearer ${apiKey}`
222
- }
223
- });
224
- if (response.status === 204) {
225
- return {};
226
- }
227
- const requestId = response.headers?.get("x-request-id") ?? void 0;
261
+ return trace(
262
+ `${method.toUpperCase()} ${path}`,
263
+ async ({ setAttributes }) => {
264
+ const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
265
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
266
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
267
+ setAttributes({
268
+ [TraceAttributes.HTTP_URL]: url,
269
+ [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
270
+ });
271
+ const response = await fetchImpl(url, {
272
+ method: method.toUpperCase(),
273
+ body: body ? JSON.stringify(body) : void 0,
274
+ headers: {
275
+ "Content-Type": "application/json",
276
+ "User-Agent": `Xata client-ts/${VERSION}`,
277
+ ...headers,
278
+ ...hostHeader(fullUrl),
279
+ Authorization: `Bearer ${apiKey}`
280
+ },
281
+ signal
282
+ });
283
+ if (response.status === 204) {
284
+ return {};
285
+ }
286
+ const { host, protocol } = parseUrl(response.url);
287
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
288
+ setAttributes({
289
+ [TraceAttributes.KIND]: "http",
290
+ [TraceAttributes.HTTP_REQUEST_ID]: requestId,
291
+ [TraceAttributes.HTTP_STATUS_CODE]: response.status,
292
+ [TraceAttributes.HTTP_HOST]: host,
293
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
294
+ });
295
+ try {
296
+ const jsonResponse = await response.json();
297
+ if (response.ok) {
298
+ return jsonResponse;
299
+ }
300
+ throw new FetcherError(response.status, jsonResponse, requestId);
301
+ } catch (error) {
302
+ throw new FetcherError(response.status, error, requestId);
303
+ }
304
+ },
305
+ { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
306
+ );
307
+ }
308
+ function parseUrl(url) {
228
309
  try {
229
- const jsonResponse = await response.json();
230
- if (response.ok) {
231
- return jsonResponse;
232
- }
233
- throw new FetcherError(response.status, jsonResponse, requestId);
310
+ const { host, protocol } = new URL(url);
311
+ return { host, protocol };
234
312
  } catch (error) {
235
- throw new FetcherError(response.status, error, requestId);
313
+ return {};
236
314
  }
237
315
  }
238
316
 
239
- const getUser = (variables) => fetch$1({ url: "/user", method: "get", ...variables });
240
- const updateUser = (variables) => fetch$1({ url: "/user", method: "put", ...variables });
241
- const deleteUser = (variables) => fetch$1({ url: "/user", method: "delete", ...variables });
242
- const getUserAPIKeys = (variables) => fetch$1({
317
+ const getUser = (variables, signal) => fetch$1({ url: "/user", method: "get", ...variables, signal });
318
+ const updateUser = (variables, signal) => fetch$1({
319
+ url: "/user",
320
+ method: "put",
321
+ ...variables,
322
+ signal
323
+ });
324
+ const deleteUser = (variables, signal) => fetch$1({ url: "/user", method: "delete", ...variables, signal });
325
+ const getUserAPIKeys = (variables, signal) => fetch$1({
243
326
  url: "/user/keys",
244
327
  method: "get",
245
- ...variables
328
+ ...variables,
329
+ signal
246
330
  });
247
- const createUserAPIKey = (variables) => fetch$1({
331
+ const createUserAPIKey = (variables, signal) => fetch$1({
248
332
  url: "/user/keys/{keyName}",
249
333
  method: "post",
250
- ...variables
334
+ ...variables,
335
+ signal
251
336
  });
252
- const deleteUserAPIKey = (variables) => fetch$1({
337
+ const deleteUserAPIKey = (variables, signal) => fetch$1({
253
338
  url: "/user/keys/{keyName}",
254
339
  method: "delete",
255
- ...variables
340
+ ...variables,
341
+ signal
256
342
  });
257
- const createWorkspace = (variables) => fetch$1({
343
+ const createWorkspace = (variables, signal) => fetch$1({
258
344
  url: "/workspaces",
259
345
  method: "post",
260
- ...variables
346
+ ...variables,
347
+ signal
261
348
  });
262
- const getWorkspacesList = (variables) => fetch$1({
349
+ const getWorkspacesList = (variables, signal) => fetch$1({
263
350
  url: "/workspaces",
264
351
  method: "get",
265
- ...variables
352
+ ...variables,
353
+ signal
266
354
  });
267
- const getWorkspace = (variables) => fetch$1({
355
+ const getWorkspace = (variables, signal) => fetch$1({
268
356
  url: "/workspaces/{workspaceId}",
269
357
  method: "get",
270
- ...variables
358
+ ...variables,
359
+ signal
271
360
  });
272
- const updateWorkspace = (variables) => fetch$1({
361
+ const updateWorkspace = (variables, signal) => fetch$1({
273
362
  url: "/workspaces/{workspaceId}",
274
363
  method: "put",
275
- ...variables
364
+ ...variables,
365
+ signal
276
366
  });
277
- const deleteWorkspace = (variables) => fetch$1({
367
+ const deleteWorkspace = (variables, signal) => fetch$1({
278
368
  url: "/workspaces/{workspaceId}",
279
369
  method: "delete",
280
- ...variables
370
+ ...variables,
371
+ signal
281
372
  });
282
- const getWorkspaceMembersList = (variables) => fetch$1({
373
+ const getWorkspaceMembersList = (variables, signal) => fetch$1({
283
374
  url: "/workspaces/{workspaceId}/members",
284
375
  method: "get",
285
- ...variables
376
+ ...variables,
377
+ signal
286
378
  });
287
- const updateWorkspaceMemberRole = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/members/{userId}", method: "put", ...variables });
288
- const removeWorkspaceMember = (variables) => fetch$1({
379
+ const updateWorkspaceMemberRole = (variables, signal) => fetch$1({ url: "/workspaces/{workspaceId}/members/{userId}", method: "put", ...variables, signal });
380
+ const removeWorkspaceMember = (variables, signal) => fetch$1({
289
381
  url: "/workspaces/{workspaceId}/members/{userId}",
290
382
  method: "delete",
291
- ...variables
383
+ ...variables,
384
+ signal
292
385
  });
293
- const inviteWorkspaceMember = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables });
294
- const cancelWorkspaceMemberInvite = (variables) => fetch$1({
386
+ const inviteWorkspaceMember = (variables, signal) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables, signal });
387
+ const updateWorkspaceMemberInvite = (variables, signal) => fetch$1({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables, signal });
388
+ const cancelWorkspaceMemberInvite = (variables, signal) => fetch$1({
295
389
  url: "/workspaces/{workspaceId}/invites/{inviteId}",
296
390
  method: "delete",
297
- ...variables
391
+ ...variables,
392
+ signal
298
393
  });
299
- const resendWorkspaceMemberInvite = (variables) => fetch$1({
394
+ const resendWorkspaceMemberInvite = (variables, signal) => fetch$1({
300
395
  url: "/workspaces/{workspaceId}/invites/{inviteId}/resend",
301
396
  method: "post",
302
- ...variables
397
+ ...variables,
398
+ signal
303
399
  });
304
- const acceptWorkspaceMemberInvite = (variables) => fetch$1({
400
+ const acceptWorkspaceMemberInvite = (variables, signal) => fetch$1({
305
401
  url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept",
306
402
  method: "post",
307
- ...variables
403
+ ...variables,
404
+ signal
308
405
  });
309
- const getDatabaseList = (variables) => fetch$1({
406
+ const getDatabaseList = (variables, signal) => fetch$1({
310
407
  url: "/dbs",
311
408
  method: "get",
312
- ...variables
409
+ ...variables,
410
+ signal
313
411
  });
314
- const getBranchList = (variables) => fetch$1({
412
+ const getBranchList = (variables, signal) => fetch$1({
315
413
  url: "/dbs/{dbName}",
316
414
  method: "get",
317
- ...variables
415
+ ...variables,
416
+ signal
318
417
  });
319
- const createDatabase = (variables) => fetch$1({
418
+ const createDatabase = (variables, signal) => fetch$1({
320
419
  url: "/dbs/{dbName}",
321
420
  method: "put",
322
- ...variables
421
+ ...variables,
422
+ signal
323
423
  });
324
- const deleteDatabase = (variables) => fetch$1({
424
+ const deleteDatabase = (variables, signal) => fetch$1({
325
425
  url: "/dbs/{dbName}",
326
426
  method: "delete",
327
- ...variables
427
+ ...variables,
428
+ signal
328
429
  });
329
- const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
330
- const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
331
- const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
332
- const resolveBranch = (variables) => fetch$1({
430
+ const getDatabaseMetadata = (variables, signal) => fetch$1({
431
+ url: "/dbs/{dbName}/metadata",
432
+ method: "get",
433
+ ...variables,
434
+ signal
435
+ });
436
+ const updateDatabaseMetadata = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/metadata", method: "patch", ...variables, signal });
437
+ const getGitBranchesMapping = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables, signal });
438
+ const addGitBranchesEntry = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables, signal });
439
+ const removeGitBranchesEntry = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables, signal });
440
+ const resolveBranch = (variables, signal) => fetch$1({
333
441
  url: "/dbs/{dbName}/resolveBranch",
334
442
  method: "get",
335
- ...variables
443
+ ...variables,
444
+ signal
336
445
  });
337
- const getBranchDetails = (variables) => fetch$1({
338
- url: "/db/{dbBranchName}",
446
+ const queryMigrationRequests = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/migrations/query", method: "post", ...variables, signal });
447
+ const createMigrationRequest = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/migrations", method: "post", ...variables, signal });
448
+ const getMigrationRequest = (variables, signal) => fetch$1({
449
+ url: "/dbs/{dbName}/migrations/{mrNumber}",
339
450
  method: "get",
340
- ...variables
451
+ ...variables,
452
+ signal
341
453
  });
342
- const createBranch = (variables) => fetch$1({
454
+ const updateMigrationRequest = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}", method: "patch", ...variables, signal });
455
+ const listMigrationRequestsCommits = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/commits", method: "post", ...variables, signal });
456
+ const compareMigrationRequest = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/compare", method: "post", ...variables, signal });
457
+ const getMigrationRequestIsMerged = (variables, signal) => fetch$1({ url: "/dbs/{dbName}/migrations/{mrNumber}/merge", method: "get", ...variables, signal });
458
+ const mergeMigrationRequest = (variables, signal) => fetch$1({
459
+ url: "/dbs/{dbName}/migrations/{mrNumber}/merge",
460
+ method: "post",
461
+ ...variables,
462
+ signal
463
+ });
464
+ const getBranchDetails = (variables, signal) => fetch$1({
343
465
  url: "/db/{dbBranchName}",
344
- method: "put",
345
- ...variables
466
+ method: "get",
467
+ ...variables,
468
+ signal
346
469
  });
347
- const deleteBranch = (variables) => fetch$1({
470
+ const createBranch = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}", method: "put", ...variables, signal });
471
+ const deleteBranch = (variables, signal) => fetch$1({
348
472
  url: "/db/{dbBranchName}",
349
473
  method: "delete",
350
- ...variables
474
+ ...variables,
475
+ signal
351
476
  });
352
- const updateBranchMetadata = (variables) => fetch$1({
477
+ const updateBranchMetadata = (variables, signal) => fetch$1({
353
478
  url: "/db/{dbBranchName}/metadata",
354
479
  method: "put",
355
- ...variables
480
+ ...variables,
481
+ signal
356
482
  });
357
- const getBranchMetadata = (variables) => fetch$1({
483
+ const getBranchMetadata = (variables, signal) => fetch$1({
358
484
  url: "/db/{dbBranchName}/metadata",
359
485
  method: "get",
360
- ...variables
486
+ ...variables,
487
+ signal
488
+ });
489
+ const getBranchMigrationHistory = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables, signal });
490
+ const executeBranchMigrationPlan = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables, signal });
491
+ const getBranchMigrationPlan = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables, signal });
492
+ const compareBranchWithUserSchema = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/schema/compare", method: "post", ...variables, signal });
493
+ const compareBranchSchemas = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/schema/compare/{branchName}", method: "post", ...variables, signal });
494
+ const updateBranchSchema = (variables, signal) => fetch$1({
495
+ url: "/db/{dbBranchName}/schema/update",
496
+ method: "post",
497
+ ...variables,
498
+ signal
361
499
  });
362
- const getBranchMigrationHistory = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables });
363
- const executeBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables });
364
- const getBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables });
365
- const getBranchStats = (variables) => fetch$1({
500
+ const previewBranchSchemaEdit = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables, signal });
501
+ const applyBranchSchemaEdit = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables, signal });
502
+ const getBranchSchemaHistory = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/schema/history", method: "post", ...variables, signal });
503
+ const getBranchStats = (variables, signal) => fetch$1({
366
504
  url: "/db/{dbBranchName}/stats",
367
505
  method: "get",
368
- ...variables
506
+ ...variables,
507
+ signal
369
508
  });
370
- const createTable = (variables) => fetch$1({
509
+ const createTable = (variables, signal) => fetch$1({
371
510
  url: "/db/{dbBranchName}/tables/{tableName}",
372
511
  method: "put",
373
- ...variables
512
+ ...variables,
513
+ signal
374
514
  });
375
- const deleteTable = (variables) => fetch$1({
515
+ const deleteTable = (variables, signal) => fetch$1({
376
516
  url: "/db/{dbBranchName}/tables/{tableName}",
377
517
  method: "delete",
378
- ...variables
518
+ ...variables,
519
+ signal
379
520
  });
380
- const updateTable = (variables) => fetch$1({
521
+ const updateTable = (variables, signal) => fetch$1({
381
522
  url: "/db/{dbBranchName}/tables/{tableName}",
382
523
  method: "patch",
383
- ...variables
524
+ ...variables,
525
+ signal
384
526
  });
385
- const getTableSchema = (variables) => fetch$1({
527
+ const getTableSchema = (variables, signal) => fetch$1({
386
528
  url: "/db/{dbBranchName}/tables/{tableName}/schema",
387
529
  method: "get",
388
- ...variables
530
+ ...variables,
531
+ signal
389
532
  });
390
- const setTableSchema = (variables) => fetch$1({
533
+ const setTableSchema = (variables, signal) => fetch$1({
391
534
  url: "/db/{dbBranchName}/tables/{tableName}/schema",
392
535
  method: "put",
393
- ...variables
536
+ ...variables,
537
+ signal
394
538
  });
395
- const getTableColumns = (variables) => fetch$1({
539
+ const getTableColumns = (variables, signal) => fetch$1({
396
540
  url: "/db/{dbBranchName}/tables/{tableName}/columns",
397
541
  method: "get",
398
- ...variables
542
+ ...variables,
543
+ signal
399
544
  });
400
- const addTableColumn = (variables) => fetch$1({
545
+ const addTableColumn = (variables, signal) => fetch$1({
401
546
  url: "/db/{dbBranchName}/tables/{tableName}/columns",
402
547
  method: "post",
403
- ...variables
548
+ ...variables,
549
+ signal
404
550
  });
405
- const getColumn = (variables) => fetch$1({
551
+ const getColumn = (variables, signal) => fetch$1({
406
552
  url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
407
553
  method: "get",
408
- ...variables
554
+ ...variables,
555
+ signal
409
556
  });
410
- const deleteColumn = (variables) => fetch$1({
557
+ const deleteColumn = (variables, signal) => fetch$1({
411
558
  url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
412
559
  method: "delete",
413
- ...variables
560
+ ...variables,
561
+ signal
414
562
  });
415
- const updateColumn = (variables) => fetch$1({
563
+ const updateColumn = (variables, signal) => fetch$1({
416
564
  url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
417
565
  method: "patch",
418
- ...variables
419
- });
420
- const insertRecord = (variables) => fetch$1({
421
- url: "/db/{dbBranchName}/tables/{tableName}/data",
422
- method: "post",
423
- ...variables
566
+ ...variables,
567
+ signal
424
568
  });
425
- const insertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables });
426
- const updateRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables });
427
- const upsertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables });
428
- const deleteRecord = (variables) => fetch$1({
569
+ const insertRecord = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
570
+ const insertRecordWithID = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables, signal });
571
+ const updateRecordWithID = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables, signal });
572
+ const upsertRecordWithID = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables, signal });
573
+ const deleteRecord = (variables, signal) => fetch$1({
429
574
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
430
575
  method: "delete",
431
- ...variables
576
+ ...variables,
577
+ signal
432
578
  });
433
- const getRecord = (variables) => fetch$1({
579
+ const getRecord = (variables, signal) => fetch$1({
434
580
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
435
581
  method: "get",
436
- ...variables
582
+ ...variables,
583
+ signal
437
584
  });
438
- const bulkInsertTableRecords = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/bulk", method: "post", ...variables });
439
- const queryTable = (variables) => fetch$1({
585
+ const bulkInsertTableRecords = (variables, signal) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/bulk", method: "post", ...variables, signal });
586
+ const queryTable = (variables, signal) => fetch$1({
440
587
  url: "/db/{dbBranchName}/tables/{tableName}/query",
441
588
  method: "post",
442
- ...variables
589
+ ...variables,
590
+ signal
443
591
  });
444
- const searchTable = (variables) => fetch$1({
592
+ const searchTable = (variables, signal) => fetch$1({
445
593
  url: "/db/{dbBranchName}/tables/{tableName}/search",
446
594
  method: "post",
447
- ...variables
595
+ ...variables,
596
+ signal
448
597
  });
449
- const searchBranch = (variables) => fetch$1({
598
+ const searchBranch = (variables, signal) => fetch$1({
450
599
  url: "/db/{dbBranchName}/search",
451
600
  method: "post",
452
- ...variables
601
+ ...variables,
602
+ signal
603
+ });
604
+ const summarizeTable = (variables, signal) => fetch$1({
605
+ url: "/db/{dbBranchName}/tables/{tableName}/summarize",
606
+ method: "post",
607
+ ...variables,
608
+ signal
609
+ });
610
+ const aggregateTable = (variables, signal) => fetch$1({
611
+ url: "/db/{dbBranchName}/tables/{tableName}/aggregate",
612
+ method: "post",
613
+ ...variables,
614
+ signal
615
+ });
616
+ const cPGetDatabaseList = (variables, signal) => fetch$1({
617
+ url: "/workspaces/{workspaceId}/dbs",
618
+ method: "get",
619
+ ...variables,
620
+ signal
621
+ });
622
+ const cPCreateDatabase = (variables, signal) => fetch$1({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "put", ...variables, signal });
623
+ const cPDeleteDatabase = (variables, signal) => fetch$1({
624
+ url: "/workspaces/{workspaceId}/dbs/{dbName}",
625
+ method: "delete",
626
+ ...variables,
627
+ signal
453
628
  });
629
+ const cPGetCPDatabaseMetadata = (variables, signal) => fetch$1(
630
+ { url: "/workspaces/{workspaceId}/dbs/{dbName}/metadata", method: "get", ...variables, signal }
631
+ );
632
+ const cPUpdateCPDatabaseMetadata = (variables, signal) => fetch$1({ url: "/workspaces/{workspaceId}/dbs/{dbName}/metadata", method: "patch", ...variables, signal });
454
633
  const operationsByTag = {
455
634
  users: { getUser, updateUser, deleteUser, getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
456
635
  workspaces: {
@@ -463,6 +642,7 @@ const operationsByTag = {
463
642
  updateWorkspaceMemberRole,
464
643
  removeWorkspaceMember,
465
644
  inviteWorkspaceMember,
645
+ updateWorkspaceMemberInvite,
466
646
  cancelWorkspaceMemberInvite,
467
647
  resendWorkspaceMemberInvite,
468
648
  acceptWorkspaceMemberInvite
@@ -471,6 +651,8 @@ const operationsByTag = {
471
651
  getDatabaseList,
472
652
  createDatabase,
473
653
  deleteDatabase,
654
+ getDatabaseMetadata,
655
+ updateDatabaseMetadata,
474
656
  getGitBranchesMapping,
475
657
  addGitBranchesEntry,
476
658
  removeGitBranchesEntry,
@@ -483,10 +665,28 @@ const operationsByTag = {
483
665
  deleteBranch,
484
666
  updateBranchMetadata,
485
667
  getBranchMetadata,
668
+ getBranchStats
669
+ },
670
+ migrationRequests: {
671
+ queryMigrationRequests,
672
+ createMigrationRequest,
673
+ getMigrationRequest,
674
+ updateMigrationRequest,
675
+ listMigrationRequestsCommits,
676
+ compareMigrationRequest,
677
+ getMigrationRequestIsMerged,
678
+ mergeMigrationRequest
679
+ },
680
+ branchSchema: {
486
681
  getBranchMigrationHistory,
487
682
  executeBranchMigrationPlan,
488
683
  getBranchMigrationPlan,
489
- getBranchStats
684
+ compareBranchWithUserSchema,
685
+ compareBranchSchemas,
686
+ updateBranchSchema,
687
+ previewBranchSchemaEdit,
688
+ applyBranchSchemaEdit,
689
+ getBranchSchemaHistory
490
690
  },
491
691
  table: {
492
692
  createTable,
@@ -510,14 +710,23 @@ const operationsByTag = {
510
710
  bulkInsertTableRecords,
511
711
  queryTable,
512
712
  searchTable,
513
- searchBranch
713
+ searchBranch,
714
+ summarizeTable,
715
+ aggregateTable
716
+ },
717
+ databases: {
718
+ cPGetDatabaseList,
719
+ cPCreateDatabase,
720
+ cPDeleteDatabase,
721
+ cPGetCPDatabaseMetadata,
722
+ cPUpdateCPDatabaseMetadata
514
723
  }
515
724
  };
516
725
 
517
726
  function getHostUrl(provider, type) {
518
- if (isValidAlias(provider)) {
727
+ if (isHostProviderAlias(provider)) {
519
728
  return providers[provider][type];
520
- } else if (isValidBuilder(provider)) {
729
+ } else if (isHostProviderBuilder(provider)) {
521
730
  return provider[type];
522
731
  }
523
732
  throw new Error("Invalid API provider");
@@ -532,12 +741,21 @@ const providers = {
532
741
  workspaces: "https://{workspaceId}.staging.xatabase.co"
533
742
  }
534
743
  };
535
- function isValidAlias(alias) {
744
+ function isHostProviderAlias(alias) {
536
745
  return isString(alias) && Object.keys(providers).includes(alias);
537
746
  }
538
- function isValidBuilder(builder) {
747
+ function isHostProviderBuilder(builder) {
539
748
  return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
540
749
  }
750
+ function parseProviderString(provider = "production") {
751
+ if (isHostProviderAlias(provider)) {
752
+ return provider;
753
+ }
754
+ const [main, workspaces] = provider.split(",");
755
+ if (!main || !workspaces)
756
+ return null;
757
+ return { main, workspaces };
758
+ }
541
759
 
542
760
  var __accessCheck$7 = (obj, member, msg) => {
543
761
  if (!member.has(obj))
@@ -563,7 +781,8 @@ class XataApiClient {
563
781
  __privateAdd$7(this, _extraProps, void 0);
564
782
  __privateAdd$7(this, _namespaces, {});
565
783
  const provider = options.host ?? "production";
566
- const apiKey = options?.apiKey ?? getAPIKey();
784
+ const apiKey = options.apiKey ?? getAPIKey();
785
+ const trace = options.trace ?? defaultTrace;
567
786
  if (!apiKey) {
568
787
  throw new Error("Could not resolve a valid apiKey");
569
788
  }
@@ -571,7 +790,8 @@ class XataApiClient {
571
790
  apiUrl: getHostUrl(provider, "main"),
572
791
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
573
792
  fetchImpl: getFetchImplementation(options.fetch),
574
- apiKey
793
+ apiKey,
794
+ trace
575
795
  });
576
796
  }
577
797
  get user() {
@@ -604,6 +824,16 @@ class XataApiClient {
604
824
  __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
605
825
  return __privateGet$7(this, _namespaces).records;
606
826
  }
827
+ get migrationRequests() {
828
+ if (!__privateGet$7(this, _namespaces).migrationRequests)
829
+ __privateGet$7(this, _namespaces).migrationRequests = new MigrationRequestsApi(__privateGet$7(this, _extraProps));
830
+ return __privateGet$7(this, _namespaces).migrationRequests;
831
+ }
832
+ get branchSchema() {
833
+ if (!__privateGet$7(this, _namespaces).branchSchema)
834
+ __privateGet$7(this, _namespaces).branchSchema = new BranchSchemaApi(__privateGet$7(this, _extraProps));
835
+ return __privateGet$7(this, _namespaces).branchSchema;
836
+ }
607
837
  }
608
838
  _extraProps = new WeakMap();
609
839
  _namespaces = new WeakMap();
@@ -694,6 +924,13 @@ class WorkspaceApi {
694
924
  ...this.extraProps
695
925
  });
696
926
  }
927
+ updateWorkspaceMemberInvite(workspaceId, inviteId, role) {
928
+ return operationsByTag.workspaces.updateWorkspaceMemberInvite({
929
+ pathParams: { workspaceId, inviteId },
930
+ body: { role },
931
+ ...this.extraProps
932
+ });
933
+ }
697
934
  cancelWorkspaceMemberInvite(workspaceId, inviteId) {
698
935
  return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
699
936
  pathParams: { workspaceId, inviteId },
@@ -736,6 +973,19 @@ class DatabaseApi {
736
973
  ...this.extraProps
737
974
  });
738
975
  }
976
+ getDatabaseMetadata(workspace, dbName) {
977
+ return operationsByTag.database.getDatabaseMetadata({
978
+ pathParams: { workspace, dbName },
979
+ ...this.extraProps
980
+ });
981
+ }
982
+ updateDatabaseMetadata(workspace, dbName, options = {}) {
983
+ return operationsByTag.database.updateDatabaseMetadata({
984
+ pathParams: { workspace, dbName },
985
+ body: options,
986
+ ...this.extraProps
987
+ });
988
+ }
739
989
  getGitBranchesMapping(workspace, dbName) {
740
990
  return operationsByTag.database.getGitBranchesMapping({
741
991
  pathParams: { workspace, dbName },
@@ -807,27 +1057,6 @@ class BranchApi {
807
1057
  ...this.extraProps
808
1058
  });
809
1059
  }
810
- getBranchMigrationHistory(workspace, database, branch, options = {}) {
811
- return operationsByTag.branch.getBranchMigrationHistory({
812
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
813
- body: options,
814
- ...this.extraProps
815
- });
816
- }
817
- executeBranchMigrationPlan(workspace, database, branch, migrationPlan) {
818
- return operationsByTag.branch.executeBranchMigrationPlan({
819
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
820
- body: migrationPlan,
821
- ...this.extraProps
822
- });
823
- }
824
- getBranchMigrationPlan(workspace, database, branch, schema) {
825
- return operationsByTag.branch.getBranchMigrationPlan({
826
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
827
- body: schema,
828
- ...this.extraProps
829
- });
830
- }
831
1060
  getBranchStats(workspace, database, branch) {
832
1061
  return operationsByTag.branch.getBranchStats({
833
1062
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -908,9 +1137,10 @@ class RecordsApi {
908
1137
  constructor(extraProps) {
909
1138
  this.extraProps = extraProps;
910
1139
  }
911
- insertRecord(workspace, database, branch, tableName, record) {
1140
+ insertRecord(workspace, database, branch, tableName, record, options = {}) {
912
1141
  return operationsByTag.records.insertRecord({
913
1142
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1143
+ queryParams: options,
914
1144
  body: record,
915
1145
  ...this.extraProps
916
1146
  });
@@ -939,21 +1169,24 @@ class RecordsApi {
939
1169
  ...this.extraProps
940
1170
  });
941
1171
  }
942
- deleteRecord(workspace, database, branch, tableName, recordId) {
1172
+ deleteRecord(workspace, database, branch, tableName, recordId, options = {}) {
943
1173
  return operationsByTag.records.deleteRecord({
944
1174
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1175
+ queryParams: options,
945
1176
  ...this.extraProps
946
1177
  });
947
1178
  }
948
1179
  getRecord(workspace, database, branch, tableName, recordId, options = {}) {
949
1180
  return operationsByTag.records.getRecord({
950
1181
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1182
+ queryParams: options,
951
1183
  ...this.extraProps
952
1184
  });
953
1185
  }
954
- bulkInsertTableRecords(workspace, database, branch, tableName, records) {
1186
+ bulkInsertTableRecords(workspace, database, branch, tableName, records, options = {}) {
955
1187
  return operationsByTag.records.bulkInsertTableRecords({
956
1188
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1189
+ queryParams: options,
957
1190
  body: { records },
958
1191
  ...this.extraProps
959
1192
  });
@@ -979,6 +1212,138 @@ class RecordsApi {
979
1212
  ...this.extraProps
980
1213
  });
981
1214
  }
1215
+ summarizeTable(workspace, database, branch, tableName, query) {
1216
+ return operationsByTag.records.summarizeTable({
1217
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1218
+ body: query,
1219
+ ...this.extraProps
1220
+ });
1221
+ }
1222
+ }
1223
+ class MigrationRequestsApi {
1224
+ constructor(extraProps) {
1225
+ this.extraProps = extraProps;
1226
+ }
1227
+ queryMigrationRequests(workspace, database, options = {}) {
1228
+ return operationsByTag.migrationRequests.queryMigrationRequests({
1229
+ pathParams: { workspace, dbName: database },
1230
+ body: options,
1231
+ ...this.extraProps
1232
+ });
1233
+ }
1234
+ createMigrationRequest(workspace, database, options) {
1235
+ return operationsByTag.migrationRequests.createMigrationRequest({
1236
+ pathParams: { workspace, dbName: database },
1237
+ body: options,
1238
+ ...this.extraProps
1239
+ });
1240
+ }
1241
+ getMigrationRequest(workspace, database, migrationRequest) {
1242
+ return operationsByTag.migrationRequests.getMigrationRequest({
1243
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1244
+ ...this.extraProps
1245
+ });
1246
+ }
1247
+ updateMigrationRequest(workspace, database, migrationRequest, options) {
1248
+ return operationsByTag.migrationRequests.updateMigrationRequest({
1249
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1250
+ body: options,
1251
+ ...this.extraProps
1252
+ });
1253
+ }
1254
+ listMigrationRequestsCommits(workspace, database, migrationRequest, options = {}) {
1255
+ return operationsByTag.migrationRequests.listMigrationRequestsCommits({
1256
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1257
+ body: options,
1258
+ ...this.extraProps
1259
+ });
1260
+ }
1261
+ compareMigrationRequest(workspace, database, migrationRequest) {
1262
+ return operationsByTag.migrationRequests.compareMigrationRequest({
1263
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1264
+ ...this.extraProps
1265
+ });
1266
+ }
1267
+ getMigrationRequestIsMerged(workspace, database, migrationRequest) {
1268
+ return operationsByTag.migrationRequests.getMigrationRequestIsMerged({
1269
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1270
+ ...this.extraProps
1271
+ });
1272
+ }
1273
+ mergeMigrationRequest(workspace, database, migrationRequest) {
1274
+ return operationsByTag.migrationRequests.mergeMigrationRequest({
1275
+ pathParams: { workspace, dbName: database, mrNumber: migrationRequest },
1276
+ ...this.extraProps
1277
+ });
1278
+ }
1279
+ }
1280
+ class BranchSchemaApi {
1281
+ constructor(extraProps) {
1282
+ this.extraProps = extraProps;
1283
+ }
1284
+ getBranchMigrationHistory(workspace, database, branch, options = {}) {
1285
+ return operationsByTag.branchSchema.getBranchMigrationHistory({
1286
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1287
+ body: options,
1288
+ ...this.extraProps
1289
+ });
1290
+ }
1291
+ executeBranchMigrationPlan(workspace, database, branch, migrationPlan) {
1292
+ return operationsByTag.branchSchema.executeBranchMigrationPlan({
1293
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1294
+ body: migrationPlan,
1295
+ ...this.extraProps
1296
+ });
1297
+ }
1298
+ getBranchMigrationPlan(workspace, database, branch, schema) {
1299
+ return operationsByTag.branchSchema.getBranchMigrationPlan({
1300
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1301
+ body: schema,
1302
+ ...this.extraProps
1303
+ });
1304
+ }
1305
+ compareBranchWithUserSchema(workspace, database, branch, schema) {
1306
+ return operationsByTag.branchSchema.compareBranchWithUserSchema({
1307
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1308
+ body: { schema },
1309
+ ...this.extraProps
1310
+ });
1311
+ }
1312
+ compareBranchSchemas(workspace, database, branch, branchName, schema) {
1313
+ return operationsByTag.branchSchema.compareBranchSchemas({
1314
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, branchName },
1315
+ body: { schema },
1316
+ ...this.extraProps
1317
+ });
1318
+ }
1319
+ updateBranchSchema(workspace, database, branch, migration) {
1320
+ return operationsByTag.branchSchema.updateBranchSchema({
1321
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1322
+ body: migration,
1323
+ ...this.extraProps
1324
+ });
1325
+ }
1326
+ previewBranchSchemaEdit(workspace, database, branch, migration) {
1327
+ return operationsByTag.branchSchema.previewBranchSchemaEdit({
1328
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1329
+ body: migration,
1330
+ ...this.extraProps
1331
+ });
1332
+ }
1333
+ applyBranchSchemaEdit(workspace, database, branch, edits) {
1334
+ return operationsByTag.branchSchema.applyBranchSchemaEdit({
1335
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1336
+ body: { edits },
1337
+ ...this.extraProps
1338
+ });
1339
+ }
1340
+ getBranchSchemaHistory(workspace, database, branch, options = {}) {
1341
+ return operationsByTag.branchSchema.getBranchSchemaHistory({
1342
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1343
+ body: options,
1344
+ ...this.extraProps
1345
+ });
1346
+ }
982
1347
  }
983
1348
 
984
1349
  class XataApiPlugin {
@@ -1042,10 +1407,10 @@ function isCursorPaginationOptions(options) {
1042
1407
  return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
1043
1408
  }
1044
1409
  const _RecordArray = class extends Array {
1045
- constructor(page, overrideRecords) {
1046
- super(..._RecordArray.parseConstructorParams(page, overrideRecords));
1410
+ constructor(...args) {
1411
+ super(..._RecordArray.parseConstructorParams(...args));
1047
1412
  __privateAdd$6(this, _page, void 0);
1048
- __privateSet$6(this, _page, page);
1413
+ __privateSet$6(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
1049
1414
  }
1050
1415
  static parseConstructorParams(...args) {
1051
1416
  if (args.length === 1 && typeof args[0] === "number") {
@@ -1057,6 +1422,12 @@ const _RecordArray = class extends Array {
1057
1422
  }
1058
1423
  return new Array(...args);
1059
1424
  }
1425
+ toArray() {
1426
+ return new Array(...this);
1427
+ }
1428
+ map(callbackfn, thisArg) {
1429
+ return this.toArray().map(callbackfn, thisArg);
1430
+ }
1060
1431
  async nextPage(size, offset) {
1061
1432
  const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1062
1433
  return new _RecordArray(newPage);
@@ -1098,9 +1469,14 @@ var __privateSet$5 = (obj, member, value, setter) => {
1098
1469
  setter ? setter.call(obj, value) : member.set(obj, value);
1099
1470
  return value;
1100
1471
  };
1101
- var _table$1, _repository, _data;
1472
+ var __privateMethod$3 = (obj, member, method) => {
1473
+ __accessCheck$5(obj, member, "access private method");
1474
+ return method;
1475
+ };
1476
+ var _table$1, _repository, _data, _cleanFilterConstraint, cleanFilterConstraint_fn;
1102
1477
  const _Query = class {
1103
1478
  constructor(repository, table, data, rawParent) {
1479
+ __privateAdd$5(this, _cleanFilterConstraint);
1104
1480
  __privateAdd$5(this, _table$1, void 0);
1105
1481
  __privateAdd$5(this, _repository, void 0);
1106
1482
  __privateAdd$5(this, _data, { filter: {} });
@@ -1157,21 +1533,29 @@ const _Query = class {
1157
1533
  }
1158
1534
  filter(a, b) {
1159
1535
  if (arguments.length === 1) {
1160
- const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
1536
+ const constraints = Object.entries(a ?? {}).map(([column, constraint]) => ({
1537
+ [column]: __privateMethod$3(this, _cleanFilterConstraint, cleanFilterConstraint_fn).call(this, column, constraint)
1538
+ }));
1161
1539
  const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1162
1540
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1163
1541
  } else {
1164
- const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
1542
+ const constraints = isDefined(a) && isDefined(b) ? [{ [a]: __privateMethod$3(this, _cleanFilterConstraint, cleanFilterConstraint_fn).call(this, a, b) }] : void 0;
1543
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1165
1544
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1166
1545
  }
1167
1546
  }
1168
- sort(column, direction) {
1547
+ sort(column, direction = "asc") {
1169
1548
  const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
1170
1549
  const sort = [...originalSort, { column, direction }];
1171
1550
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
1172
1551
  }
1173
1552
  select(columns) {
1174
- return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { columns }, __privateGet$5(this, _data));
1553
+ return new _Query(
1554
+ __privateGet$5(this, _repository),
1555
+ __privateGet$5(this, _table$1),
1556
+ { columns },
1557
+ __privateGet$5(this, _data)
1558
+ );
1175
1559
  }
1176
1560
  getPaginated(options = {}) {
1177
1561
  const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
@@ -1194,11 +1578,20 @@ const _Query = class {
1194
1578
  }
1195
1579
  }
1196
1580
  async getMany(options = {}) {
1197
- const page = await this.getPaginated(options);
1581
+ const { pagination = {}, ...rest } = options;
1582
+ const { size = PAGINATION_DEFAULT_SIZE, offset } = pagination;
1583
+ const batchSize = size <= PAGINATION_MAX_SIZE ? size : PAGINATION_MAX_SIZE;
1584
+ let page = await this.getPaginated({ ...rest, pagination: { size: batchSize, offset } });
1585
+ const results = [...page.records];
1586
+ while (page.hasNextPage() && results.length < size) {
1587
+ page = await page.nextPage();
1588
+ results.push(...page.records);
1589
+ }
1198
1590
  if (page.hasNextPage() && options.pagination?.size === void 0) {
1199
1591
  console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1200
1592
  }
1201
- return page.records;
1593
+ const array = new RecordArray(page, results.slice(0, size));
1594
+ return array;
1202
1595
  }
1203
1596
  async getAll(options = {}) {
1204
1597
  const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
@@ -1212,6 +1605,12 @@ const _Query = class {
1212
1605
  const records = await this.getMany({ ...options, pagination: { size: 1 } });
1213
1606
  return records[0] ?? null;
1214
1607
  }
1608
+ async getFirstOrThrow(options = {}) {
1609
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1610
+ if (records[0] === void 0)
1611
+ throw new Error("No results found.");
1612
+ return records[0];
1613
+ }
1215
1614
  cache(ttl) {
1216
1615
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1217
1616
  }
@@ -1235,6 +1634,17 @@ let Query = _Query;
1235
1634
  _table$1 = new WeakMap();
1236
1635
  _repository = new WeakMap();
1237
1636
  _data = new WeakMap();
1637
+ _cleanFilterConstraint = new WeakSet();
1638
+ cleanFilterConstraint_fn = function(column, value) {
1639
+ const columnType = __privateGet$5(this, _table$1).schema?.columns.find(({ name }) => name === column)?.type;
1640
+ if (columnType === "multiple" && (isString(value) || isStringArray(value))) {
1641
+ return { $includes: value };
1642
+ }
1643
+ if (columnType === "link" && isObject(value) && isString(value.id)) {
1644
+ return value.id;
1645
+ }
1646
+ return value;
1647
+ };
1238
1648
  function cleanParent(data, parent) {
1239
1649
  if (isCursorPaginationOptions(data.pagination)) {
1240
1650
  return { ...parent, sorting: void 0, filter: void 0 };
@@ -1296,203 +1706,286 @@ var __privateMethod$2 = (obj, member, method) => {
1296
1706
  __accessCheck$4(obj, member, "access private method");
1297
1707
  return method;
1298
1708
  };
1299
- var _table, _getFetchProps, _cache, _schemaTables$2, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _invalidateCache, invalidateCache_fn, _setCacheRecord, setCacheRecord_fn, _getCacheRecord, getCacheRecord_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaTables$1, getSchemaTables_fn$1;
1709
+ 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;
1300
1710
  class Repository extends Query {
1301
1711
  }
1302
1712
  class RestRepository extends Query {
1303
1713
  constructor(options) {
1304
- super(null, options.table, {});
1714
+ super(
1715
+ null,
1716
+ { name: options.table, schema: options.schemaTables?.find((table) => table.name === options.table) },
1717
+ {}
1718
+ );
1305
1719
  __privateAdd$4(this, _insertRecordWithoutId);
1306
1720
  __privateAdd$4(this, _insertRecordWithId);
1307
1721
  __privateAdd$4(this, _bulkInsertTableRecords);
1308
1722
  __privateAdd$4(this, _updateRecordWithID);
1309
1723
  __privateAdd$4(this, _upsertRecordWithID);
1310
1724
  __privateAdd$4(this, _deleteRecord);
1311
- __privateAdd$4(this, _invalidateCache);
1312
- __privateAdd$4(this, _setCacheRecord);
1313
- __privateAdd$4(this, _getCacheRecord);
1314
1725
  __privateAdd$4(this, _setCacheQuery);
1315
1726
  __privateAdd$4(this, _getCacheQuery);
1316
1727
  __privateAdd$4(this, _getSchemaTables$1);
1317
1728
  __privateAdd$4(this, _table, void 0);
1318
1729
  __privateAdd$4(this, _getFetchProps, void 0);
1730
+ __privateAdd$4(this, _db, void 0);
1319
1731
  __privateAdd$4(this, _cache, void 0);
1320
1732
  __privateAdd$4(this, _schemaTables$2, void 0);
1733
+ __privateAdd$4(this, _trace, void 0);
1321
1734
  __privateSet$4(this, _table, options.table);
1322
1735
  __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1323
- this.db = options.db;
1736
+ __privateSet$4(this, _db, options.db);
1324
1737
  __privateSet$4(this, _cache, options.pluginOptions.cache);
1325
1738
  __privateSet$4(this, _schemaTables$2, options.schemaTables);
1739
+ const trace = options.pluginOptions.trace ?? defaultTrace;
1740
+ __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
1741
+ return trace(name, fn, {
1742
+ ...options2,
1743
+ [TraceAttributes.TABLE]: __privateGet$4(this, _table),
1744
+ [TraceAttributes.KIND]: "sdk-operation",
1745
+ [TraceAttributes.VERSION]: VERSION
1746
+ });
1747
+ });
1326
1748
  }
1327
- async create(a, b) {
1328
- if (Array.isArray(a)) {
1329
- if (a.length === 0)
1330
- return [];
1331
- const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1332
- await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1333
- return records;
1334
- }
1335
- if (isString(a) && isObject(b)) {
1336
- if (a === "")
1337
- throw new Error("The id can't be empty");
1338
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1339
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1340
- return record;
1341
- }
1342
- if (isObject(a) && isString(a.id)) {
1343
- if (a.id === "")
1344
- throw new Error("The id can't be empty");
1345
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1346
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1347
- return record;
1348
- }
1349
- if (isObject(a)) {
1350
- const record = await __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1351
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1352
- return record;
1353
- }
1354
- throw new Error("Invalid arguments for create method");
1355
- }
1356
- async read(a) {
1357
- if (Array.isArray(a)) {
1358
- if (a.length === 0)
1359
- return [];
1360
- const ids = a.map((item) => isString(item) ? item : item.id).filter((id2) => isString(id2));
1361
- return this.getAll({ filter: { id: { $any: ids } } });
1362
- }
1363
- const id = isString(a) ? a : a.id;
1364
- if (isString(id)) {
1365
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, id);
1366
- if (cacheRecord)
1367
- return cacheRecord;
1368
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1369
- try {
1370
- const response = await getRecord({
1371
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: id },
1372
- ...fetchProps
1373
- });
1374
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1375
- return initObject(this.db, schemaTables, __privateGet$4(this, _table), response);
1376
- } catch (e) {
1377
- if (isObject(e) && e.status === 404) {
1378
- return null;
1749
+ async create(a, b, c) {
1750
+ return __privateGet$4(this, _trace).call(this, "create", async () => {
1751
+ if (Array.isArray(a)) {
1752
+ if (a.length === 0)
1753
+ return [];
1754
+ const columns = isStringArray(b) ? b : void 0;
1755
+ return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
1756
+ }
1757
+ if (isString(a) && isObject(b)) {
1758
+ if (a === "")
1759
+ throw new Error("The id can't be empty");
1760
+ const columns = isStringArray(c) ? c : void 0;
1761
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns);
1762
+ }
1763
+ if (isObject(a) && isString(a.id)) {
1764
+ if (a.id === "")
1765
+ throw new Error("The id can't be empty");
1766
+ const columns = isStringArray(b) ? b : void 0;
1767
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1768
+ }
1769
+ if (isObject(a)) {
1770
+ const columns = isStringArray(b) ? b : void 0;
1771
+ return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
1772
+ }
1773
+ throw new Error("Invalid arguments for create method");
1774
+ });
1775
+ }
1776
+ async read(a, b) {
1777
+ return __privateGet$4(this, _trace).call(this, "read", async () => {
1778
+ const columns = isStringArray(b) ? b : ["*"];
1779
+ if (Array.isArray(a)) {
1780
+ if (a.length === 0)
1781
+ return [];
1782
+ const ids = a.map((item) => extractId(item));
1783
+ const finalObjects = await this.getAll({ filter: { id: { $any: compact(ids) } }, columns });
1784
+ const dictionary = finalObjects.reduce((acc, object) => {
1785
+ acc[object.id] = object;
1786
+ return acc;
1787
+ }, {});
1788
+ return ids.map((id2) => dictionary[id2 ?? ""] ?? null);
1789
+ }
1790
+ const id = extractId(a);
1791
+ if (id) {
1792
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1793
+ try {
1794
+ const response = await getRecord({
1795
+ pathParams: {
1796
+ workspace: "{workspaceId}",
1797
+ dbBranchName: "{dbBranch}",
1798
+ tableName: __privateGet$4(this, _table),
1799
+ recordId: id
1800
+ },
1801
+ queryParams: { columns },
1802
+ ...fetchProps
1803
+ });
1804
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1805
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
1806
+ } catch (e) {
1807
+ if (isObject(e) && e.status === 404) {
1808
+ return null;
1809
+ }
1810
+ throw e;
1379
1811
  }
1380
- throw e;
1381
1812
  }
1382
- }
1813
+ return null;
1814
+ });
1383
1815
  }
1384
- async update(a, b) {
1385
- if (Array.isArray(a)) {
1386
- if (a.length === 0)
1387
- return [];
1388
- if (a.length > 100) {
1389
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1816
+ async readOrThrow(a, b) {
1817
+ return __privateGet$4(this, _trace).call(this, "readOrThrow", async () => {
1818
+ const result = await this.read(a, b);
1819
+ if (Array.isArray(result)) {
1820
+ const missingIds = compact(
1821
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
1822
+ );
1823
+ if (missingIds.length > 0) {
1824
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
1825
+ }
1826
+ return result;
1390
1827
  }
1391
- return Promise.all(a.map((object) => this.update(object)));
1392
- }
1393
- if (isString(a) && isObject(b)) {
1394
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1395
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1396
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1397
- return record;
1398
- }
1399
- if (isObject(a) && isString(a.id)) {
1400
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1401
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1402
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1403
- return record;
1404
- }
1405
- throw new Error("Invalid arguments for update method");
1406
- }
1407
- async createOrUpdate(a, b) {
1408
- if (Array.isArray(a)) {
1409
- if (a.length === 0)
1410
- return [];
1411
- if (a.length > 100) {
1412
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1828
+ if (result === null) {
1829
+ const id = extractId(a) ?? "unknown";
1830
+ throw new Error(`Record with id ${id} not found`);
1413
1831
  }
1414
- return Promise.all(a.map((object) => this.createOrUpdate(object)));
1415
- }
1416
- if (isString(a) && isObject(b)) {
1417
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1418
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1419
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1420
- return record;
1421
- }
1422
- if (isObject(a) && isString(a.id)) {
1423
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1424
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1425
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1426
- return record;
1427
- }
1428
- throw new Error("Invalid arguments for createOrUpdate method");
1429
- }
1430
- async delete(a) {
1431
- if (Array.isArray(a)) {
1432
- if (a.length === 0)
1433
- return;
1434
- if (a.length > 100) {
1435
- console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1832
+ return result;
1833
+ });
1834
+ }
1835
+ async update(a, b, c) {
1836
+ return __privateGet$4(this, _trace).call(this, "update", async () => {
1837
+ if (Array.isArray(a)) {
1838
+ if (a.length === 0)
1839
+ return [];
1840
+ if (a.length > 100) {
1841
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1842
+ }
1843
+ const columns = isStringArray(b) ? b : ["*"];
1844
+ return Promise.all(a.map((object) => this.update(object, columns)));
1436
1845
  }
1437
- await Promise.all(a.map((id) => this.delete(id)));
1438
- return;
1439
- }
1440
- if (isString(a)) {
1441
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1442
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1443
- return;
1444
- }
1445
- if (isObject(a) && isString(a.id)) {
1446
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1447
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1448
- return;
1449
- }
1450
- throw new Error("Invalid arguments for delete method");
1846
+ if (isString(a) && isObject(b)) {
1847
+ const columns = isStringArray(c) ? c : void 0;
1848
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns);
1849
+ }
1850
+ if (isObject(a) && isString(a.id)) {
1851
+ const columns = isStringArray(b) ? b : void 0;
1852
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1853
+ }
1854
+ throw new Error("Invalid arguments for update method");
1855
+ });
1856
+ }
1857
+ async updateOrThrow(a, b, c) {
1858
+ return __privateGet$4(this, _trace).call(this, "updateOrThrow", async () => {
1859
+ const result = await this.update(a, b, c);
1860
+ if (Array.isArray(result)) {
1861
+ const missingIds = compact(
1862
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
1863
+ );
1864
+ if (missingIds.length > 0) {
1865
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
1866
+ }
1867
+ return result;
1868
+ }
1869
+ if (result === null) {
1870
+ const id = extractId(a) ?? "unknown";
1871
+ throw new Error(`Record with id ${id} not found`);
1872
+ }
1873
+ return result;
1874
+ });
1875
+ }
1876
+ async createOrUpdate(a, b, c) {
1877
+ return __privateGet$4(this, _trace).call(this, "createOrUpdate", async () => {
1878
+ if (Array.isArray(a)) {
1879
+ if (a.length === 0)
1880
+ return [];
1881
+ if (a.length > 100) {
1882
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1883
+ }
1884
+ const columns = isStringArray(b) ? b : ["*"];
1885
+ return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
1886
+ }
1887
+ if (isString(a) && isObject(b)) {
1888
+ const columns = isStringArray(c) ? c : void 0;
1889
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns);
1890
+ }
1891
+ if (isObject(a) && isString(a.id)) {
1892
+ const columns = isStringArray(c) ? c : void 0;
1893
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1894
+ }
1895
+ throw new Error("Invalid arguments for createOrUpdate method");
1896
+ });
1897
+ }
1898
+ async delete(a, b) {
1899
+ return __privateGet$4(this, _trace).call(this, "delete", async () => {
1900
+ if (Array.isArray(a)) {
1901
+ if (a.length === 0)
1902
+ return [];
1903
+ if (a.length > 100) {
1904
+ console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1905
+ }
1906
+ return Promise.all(a.map((id) => this.delete(id, b)));
1907
+ }
1908
+ if (isString(a)) {
1909
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
1910
+ }
1911
+ if (isObject(a) && isString(a.id)) {
1912
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id, b);
1913
+ }
1914
+ throw new Error("Invalid arguments for delete method");
1915
+ });
1916
+ }
1917
+ async deleteOrThrow(a, b) {
1918
+ return __privateGet$4(this, _trace).call(this, "deleteOrThrow", async () => {
1919
+ const result = await this.delete(a, b);
1920
+ if (Array.isArray(result)) {
1921
+ const missingIds = compact(
1922
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
1923
+ );
1924
+ if (missingIds.length > 0) {
1925
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
1926
+ }
1927
+ return result;
1928
+ } else if (result === null) {
1929
+ const id = extractId(a) ?? "unknown";
1930
+ throw new Error(`Record with id ${id} not found`);
1931
+ }
1932
+ return result;
1933
+ });
1451
1934
  }
1452
1935
  async search(query, options = {}) {
1453
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1454
- const { records } = await searchTable({
1455
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1456
- body: {
1457
- query,
1458
- fuzziness: options.fuzziness,
1459
- highlight: options.highlight,
1460
- filter: options.filter
1461
- },
1462
- ...fetchProps
1936
+ return __privateGet$4(this, _trace).call(this, "search", async () => {
1937
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1938
+ const { records } = await searchTable({
1939
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1940
+ body: {
1941
+ query,
1942
+ fuzziness: options.fuzziness,
1943
+ prefix: options.prefix,
1944
+ highlight: options.highlight,
1945
+ filter: options.filter,
1946
+ boosters: options.boosters
1947
+ },
1948
+ ...fetchProps
1949
+ });
1950
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1951
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
1463
1952
  });
1464
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1465
- return records.map((item) => initObject(this.db, schemaTables, __privateGet$4(this, _table), item));
1466
1953
  }
1467
1954
  async query(query) {
1468
- const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1469
- if (cacheQuery)
1470
- return new Page(query, cacheQuery.meta, cacheQuery.records);
1471
- const data = query.getQueryOptions();
1472
- const body = {
1473
- filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1474
- sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1475
- page: data.pagination,
1476
- columns: data.columns
1477
- };
1478
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1479
- const { meta, records: objects } = await queryTable({
1480
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1481
- body,
1482
- ...fetchProps
1955
+ return __privateGet$4(this, _trace).call(this, "query", async () => {
1956
+ const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1957
+ if (cacheQuery)
1958
+ return new Page(query, cacheQuery.meta, cacheQuery.records);
1959
+ const data = query.getQueryOptions();
1960
+ const body = {
1961
+ filter: cleanFilter(data.filter),
1962
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1963
+ page: data.pagination,
1964
+ columns: data.columns
1965
+ };
1966
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1967
+ const { meta, records: objects } = await queryTable({
1968
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1969
+ body,
1970
+ ...fetchProps
1971
+ });
1972
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1973
+ const records = objects.map(
1974
+ (record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record, data.columns ?? ["*"])
1975
+ );
1976
+ await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1977
+ return new Page(query, meta, records);
1483
1978
  });
1484
- const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1485
- const records = objects.map((record) => initObject(this.db, schemaTables, __privateGet$4(this, _table), record));
1486
- await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1487
- return new Page(query, meta, records);
1488
1979
  }
1489
1980
  }
1490
1981
  _table = new WeakMap();
1491
1982
  _getFetchProps = new WeakMap();
1983
+ _db = new WeakMap();
1492
1984
  _cache = new WeakMap();
1493
1985
  _schemaTables$2 = new WeakMap();
1986
+ _trace = new WeakMap();
1494
1987
  _insertRecordWithoutId = new WeakSet();
1495
- insertRecordWithoutId_fn = async function(object) {
1988
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1496
1989
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1497
1990
  const record = transformObjectLinks(object);
1498
1991
  const response = await insertRecord({
@@ -1501,17 +1994,15 @@ insertRecordWithoutId_fn = async function(object) {
1501
1994
  dbBranchName: "{dbBranch}",
1502
1995
  tableName: __privateGet$4(this, _table)
1503
1996
  },
1997
+ queryParams: { columns },
1504
1998
  body: record,
1505
1999
  ...fetchProps
1506
2000
  });
1507
- const finalObject = await this.read(response.id);
1508
- if (!finalObject) {
1509
- throw new Error("The server failed to save the record");
1510
- }
1511
- return finalObject;
2001
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2002
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
1512
2003
  };
1513
2004
  _insertRecordWithId = new WeakSet();
1514
- insertRecordWithId_fn = async function(recordId, object) {
2005
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
1515
2006
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1516
2007
  const record = transformObjectLinks(object);
1517
2008
  const response = await insertRecordWithID({
@@ -1522,92 +2013,78 @@ insertRecordWithId_fn = async function(recordId, object) {
1522
2013
  recordId
1523
2014
  },
1524
2015
  body: record,
1525
- queryParams: { createOnly: true },
2016
+ queryParams: { createOnly: true, columns },
1526
2017
  ...fetchProps
1527
2018
  });
1528
- const finalObject = await this.read(response.id);
1529
- if (!finalObject) {
1530
- throw new Error("The server failed to save the record");
1531
- }
1532
- return finalObject;
2019
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2020
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
1533
2021
  };
1534
2022
  _bulkInsertTableRecords = new WeakSet();
1535
- bulkInsertTableRecords_fn = async function(objects) {
2023
+ bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
1536
2024
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1537
2025
  const records = objects.map((object) => transformObjectLinks(object));
1538
- const { recordIDs } = await bulkInsertTableRecords({
2026
+ const response = await bulkInsertTableRecords({
1539
2027
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
2028
+ queryParams: { columns },
1540
2029
  body: { records },
1541
2030
  ...fetchProps
1542
2031
  });
1543
- const finalObjects = await this.read(recordIDs);
1544
- if (finalObjects.length !== objects.length) {
1545
- throw new Error("The server failed to save some records");
2032
+ if (!isResponseWithRecords(response)) {
2033
+ throw new Error("Request included columns but server didn't include them");
1546
2034
  }
1547
- const dictionary = finalObjects.reduce((acc, object) => {
1548
- acc[object.id] = object;
1549
- return acc;
1550
- }, {});
1551
- return recordIDs.map((id) => dictionary[id]);
2035
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2036
+ return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, columns));
1552
2037
  };
1553
2038
  _updateRecordWithID = new WeakSet();
1554
- updateRecordWithID_fn = async function(recordId, object) {
2039
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1555
2040
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1556
2041
  const record = transformObjectLinks(object);
1557
- const response = await updateRecordWithID({
1558
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1559
- body: record,
1560
- ...fetchProps
1561
- });
1562
- const item = await this.read(response.id);
1563
- if (!item)
1564
- throw new Error("The server failed to save the record");
1565
- return item;
2042
+ try {
2043
+ const response = await updateRecordWithID({
2044
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
2045
+ queryParams: { columns },
2046
+ body: record,
2047
+ ...fetchProps
2048
+ });
2049
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2050
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2051
+ } catch (e) {
2052
+ if (isObject(e) && e.status === 404) {
2053
+ return null;
2054
+ }
2055
+ throw e;
2056
+ }
1566
2057
  };
1567
2058
  _upsertRecordWithID = new WeakSet();
1568
- upsertRecordWithID_fn = async function(recordId, object) {
2059
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1569
2060
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1570
2061
  const response = await upsertRecordWithID({
1571
2062
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
2063
+ queryParams: { columns },
1572
2064
  body: object,
1573
2065
  ...fetchProps
1574
2066
  });
1575
- const item = await this.read(response.id);
1576
- if (!item)
1577
- throw new Error("The server failed to save the record");
1578
- return item;
2067
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2068
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
1579
2069
  };
1580
2070
  _deleteRecord = new WeakSet();
1581
- deleteRecord_fn = async function(recordId) {
2071
+ deleteRecord_fn = async function(recordId, columns = ["*"]) {
1582
2072
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1583
- await deleteRecord({
1584
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1585
- ...fetchProps
1586
- });
1587
- };
1588
- _invalidateCache = new WeakSet();
1589
- invalidateCache_fn = async function(recordId) {
1590
- await __privateGet$4(this, _cache).delete(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1591
- const cacheItems = await __privateGet$4(this, _cache).getAll();
1592
- const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1593
- for (const [key, value] of queries) {
1594
- const ids = getIds(value);
1595
- if (ids.includes(recordId))
1596
- await __privateGet$4(this, _cache).delete(key);
2073
+ try {
2074
+ const response = await deleteRecord({
2075
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
2076
+ queryParams: { columns },
2077
+ ...fetchProps
2078
+ });
2079
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2080
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2081
+ } catch (e) {
2082
+ if (isObject(e) && e.status === 404) {
2083
+ return null;
2084
+ }
2085
+ throw e;
1597
2086
  }
1598
2087
  };
1599
- _setCacheRecord = new WeakSet();
1600
- setCacheRecord_fn = async function(record) {
1601
- if (!__privateGet$4(this, _cache).cacheRecords)
1602
- return;
1603
- await __privateGet$4(this, _cache).set(`rec_${__privateGet$4(this, _table)}:${record.id}`, record);
1604
- };
1605
- _getCacheRecord = new WeakSet();
1606
- getCacheRecord_fn = async function(recordId) {
1607
- if (!__privateGet$4(this, _cache).cacheRecords)
1608
- return null;
1609
- return __privateGet$4(this, _cache).get(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1610
- };
1611
2088
  _setCacheQuery = new WeakSet();
1612
2089
  setCacheQuery_fn = async function(query, meta, records) {
1613
2090
  await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
@@ -1643,7 +2120,7 @@ const transformObjectLinks = (object) => {
1643
2120
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1644
2121
  }, {});
1645
2122
  };
1646
- const initObject = (db, schemaTables, table, object) => {
2123
+ const initObject = (db, schemaTables, table, object, selectedColumns) => {
1647
2124
  const result = {};
1648
2125
  const { xata, ...rest } = object ?? {};
1649
2126
  Object.assign(result, rest);
@@ -1651,6 +2128,8 @@ const initObject = (db, schemaTables, table, object) => {
1651
2128
  if (!columns)
1652
2129
  console.error(`Table ${table} not found in schema`);
1653
2130
  for (const column of columns ?? []) {
2131
+ if (!isValidColumn(selectedColumns, column))
2132
+ continue;
1654
2133
  const value = result[column.name];
1655
2134
  switch (column.type) {
1656
2135
  case "datetime": {
@@ -1667,17 +2146,35 @@ const initObject = (db, schemaTables, table, object) => {
1667
2146
  if (!linkTable) {
1668
2147
  console.error(`Failed to parse link for field ${column.name}`);
1669
2148
  } else if (isObject(value)) {
1670
- result[column.name] = initObject(db, schemaTables, linkTable, value);
2149
+ const selectedLinkColumns = selectedColumns.reduce((acc, item) => {
2150
+ if (item === column.name) {
2151
+ return [...acc, "*"];
2152
+ }
2153
+ if (item.startsWith(`${column.name}.`)) {
2154
+ const [, ...path] = item.split(".");
2155
+ return [...acc, path.join(".")];
2156
+ }
2157
+ return acc;
2158
+ }, []);
2159
+ result[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
2160
+ } else {
2161
+ result[column.name] = null;
1671
2162
  }
1672
2163
  break;
1673
2164
  }
2165
+ default:
2166
+ result[column.name] = value ?? null;
2167
+ if (column.notNull === true && value === null) {
2168
+ console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
2169
+ }
2170
+ break;
1674
2171
  }
1675
2172
  }
1676
- result.read = function() {
1677
- return db[table].read(result["id"]);
2173
+ result.read = function(columns2) {
2174
+ return db[table].read(result["id"], columns2);
1678
2175
  };
1679
- result.update = function(data) {
1680
- return db[table].update(result["id"], data);
2176
+ result.update = function(data, columns2) {
2177
+ return db[table].update(result["id"], data, columns2);
1681
2178
  };
1682
2179
  result.delete = function() {
1683
2180
  return db[table].delete(result["id"]);
@@ -1691,14 +2188,30 @@ const initObject = (db, schemaTables, table, object) => {
1691
2188
  Object.freeze(result);
1692
2189
  return result;
1693
2190
  };
1694
- function getIds(value) {
1695
- if (Array.isArray(value)) {
1696
- return value.map((item) => getIds(item)).flat();
1697
- }
1698
- if (!isObject(value))
1699
- return [];
1700
- const nestedIds = Object.values(value).map((item) => getIds(item)).flat();
1701
- return isString(value.id) ? [value.id, ...nestedIds] : nestedIds;
2191
+ function isResponseWithRecords(value) {
2192
+ return isObject(value) && Array.isArray(value.records);
2193
+ }
2194
+ function extractId(value) {
2195
+ if (isString(value))
2196
+ return value;
2197
+ if (isObject(value) && isString(value.id))
2198
+ return value.id;
2199
+ return void 0;
2200
+ }
2201
+ function cleanFilter(filter) {
2202
+ if (!filter)
2203
+ return void 0;
2204
+ const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
2205
+ return values.length > 0 ? filter : void 0;
2206
+ }
2207
+ function isValidColumn(columns, column) {
2208
+ if (columns.includes("*"))
2209
+ return true;
2210
+ if (column.type === "link") {
2211
+ const linkColumns = columns.filter((item) => item.startsWith(column.name));
2212
+ return linkColumns.length > 0;
2213
+ }
2214
+ return columns.includes(column.name);
1702
2215
  }
1703
2216
 
1704
2217
  var __accessCheck$3 = (obj, member, msg) => {
@@ -1725,7 +2238,6 @@ class SimpleCache {
1725
2238
  __privateAdd$3(this, _map, void 0);
1726
2239
  __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1727
2240
  this.capacity = options.max ?? 500;
1728
- this.cacheRecords = options.cacheRecords ?? true;
1729
2241
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1730
2242
  }
1731
2243
  async getAll() {
@@ -1751,18 +2263,25 @@ class SimpleCache {
1751
2263
  }
1752
2264
  _map = new WeakMap();
1753
2265
 
1754
- const gt = (value) => ({ $gt: value });
1755
- const ge = (value) => ({ $ge: value });
1756
- const gte = (value) => ({ $ge: value });
1757
- const lt = (value) => ({ $lt: value });
1758
- const lte = (value) => ({ $le: value });
1759
- const le = (value) => ({ $le: value });
2266
+ const greaterThan = (value) => ({ $gt: value });
2267
+ const gt = greaterThan;
2268
+ const greaterThanEquals = (value) => ({ $ge: value });
2269
+ const greaterEquals = greaterThanEquals;
2270
+ const gte = greaterThanEquals;
2271
+ const ge = greaterThanEquals;
2272
+ const lessThan = (value) => ({ $lt: value });
2273
+ const lt = lessThan;
2274
+ const lessThanEquals = (value) => ({ $le: value });
2275
+ const lessEquals = lessThanEquals;
2276
+ const lte = lessThanEquals;
2277
+ const le = lessThanEquals;
1760
2278
  const exists = (column) => ({ $exists: column });
1761
2279
  const notExists = (column) => ({ $notExists: column });
1762
2280
  const startsWith = (value) => ({ $startsWith: value });
1763
2281
  const endsWith = (value) => ({ $endsWith: value });
1764
2282
  const pattern = (value) => ({ $pattern: value });
1765
2283
  const is = (value) => ({ $is: value });
2284
+ const equals = is;
1766
2285
  const isNot = (value) => ({ $isNot: value });
1767
2286
  const contains = (value) => ({ $contains: value });
1768
2287
  const includes = (value) => ({ $includes: value });
@@ -1797,16 +2316,19 @@ class SchemaPlugin extends XataPlugin {
1797
2316
  __privateSet$2(this, _schemaTables$1, schemaTables);
1798
2317
  }
1799
2318
  build(pluginOptions) {
1800
- const db = new Proxy({}, {
1801
- get: (_target, table) => {
1802
- if (!isString(table))
1803
- throw new Error("Invalid table name");
1804
- if (__privateGet$2(this, _tables)[table] === void 0) {
1805
- __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table });
2319
+ const db = new Proxy(
2320
+ {},
2321
+ {
2322
+ get: (_target, table) => {
2323
+ if (!isString(table))
2324
+ throw new Error("Invalid table name");
2325
+ if (__privateGet$2(this, _tables)[table] === void 0) {
2326
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
2327
+ }
2328
+ return __privateGet$2(this, _tables)[table];
1806
2329
  }
1807
- return __privateGet$2(this, _tables)[table];
1808
2330
  }
1809
- });
2331
+ );
1810
2332
  const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
1811
2333
  for (const table of tableNames) {
1812
2334
  db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
@@ -1856,7 +2378,7 @@ class SearchPlugin extends XataPlugin {
1856
2378
  const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1857
2379
  return records.map((record) => {
1858
2380
  const { table = "orphan" } = record.xata;
1859
- return { table, record: initObject(this.db, schemaTables, table, record) };
2381
+ return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
1860
2382
  });
1861
2383
  },
1862
2384
  byTable: async (query, options = {}) => {
@@ -1865,7 +2387,7 @@ class SearchPlugin extends XataPlugin {
1865
2387
  return records.reduce((acc, record) => {
1866
2388
  const { table = "orphan" } = record.xata;
1867
2389
  const items = acc[table] ?? [];
1868
- const item = initObject(this.db, schemaTables, table, record);
2390
+ const item = initObject(this.db, schemaTables, table, record, ["*"]);
1869
2391
  return { ...acc, [table]: [...items, item] };
1870
2392
  }, {});
1871
2393
  }
@@ -1876,10 +2398,10 @@ _schemaTables = new WeakMap();
1876
2398
  _search = new WeakSet();
1877
2399
  search_fn = async function(query, options, getFetchProps) {
1878
2400
  const fetchProps = await getFetchProps();
1879
- const { tables, fuzziness, highlight } = options ?? {};
2401
+ const { tables, fuzziness, highlight, prefix } = options ?? {};
1880
2402
  const { records } = await searchBranch({
1881
2403
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1882
- body: { tables, query, fuzziness, highlight },
2404
+ body: { tables, query, fuzziness, prefix, highlight },
1883
2405
  ...fetchProps
1884
2406
  });
1885
2407
  return records;
@@ -1920,9 +2442,13 @@ async function resolveXataBranch(gitBranch, options) {
1920
2442
  const databaseURL = options?.databaseURL || getDatabaseURL();
1921
2443
  const apiKey = options?.apiKey || getAPIKey();
1922
2444
  if (!databaseURL)
1923
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
2445
+ throw new Error(
2446
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2447
+ );
1924
2448
  if (!apiKey)
1925
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
2449
+ throw new Error(
2450
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2451
+ );
1926
2452
  const [protocol, , host, , dbName] = databaseURL.split("/");
1927
2453
  const [workspace] = host.split(".");
1928
2454
  const { fallbackBranch } = getEnvironment();
@@ -1932,7 +2458,8 @@ async function resolveXataBranch(gitBranch, options) {
1932
2458
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1933
2459
  workspacesApiUrl: `${protocol}//${host}`,
1934
2460
  pathParams: { dbName, workspace },
1935
- queryParams: { gitBranch, fallbackBranch }
2461
+ queryParams: { gitBranch, fallbackBranch },
2462
+ trace: defaultTrace
1936
2463
  });
1937
2464
  return branch;
1938
2465
  }
@@ -1940,9 +2467,13 @@ async function getDatabaseBranch(branch, options) {
1940
2467
  const databaseURL = options?.databaseURL || getDatabaseURL();
1941
2468
  const apiKey = options?.apiKey || getAPIKey();
1942
2469
  if (!databaseURL)
1943
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
2470
+ throw new Error(
2471
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2472
+ );
1944
2473
  if (!apiKey)
1945
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
2474
+ throw new Error(
2475
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2476
+ );
1946
2477
  const [protocol, , host, , database] = databaseURL.split("/");
1947
2478
  const [workspace] = host.split(".");
1948
2479
  const dbBranchName = `${database}:${branch}`;
@@ -1952,7 +2483,8 @@ async function getDatabaseBranch(branch, options) {
1952
2483
  apiUrl: databaseURL,
1953
2484
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1954
2485
  workspacesApiUrl: `${protocol}//${host}`,
1955
- pathParams: { dbBranchName, workspace }
2486
+ pathParams: { dbBranchName, workspace },
2487
+ trace: defaultTrace
1956
2488
  });
1957
2489
  } catch (err) {
1958
2490
  if (isObject(err) && err.status === 404)
@@ -1992,17 +2524,20 @@ var __privateMethod = (obj, member, method) => {
1992
2524
  return method;
1993
2525
  };
1994
2526
  const buildClient = (plugins) => {
1995
- var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
2527
+ var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1996
2528
  return _a = class {
1997
2529
  constructor(options = {}, schemaTables) {
1998
2530
  __privateAdd(this, _parseOptions);
1999
2531
  __privateAdd(this, _getFetchProps);
2000
2532
  __privateAdd(this, _evaluateBranch);
2001
2533
  __privateAdd(this, _branch, void 0);
2534
+ __privateAdd(this, _options, void 0);
2002
2535
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
2536
+ __privateSet(this, _options, safeOptions);
2003
2537
  const pluginOptions = {
2004
2538
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
2005
- cache: safeOptions.cache
2539
+ cache: safeOptions.cache,
2540
+ trace: safeOptions.trace
2006
2541
  };
2007
2542
  const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2008
2543
  const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
@@ -2021,22 +2556,26 @@ const buildClient = (plugins) => {
2021
2556
  }
2022
2557
  }
2023
2558
  }
2024
- }, _branch = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
2559
+ async getConfig() {
2560
+ const databaseURL = __privateGet(this, _options).databaseURL;
2561
+ const branch = await __privateGet(this, _options).branch();
2562
+ return { databaseURL, branch };
2563
+ }
2564
+ }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
2025
2565
  const fetch = getFetchImplementation(options?.fetch);
2026
2566
  const databaseURL = options?.databaseURL || getDatabaseURL();
2027
2567
  const apiKey = options?.apiKey || getAPIKey();
2028
- const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
2568
+ const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
2569
+ const trace = options?.trace ?? defaultTrace;
2029
2570
  const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
2030
- if (!databaseURL || !apiKey) {
2031
- throw new Error("Options databaseURL and apiKey are required");
2571
+ if (!apiKey) {
2572
+ throw new Error("Option apiKey is required");
2032
2573
  }
2033
- return { fetch, databaseURL, apiKey, branch, cache };
2034
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
2035
- fetch,
2036
- apiKey,
2037
- databaseURL,
2038
- branch
2039
- }) {
2574
+ if (!databaseURL) {
2575
+ throw new Error("Option databaseURL is required");
2576
+ }
2577
+ return { fetch, databaseURL, apiKey, branch, cache, trace };
2578
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace }) {
2040
2579
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
2041
2580
  if (!branchValue)
2042
2581
  throw new Error("Unable to resolve branch value");
@@ -2046,9 +2585,10 @@ const buildClient = (plugins) => {
2046
2585
  apiUrl: "",
2047
2586
  workspacesApiUrl: (path, params) => {
2048
2587
  const hasBranch = params.dbBranchName ?? params.branch;
2049
- const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branchValue}` : "");
2588
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branchValue}` : "");
2050
2589
  return databaseURL + newPath;
2051
- }
2590
+ },
2591
+ trace
2052
2592
  };
2053
2593
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
2054
2594
  if (__privateGet(this, _branch))
@@ -2071,6 +2611,88 @@ const buildClient = (plugins) => {
2071
2611
  class BaseClient extends buildClient() {
2072
2612
  }
2073
2613
 
2614
+ const META = "__";
2615
+ const VALUE = "___";
2616
+ class Serializer {
2617
+ constructor() {
2618
+ this.classes = {};
2619
+ }
2620
+ add(clazz) {
2621
+ this.classes[clazz.name] = clazz;
2622
+ }
2623
+ toJSON(data) {
2624
+ function visit(obj) {
2625
+ if (Array.isArray(obj))
2626
+ return obj.map(visit);
2627
+ const type = typeof obj;
2628
+ if (type === "undefined")
2629
+ return { [META]: "undefined" };
2630
+ if (type === "bigint")
2631
+ return { [META]: "bigint", [VALUE]: obj.toString() };
2632
+ if (obj === null || type !== "object")
2633
+ return obj;
2634
+ const constructor = obj.constructor;
2635
+ const o = { [META]: constructor.name };
2636
+ for (const [key, value] of Object.entries(obj)) {
2637
+ o[key] = visit(value);
2638
+ }
2639
+ if (constructor === Date)
2640
+ o[VALUE] = obj.toISOString();
2641
+ if (constructor === Map)
2642
+ o[VALUE] = Object.fromEntries(obj);
2643
+ if (constructor === Set)
2644
+ o[VALUE] = [...obj];
2645
+ return o;
2646
+ }
2647
+ return JSON.stringify(visit(data));
2648
+ }
2649
+ fromJSON(json) {
2650
+ return JSON.parse(json, (key, value) => {
2651
+ if (value && typeof value === "object" && !Array.isArray(value)) {
2652
+ const { [META]: clazz, [VALUE]: val, ...rest } = value;
2653
+ const constructor = this.classes[clazz];
2654
+ if (constructor) {
2655
+ return Object.assign(Object.create(constructor.prototype), rest);
2656
+ }
2657
+ if (clazz === "Date")
2658
+ return new Date(val);
2659
+ if (clazz === "Set")
2660
+ return new Set(val);
2661
+ if (clazz === "Map")
2662
+ return new Map(Object.entries(val));
2663
+ if (clazz === "bigint")
2664
+ return BigInt(val);
2665
+ if (clazz === "undefined")
2666
+ return void 0;
2667
+ return rest;
2668
+ }
2669
+ return value;
2670
+ });
2671
+ }
2672
+ }
2673
+ const defaultSerializer = new Serializer();
2674
+ const serialize = (data) => {
2675
+ return defaultSerializer.toJSON(data);
2676
+ };
2677
+ const deserialize = (json) => {
2678
+ return defaultSerializer.fromJSON(json);
2679
+ };
2680
+
2681
+ function buildWorkerRunner(config) {
2682
+ return function xataWorker(name, _worker) {
2683
+ return async (...args) => {
2684
+ const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
2685
+ const result = await fetch(url, {
2686
+ method: "POST",
2687
+ headers: { "Content-Type": "application/json" },
2688
+ body: serialize({ args })
2689
+ });
2690
+ const text = await result.text();
2691
+ return deserialize(text);
2692
+ };
2693
+ };
2694
+ }
2695
+
2074
2696
  class XataError extends Error {
2075
2697
  constructor(message, status) {
2076
2698
  super(message);
@@ -2091,6 +2713,7 @@ exports.Repository = Repository;
2091
2713
  exports.RestRepository = RestRepository;
2092
2714
  exports.SchemaPlugin = SchemaPlugin;
2093
2715
  exports.SearchPlugin = SearchPlugin;
2716
+ exports.Serializer = Serializer;
2094
2717
  exports.SimpleCache = SimpleCache;
2095
2718
  exports.XataApiClient = XataApiClient;
2096
2719
  exports.XataApiPlugin = XataApiPlugin;
@@ -2099,12 +2722,24 @@ exports.XataPlugin = XataPlugin;
2099
2722
  exports.acceptWorkspaceMemberInvite = acceptWorkspaceMemberInvite;
2100
2723
  exports.addGitBranchesEntry = addGitBranchesEntry;
2101
2724
  exports.addTableColumn = addTableColumn;
2725
+ exports.aggregateTable = aggregateTable;
2726
+ exports.applyBranchSchemaEdit = applyBranchSchemaEdit;
2102
2727
  exports.buildClient = buildClient;
2728
+ exports.buildWorkerRunner = buildWorkerRunner;
2103
2729
  exports.bulkInsertTableRecords = bulkInsertTableRecords;
2730
+ exports.cPCreateDatabase = cPCreateDatabase;
2731
+ exports.cPDeleteDatabase = cPDeleteDatabase;
2732
+ exports.cPGetCPDatabaseMetadata = cPGetCPDatabaseMetadata;
2733
+ exports.cPGetDatabaseList = cPGetDatabaseList;
2734
+ exports.cPUpdateCPDatabaseMetadata = cPUpdateCPDatabaseMetadata;
2104
2735
  exports.cancelWorkspaceMemberInvite = cancelWorkspaceMemberInvite;
2736
+ exports.compareBranchSchemas = compareBranchSchemas;
2737
+ exports.compareBranchWithUserSchema = compareBranchWithUserSchema;
2738
+ exports.compareMigrationRequest = compareMigrationRequest;
2105
2739
  exports.contains = contains;
2106
2740
  exports.createBranch = createBranch;
2107
2741
  exports.createDatabase = createDatabase;
2742
+ exports.createMigrationRequest = createMigrationRequest;
2108
2743
  exports.createTable = createTable;
2109
2744
  exports.createUserAPIKey = createUserAPIKey;
2110
2745
  exports.createWorkspace = createWorkspace;
@@ -2116,7 +2751,9 @@ exports.deleteTable = deleteTable;
2116
2751
  exports.deleteUser = deleteUser;
2117
2752
  exports.deleteUserAPIKey = deleteUserAPIKey;
2118
2753
  exports.deleteWorkspace = deleteWorkspace;
2754
+ exports.deserialize = deserialize;
2119
2755
  exports.endsWith = endsWith;
2756
+ exports.equals = equals;
2120
2757
  exports.executeBranchMigrationPlan = executeBranchMigrationPlan;
2121
2758
  exports.exists = exists;
2122
2759
  exports.ge = ge;
@@ -2126,13 +2763,18 @@ exports.getBranchList = getBranchList;
2126
2763
  exports.getBranchMetadata = getBranchMetadata;
2127
2764
  exports.getBranchMigrationHistory = getBranchMigrationHistory;
2128
2765
  exports.getBranchMigrationPlan = getBranchMigrationPlan;
2766
+ exports.getBranchSchemaHistory = getBranchSchemaHistory;
2129
2767
  exports.getBranchStats = getBranchStats;
2130
2768
  exports.getColumn = getColumn;
2131
2769
  exports.getCurrentBranchDetails = getCurrentBranchDetails;
2132
2770
  exports.getCurrentBranchName = getCurrentBranchName;
2133
2771
  exports.getDatabaseList = getDatabaseList;
2772
+ exports.getDatabaseMetadata = getDatabaseMetadata;
2134
2773
  exports.getDatabaseURL = getDatabaseURL;
2135
2774
  exports.getGitBranchesMapping = getGitBranchesMapping;
2775
+ exports.getHostUrl = getHostUrl;
2776
+ exports.getMigrationRequest = getMigrationRequest;
2777
+ exports.getMigrationRequestIsMerged = getMigrationRequestIsMerged;
2136
2778
  exports.getRecord = getRecord;
2137
2779
  exports.getTableColumns = getTableColumns;
2138
2780
  exports.getTableSchema = getTableSchema;
@@ -2141,6 +2783,9 @@ exports.getUserAPIKeys = getUserAPIKeys;
2141
2783
  exports.getWorkspace = getWorkspace;
2142
2784
  exports.getWorkspaceMembersList = getWorkspaceMembersList;
2143
2785
  exports.getWorkspacesList = getWorkspacesList;
2786
+ exports.greaterEquals = greaterEquals;
2787
+ exports.greaterThan = greaterThan;
2788
+ exports.greaterThanEquals = greaterThanEquals;
2144
2789
  exports.gt = gt;
2145
2790
  exports.gte = gte;
2146
2791
  exports.includes = includes;
@@ -2152,15 +2797,25 @@ exports.insertRecordWithID = insertRecordWithID;
2152
2797
  exports.inviteWorkspaceMember = inviteWorkspaceMember;
2153
2798
  exports.is = is;
2154
2799
  exports.isCursorPaginationOptions = isCursorPaginationOptions;
2800
+ exports.isHostProviderAlias = isHostProviderAlias;
2801
+ exports.isHostProviderBuilder = isHostProviderBuilder;
2155
2802
  exports.isIdentifiable = isIdentifiable;
2156
2803
  exports.isNot = isNot;
2157
2804
  exports.isXataRecord = isXataRecord;
2158
2805
  exports.le = le;
2806
+ exports.lessEquals = lessEquals;
2807
+ exports.lessThan = lessThan;
2808
+ exports.lessThanEquals = lessThanEquals;
2809
+ exports.listMigrationRequestsCommits = listMigrationRequestsCommits;
2159
2810
  exports.lt = lt;
2160
2811
  exports.lte = lte;
2812
+ exports.mergeMigrationRequest = mergeMigrationRequest;
2161
2813
  exports.notExists = notExists;
2162
2814
  exports.operationsByTag = operationsByTag;
2815
+ exports.parseProviderString = parseProviderString;
2163
2816
  exports.pattern = pattern;
2817
+ exports.previewBranchSchemaEdit = previewBranchSchemaEdit;
2818
+ exports.queryMigrationRequests = queryMigrationRequests;
2164
2819
  exports.queryTable = queryTable;
2165
2820
  exports.removeGitBranchesEntry = removeGitBranchesEntry;
2166
2821
  exports.removeWorkspaceMember = removeWorkspaceMember;
@@ -2168,14 +2823,20 @@ exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite;
2168
2823
  exports.resolveBranch = resolveBranch;
2169
2824
  exports.searchBranch = searchBranch;
2170
2825
  exports.searchTable = searchTable;
2826
+ exports.serialize = serialize;
2171
2827
  exports.setTableSchema = setTableSchema;
2172
2828
  exports.startsWith = startsWith;
2829
+ exports.summarizeTable = summarizeTable;
2173
2830
  exports.updateBranchMetadata = updateBranchMetadata;
2831
+ exports.updateBranchSchema = updateBranchSchema;
2174
2832
  exports.updateColumn = updateColumn;
2833
+ exports.updateDatabaseMetadata = updateDatabaseMetadata;
2834
+ exports.updateMigrationRequest = updateMigrationRequest;
2175
2835
  exports.updateRecordWithID = updateRecordWithID;
2176
2836
  exports.updateTable = updateTable;
2177
2837
  exports.updateUser = updateUser;
2178
2838
  exports.updateWorkspace = updateWorkspace;
2839
+ exports.updateWorkspaceMemberInvite = updateWorkspaceMemberInvite;
2179
2840
  exports.updateWorkspaceMemberRole = updateWorkspaceMemberRole;
2180
2841
  exports.upsertRecordWithID = upsertRecordWithID;
2181
2842
  //# sourceMappingURL=index.cjs.map