@xata.io/client 0.0.0-alpha.vfd6aaf3 → 0.0.0-alpha.vfda8f2e

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,3 +1,25 @@
1
+ const defaultTrace = async (_name, fn, _options) => {
2
+ return await fn({
3
+ setAttributes: () => {
4
+ return;
5
+ }
6
+ });
7
+ };
8
+ const TraceAttributes = {
9
+ KIND: "xata.trace.kind",
10
+ VERSION: "xata.sdk.version",
11
+ TABLE: "xata.table",
12
+ HTTP_REQUEST_ID: "http.request_id",
13
+ HTTP_STATUS_CODE: "http.status_code",
14
+ HTTP_HOST: "http.host",
15
+ HTTP_SCHEME: "http.scheme",
16
+ HTTP_USER_AGENT: "http.user_agent",
17
+ HTTP_METHOD: "http.method",
18
+ HTTP_URL: "http.url",
19
+ HTTP_ROUTE: "http.route",
20
+ HTTP_TARGET: "http.target"
21
+ };
22
+
1
23
  function notEmpty(value) {
2
24
  return value !== null && value !== void 0;
3
25
  }
@@ -13,6 +35,24 @@ function isDefined(value) {
13
35
  function isString(value) {
14
36
  return isDefined(value) && typeof value === "string";
15
37
  }
38
+ function isStringArray(value) {
39
+ return isDefined(value) && Array.isArray(value) && value.every(isString);
40
+ }
41
+ function isNumber(value) {
42
+ return isDefined(value) && typeof value === "number";
43
+ }
44
+ function parseNumber(value) {
45
+ if (isNumber(value)) {
46
+ return value;
47
+ }
48
+ if (isString(value)) {
49
+ const parsed = Number(value);
50
+ if (!Number.isNaN(parsed)) {
51
+ return parsed;
52
+ }
53
+ }
54
+ return void 0;
55
+ }
16
56
  function toBase64(value) {
17
57
  try {
18
58
  return btoa(value);
@@ -21,36 +61,124 @@ function toBase64(value) {
21
61
  return buf.from(value).toString("base64");
22
62
  }
23
63
  }
64
+ function deepMerge(a, b) {
65
+ const result = { ...a };
66
+ for (const [key, value] of Object.entries(b)) {
67
+ if (isObject(value) && isObject(result[key])) {
68
+ result[key] = deepMerge(result[key], value);
69
+ } else {
70
+ result[key] = value;
71
+ }
72
+ }
73
+ return result;
74
+ }
75
+ function chunk(array, chunkSize) {
76
+ const result = [];
77
+ for (let i = 0; i < array.length; i += chunkSize) {
78
+ result.push(array.slice(i, i + chunkSize));
79
+ }
80
+ return result;
81
+ }
82
+ async function timeout(ms) {
83
+ return new Promise((resolve) => setTimeout(resolve, ms));
84
+ }
24
85
 
25
- function getEnvVariable(name) {
86
+ function getEnvironment() {
87
+ try {
88
+ if (isObject(process) && isObject(process.env)) {
89
+ return {
90
+ apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
91
+ databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
92
+ branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
93
+ envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
94
+ fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
95
+ };
96
+ }
97
+ } catch (err) {
98
+ }
99
+ try {
100
+ if (isObject(Deno) && isObject(Deno.env)) {
101
+ return {
102
+ apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
103
+ databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
104
+ branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
105
+ envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
106
+ fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
107
+ };
108
+ }
109
+ } catch (err) {
110
+ }
111
+ return {
112
+ apiKey: getGlobalApiKey(),
113
+ databaseURL: getGlobalDatabaseURL(),
114
+ branch: getGlobalBranch(),
115
+ envBranch: void 0,
116
+ fallbackBranch: getGlobalFallbackBranch()
117
+ };
118
+ }
119
+ function getEnableBrowserVariable() {
26
120
  try {
27
- if (isObject(process) && isString(process?.env?.[name])) {
28
- return process.env[name];
121
+ if (isObject(process) && isObject(process.env) && process.env.XATA_ENABLE_BROWSER !== void 0) {
122
+ return process.env.XATA_ENABLE_BROWSER === "true";
29
123
  }
30
124
  } catch (err) {
31
125
  }
32
126
  try {
33
- if (isObject(Deno) && isString(Deno?.env?.get(name))) {
34
- return Deno.env.get(name);
127
+ if (isObject(Deno) && isObject(Deno.env) && Deno.env.get("XATA_ENABLE_BROWSER") !== void 0) {
128
+ return Deno.env.get("XATA_ENABLE_BROWSER") === "true";
35
129
  }
36
130
  } catch (err) {
37
131
  }
132
+ try {
133
+ return XATA_ENABLE_BROWSER === true || XATA_ENABLE_BROWSER === "true";
134
+ } catch (err) {
135
+ return void 0;
136
+ }
137
+ }
138
+ function getGlobalApiKey() {
139
+ try {
140
+ return XATA_API_KEY;
141
+ } catch (err) {
142
+ return void 0;
143
+ }
144
+ }
145
+ function getGlobalDatabaseURL() {
146
+ try {
147
+ return XATA_DATABASE_URL;
148
+ } catch (err) {
149
+ return void 0;
150
+ }
151
+ }
152
+ function getGlobalBranch() {
153
+ try {
154
+ return XATA_BRANCH;
155
+ } catch (err) {
156
+ return void 0;
157
+ }
158
+ }
159
+ function getGlobalFallbackBranch() {
160
+ try {
161
+ return XATA_FALLBACK_BRANCH;
162
+ } catch (err) {
163
+ return void 0;
164
+ }
38
165
  }
39
166
  async function getGitBranch() {
167
+ const cmd = ["git", "branch", "--show-current"];
168
+ const fullCmd = cmd.join(" ");
169
+ const nodeModule = ["child", "process"].join("_");
170
+ const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
40
171
  try {
41
172
  if (typeof require === "function") {
42
- const req = require;
43
- return req("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
173
+ return require(nodeModule).execSync(fullCmd, execOptions).trim();
44
174
  }
175
+ const { execSync } = await import(nodeModule);
176
+ return execSync(fullCmd, execOptions).toString().trim();
45
177
  } catch (err) {
46
178
  }
47
179
  try {
48
180
  if (isObject(Deno)) {
49
- const process2 = Deno.run({
50
- cmd: ["git", "branch", "--show-current"],
51
- stdout: "piped",
52
- stderr: "piped"
53
- });
181
+ const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
54
182
  return new TextDecoder().decode(await process2.output()).trim();
55
183
  }
56
184
  } catch (err) {
@@ -59,22 +187,110 @@ async function getGitBranch() {
59
187
 
60
188
  function getAPIKey() {
61
189
  try {
62
- return getEnvVariable("XATA_API_KEY") ?? XATA_API_KEY;
190
+ const { apiKey } = getEnvironment();
191
+ return apiKey;
63
192
  } catch (err) {
64
193
  return void 0;
65
194
  }
66
195
  }
67
196
 
197
+ var __accessCheck$8 = (obj, member, msg) => {
198
+ if (!member.has(obj))
199
+ throw TypeError("Cannot " + msg);
200
+ };
201
+ var __privateGet$8 = (obj, member, getter) => {
202
+ __accessCheck$8(obj, member, "read from private field");
203
+ return getter ? getter.call(obj) : member.get(obj);
204
+ };
205
+ var __privateAdd$8 = (obj, member, value) => {
206
+ if (member.has(obj))
207
+ throw TypeError("Cannot add the same private member more than once");
208
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
209
+ };
210
+ var __privateSet$8 = (obj, member, value, setter) => {
211
+ __accessCheck$8(obj, member, "write to private field");
212
+ setter ? setter.call(obj, value) : member.set(obj, value);
213
+ return value;
214
+ };
215
+ var __privateMethod$4 = (obj, member, method) => {
216
+ __accessCheck$8(obj, member, "access private method");
217
+ return method;
218
+ };
219
+ var _fetch, _queue, _concurrency, _enqueue, enqueue_fn;
68
220
  function getFetchImplementation(userFetch) {
69
221
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
70
222
  const fetchImpl = userFetch ?? globalFetch;
71
223
  if (!fetchImpl) {
72
- throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
224
+ throw new Error(
225
+ `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
226
+ );
73
227
  }
74
228
  return fetchImpl;
75
229
  }
230
+ class ApiRequestPool {
231
+ constructor(concurrency = 10) {
232
+ __privateAdd$8(this, _enqueue);
233
+ __privateAdd$8(this, _fetch, void 0);
234
+ __privateAdd$8(this, _queue, void 0);
235
+ __privateAdd$8(this, _concurrency, void 0);
236
+ __privateSet$8(this, _queue, []);
237
+ __privateSet$8(this, _concurrency, concurrency);
238
+ this.running = 0;
239
+ this.started = 0;
240
+ }
241
+ setFetch(fetch2) {
242
+ __privateSet$8(this, _fetch, fetch2);
243
+ }
244
+ getFetch() {
245
+ if (!__privateGet$8(this, _fetch)) {
246
+ throw new Error("Fetch not set");
247
+ }
248
+ return __privateGet$8(this, _fetch);
249
+ }
250
+ request(url, options, context = { start: new Date(), stalled: false }) {
251
+ const fetch2 = this.getFetch();
252
+ return __privateMethod$4(this, _enqueue, enqueue_fn).call(this, async () => {
253
+ const response = await fetch2(url, options);
254
+ if (response.status === 429) {
255
+ const rateLimitReset = parseNumber(response.headers?.get("x-ratelimit-reset")) ?? 1;
256
+ await timeout(rateLimitReset * 1e3);
257
+ return await this.request(url, options, { ...context, stalled: true });
258
+ }
259
+ if (context.stalled) {
260
+ const stalledTime = new Date().getTime() - context.start.getTime();
261
+ console.warn(`A request to Xata hit your workspace limits, was retried and stalled for ${stalledTime}ms`);
262
+ }
263
+ return response;
264
+ });
265
+ }
266
+ }
267
+ _fetch = new WeakMap();
268
+ _queue = new WeakMap();
269
+ _concurrency = new WeakMap();
270
+ _enqueue = new WeakSet();
271
+ enqueue_fn = function(task) {
272
+ const promise = new Promise((resolve) => __privateGet$8(this, _queue).push(resolve)).finally(() => {
273
+ this.started--;
274
+ this.running++;
275
+ }).then(() => task()).finally(() => {
276
+ this.running--;
277
+ const next = __privateGet$8(this, _queue).shift();
278
+ if (next !== void 0) {
279
+ this.started++;
280
+ next();
281
+ }
282
+ });
283
+ if (this.running + this.started < __privateGet$8(this, _concurrency)) {
284
+ const next = __privateGet$8(this, _queue).shift();
285
+ if (next !== void 0) {
286
+ this.started++;
287
+ next();
288
+ }
289
+ }
290
+ return promise;
291
+ };
76
292
 
77
- const VERSION = "0.0.0-alpha.vfd6aaf3";
293
+ const VERSION = "0.0.0-alpha.vfda8f2e";
78
294
 
79
295
  class ErrorWithCause extends Error {
80
296
  constructor(message, options) {
@@ -117,6 +333,7 @@ function getMessage(data) {
117
333
  }
118
334
  }
119
335
 
336
+ const pool = new ApiRequestPool();
120
337
  const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
121
338
  const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
122
339
  if (value === void 0 || value === null)
@@ -125,18 +342,24 @@ const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
125
342
  }, {});
126
343
  const query = new URLSearchParams(cleanQueryParams).toString();
127
344
  const queryString = query.length > 0 ? `?${query}` : "";
128
- return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
345
+ const cleanPathParams = Object.entries(pathParams).reduce((acc, [key, value]) => {
346
+ return { ...acc, [key]: encodeURIComponent(String(value ?? "")).replace("%3A", ":") };
347
+ }, {});
348
+ return url.replace(/\{\w*\}/g, (key) => cleanPathParams[key.slice(1, -1)]) + queryString;
129
349
  };
130
350
  function buildBaseUrl({
351
+ endpoint,
131
352
  path,
132
353
  workspacesApiUrl,
133
354
  apiUrl,
134
- pathParams
355
+ pathParams = {}
135
356
  }) {
136
- if (!pathParams?.workspace)
137
- return `${apiUrl}${path}`;
138
- const url = typeof workspacesApiUrl === "string" ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
139
- return url.replace("{workspaceId}", pathParams.workspace);
357
+ if (endpoint === "dataPlane") {
358
+ const url = isString(workspacesApiUrl) ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
359
+ const urlWithWorkspace = isString(pathParams.workspace) ? url.replace("{workspaceId}", String(pathParams.workspace)) : url;
360
+ return isString(pathParams.region) ? urlWithWorkspace.replace("{region}", String(pathParams.region)) : urlWithWorkspace;
361
+ }
362
+ return `${apiUrl}${path}`;
140
363
  }
141
364
  function hostHeader(url) {
142
365
  const pattern = /.*:\/\/(?<host>[^/]+).*/;
@@ -152,277 +375,235 @@ async function fetch$1({
152
375
  queryParams,
153
376
  fetchImpl,
154
377
  apiKey,
378
+ endpoint,
155
379
  apiUrl,
156
- workspacesApiUrl
380
+ workspacesApiUrl,
381
+ trace,
382
+ signal,
383
+ clientID,
384
+ sessionID,
385
+ fetchOptions = {}
157
386
  }) {
158
- const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
159
- const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
160
- const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
161
- const response = await fetchImpl(url, {
162
- method: method.toUpperCase(),
163
- body: body ? JSON.stringify(body) : void 0,
164
- headers: {
165
- "Content-Type": "application/json",
166
- "User-Agent": `Xata client-ts/${VERSION}`,
167
- ...headers,
168
- ...hostHeader(fullUrl),
169
- Authorization: `Bearer ${apiKey}`
170
- }
171
- });
172
- if (response.status === 204) {
173
- return {};
174
- }
175
- const requestId = response.headers?.get("x-request-id") ?? void 0;
387
+ pool.setFetch(fetchImpl);
388
+ return await trace(
389
+ `${method.toUpperCase()} ${path}`,
390
+ async ({ setAttributes }) => {
391
+ const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
392
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
393
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
394
+ setAttributes({
395
+ [TraceAttributes.HTTP_URL]: url,
396
+ [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
397
+ });
398
+ const response = await pool.request(url, {
399
+ ...fetchOptions,
400
+ method: method.toUpperCase(),
401
+ body: body ? JSON.stringify(body) : void 0,
402
+ headers: {
403
+ "Content-Type": "application/json",
404
+ "User-Agent": `Xata client-ts/${VERSION}`,
405
+ "X-Xata-Client-ID": clientID ?? "",
406
+ "X-Xata-Session-ID": sessionID ?? "",
407
+ ...headers,
408
+ ...hostHeader(fullUrl),
409
+ Authorization: `Bearer ${apiKey}`
410
+ },
411
+ signal
412
+ });
413
+ const { host, protocol } = parseUrl(response.url);
414
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
415
+ setAttributes({
416
+ [TraceAttributes.KIND]: "http",
417
+ [TraceAttributes.HTTP_REQUEST_ID]: requestId,
418
+ [TraceAttributes.HTTP_STATUS_CODE]: response.status,
419
+ [TraceAttributes.HTTP_HOST]: host,
420
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
421
+ });
422
+ if (response.status === 204) {
423
+ return {};
424
+ }
425
+ if (response.status === 429) {
426
+ throw new FetcherError(response.status, "Rate limit exceeded", requestId);
427
+ }
428
+ try {
429
+ const jsonResponse = await response.json();
430
+ if (response.ok) {
431
+ return jsonResponse;
432
+ }
433
+ throw new FetcherError(response.status, jsonResponse, requestId);
434
+ } catch (error) {
435
+ throw new FetcherError(response.status, error, requestId);
436
+ }
437
+ },
438
+ { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
439
+ );
440
+ }
441
+ function parseUrl(url) {
176
442
  try {
177
- const jsonResponse = await response.json();
178
- if (response.ok) {
179
- return jsonResponse;
180
- }
181
- throw new FetcherError(response.status, jsonResponse, requestId);
443
+ const { host, protocol } = new URL(url);
444
+ return { host, protocol };
182
445
  } catch (error) {
183
- throw new FetcherError(response.status, error, requestId);
446
+ return {};
184
447
  }
185
448
  }
186
449
 
187
- const getUser = (variables) => fetch$1({ url: "/user", method: "get", ...variables });
188
- const updateUser = (variables) => fetch$1({ url: "/user", method: "put", ...variables });
189
- const deleteUser = (variables) => fetch$1({ url: "/user", method: "delete", ...variables });
190
- const getUserAPIKeys = (variables) => fetch$1({
191
- url: "/user/keys",
192
- method: "get",
193
- ...variables
194
- });
195
- const createUserAPIKey = (variables) => fetch$1({
196
- url: "/user/keys/{keyName}",
197
- method: "post",
198
- ...variables
199
- });
200
- const deleteUserAPIKey = (variables) => fetch$1({
201
- url: "/user/keys/{keyName}",
202
- method: "delete",
203
- ...variables
204
- });
205
- const createWorkspace = (variables) => fetch$1({
206
- url: "/workspaces",
207
- method: "post",
208
- ...variables
209
- });
210
- const getWorkspacesList = (variables) => fetch$1({
211
- url: "/workspaces",
212
- method: "get",
213
- ...variables
214
- });
215
- const getWorkspace = (variables) => fetch$1({
216
- url: "/workspaces/{workspaceId}",
217
- method: "get",
218
- ...variables
219
- });
220
- const updateWorkspace = (variables) => fetch$1({
221
- url: "/workspaces/{workspaceId}",
222
- method: "put",
223
- ...variables
224
- });
225
- const deleteWorkspace = (variables) => fetch$1({
226
- url: "/workspaces/{workspaceId}",
227
- method: "delete",
228
- ...variables
229
- });
230
- const getWorkspaceMembersList = (variables) => fetch$1({
231
- url: "/workspaces/{workspaceId}/members",
232
- method: "get",
233
- ...variables
234
- });
235
- const updateWorkspaceMemberRole = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/members/{userId}", method: "put", ...variables });
236
- const removeWorkspaceMember = (variables) => fetch$1({
237
- url: "/workspaces/{workspaceId}/members/{userId}",
238
- method: "delete",
239
- ...variables
240
- });
241
- const inviteWorkspaceMember = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables });
242
- const cancelWorkspaceMemberInvite = (variables) => fetch$1({
243
- url: "/workspaces/{workspaceId}/invites/{inviteId}",
244
- method: "delete",
245
- ...variables
246
- });
247
- const resendWorkspaceMemberInvite = (variables) => fetch$1({
248
- url: "/workspaces/{workspaceId}/invites/{inviteId}/resend",
249
- method: "post",
250
- ...variables
251
- });
252
- const acceptWorkspaceMemberInvite = (variables) => fetch$1({
253
- url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept",
254
- method: "post",
255
- ...variables
256
- });
257
- const getDatabaseList = (variables) => fetch$1({
258
- url: "/dbs",
259
- method: "get",
260
- ...variables
261
- });
262
- const getBranchList = (variables) => fetch$1({
263
- url: "/dbs/{dbName}",
264
- method: "get",
265
- ...variables
266
- });
267
- const createDatabase = (variables) => fetch$1({
268
- url: "/dbs/{dbName}",
269
- method: "put",
270
- ...variables
271
- });
272
- const deleteDatabase = (variables) => fetch$1({
450
+ const dataPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "dataPlane" });
451
+
452
+ const dEPRECATEDgetDatabaseList = (variables, signal) => dataPlaneFetch({ url: "/dbs", method: "get", ...variables, signal });
453
+ const getBranchList = (variables, signal) => dataPlaneFetch({
273
454
  url: "/dbs/{dbName}",
274
- method: "delete",
275
- ...variables
276
- });
277
- const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
278
- const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
279
- const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
280
- const resolveBranch = (variables) => fetch$1({
281
- url: "/dbs/{dbName}/resolveBranch",
282
455
  method: "get",
283
- ...variables
456
+ ...variables,
457
+ signal
284
458
  });
285
- const getBranchDetails = (variables) => fetch$1({
459
+ const dEPRECATEDcreateDatabase = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}", method: "put", ...variables, signal });
460
+ const dEPRECATEDdeleteDatabase = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}", method: "delete", ...variables, signal });
461
+ const dEPRECATEDgetDatabaseMetadata = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/metadata", method: "get", ...variables, signal });
462
+ const dEPRECATEDupdateDatabaseMetadata = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/metadata", method: "patch", ...variables, signal });
463
+ const getBranchDetails = (variables, signal) => dataPlaneFetch({
286
464
  url: "/db/{dbBranchName}",
287
465
  method: "get",
288
- ...variables
466
+ ...variables,
467
+ signal
289
468
  });
290
- const createBranch = (variables) => fetch$1({
291
- url: "/db/{dbBranchName}",
292
- method: "put",
293
- ...variables
294
- });
295
- const deleteBranch = (variables) => fetch$1({
469
+ const createBranch = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}", method: "put", ...variables, signal });
470
+ const deleteBranch = (variables, signal) => dataPlaneFetch({
296
471
  url: "/db/{dbBranchName}",
297
472
  method: "delete",
298
- ...variables
473
+ ...variables,
474
+ signal
299
475
  });
300
- const updateBranchMetadata = (variables) => fetch$1({
476
+ const updateBranchMetadata = (variables, signal) => dataPlaneFetch({
301
477
  url: "/db/{dbBranchName}/metadata",
302
478
  method: "put",
303
- ...variables
479
+ ...variables,
480
+ signal
304
481
  });
305
- const getBranchMetadata = (variables) => fetch$1({
482
+ const getBranchMetadata = (variables, signal) => dataPlaneFetch({
306
483
  url: "/db/{dbBranchName}/metadata",
307
484
  method: "get",
308
- ...variables
485
+ ...variables,
486
+ signal
309
487
  });
310
- const getBranchMigrationHistory = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables });
311
- const executeBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables });
312
- const getBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables });
313
- const getBranchStats = (variables) => fetch$1({
488
+ const getBranchStats = (variables, signal) => dataPlaneFetch({
314
489
  url: "/db/{dbBranchName}/stats",
315
490
  method: "get",
316
- ...variables
491
+ ...variables,
492
+ signal
493
+ });
494
+ const getGitBranchesMapping = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables, signal });
495
+ const addGitBranchesEntry = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables, signal });
496
+ const removeGitBranchesEntry = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables, signal });
497
+ const resolveBranch = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/resolveBranch", method: "get", ...variables, signal });
498
+ const getBranchMigrationHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables, signal });
499
+ const getBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables, signal });
500
+ const executeBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables, signal });
501
+ const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
502
+ const queryMigrationRequests = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/query", method: "post", ...variables, signal });
503
+ const createMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations", method: "post", ...variables, signal });
504
+ const getMigrationRequest = (variables, signal) => dataPlaneFetch({
505
+ url: "/dbs/{dbName}/migrations/{mrNumber}",
506
+ method: "get",
507
+ ...variables,
508
+ signal
317
509
  });
318
- const createTable = (variables) => fetch$1({
510
+ const updateMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/{mrNumber}", method: "patch", ...variables, signal });
511
+ const listMigrationRequestsCommits = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/{mrNumber}/commits", method: "post", ...variables, signal });
512
+ const compareMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/{mrNumber}/compare", method: "post", ...variables, signal });
513
+ const getMigrationRequestIsMerged = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/{mrNumber}/merge", method: "get", ...variables, signal });
514
+ const mergeMigrationRequest = (variables, signal) => dataPlaneFetch({
515
+ url: "/dbs/{dbName}/migrations/{mrNumber}/merge",
516
+ method: "post",
517
+ ...variables,
518
+ signal
519
+ });
520
+ const getBranchSchemaHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/history", method: "post", ...variables, signal });
521
+ const compareBranchWithUserSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/compare", method: "post", ...variables, signal });
522
+ const compareBranchSchemas = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/compare/{branchName}", method: "post", ...variables, signal });
523
+ const updateBranchSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/update", method: "post", ...variables, signal });
524
+ const previewBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables, signal });
525
+ const applyBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables, signal });
526
+ const createTable = (variables, signal) => dataPlaneFetch({
319
527
  url: "/db/{dbBranchName}/tables/{tableName}",
320
528
  method: "put",
321
- ...variables
529
+ ...variables,
530
+ signal
322
531
  });
323
- const deleteTable = (variables) => fetch$1({
532
+ const deleteTable = (variables, signal) => dataPlaneFetch({
324
533
  url: "/db/{dbBranchName}/tables/{tableName}",
325
534
  method: "delete",
326
- ...variables
327
- });
328
- const updateTable = (variables) => fetch$1({
329
- url: "/db/{dbBranchName}/tables/{tableName}",
330
- method: "patch",
331
- ...variables
535
+ ...variables,
536
+ signal
332
537
  });
333
- const getTableSchema = (variables) => fetch$1({
538
+ const updateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}", method: "patch", ...variables, signal });
539
+ const getTableSchema = (variables, signal) => dataPlaneFetch({
334
540
  url: "/db/{dbBranchName}/tables/{tableName}/schema",
335
541
  method: "get",
336
- ...variables
542
+ ...variables,
543
+ signal
337
544
  });
338
- const setTableSchema = (variables) => fetch$1({
339
- url: "/db/{dbBranchName}/tables/{tableName}/schema",
340
- method: "put",
341
- ...variables
342
- });
343
- const getTableColumns = (variables) => fetch$1({
545
+ const setTableSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/schema", method: "put", ...variables, signal });
546
+ const getTableColumns = (variables, signal) => dataPlaneFetch({
344
547
  url: "/db/{dbBranchName}/tables/{tableName}/columns",
345
548
  method: "get",
346
- ...variables
549
+ ...variables,
550
+ signal
347
551
  });
348
- const addTableColumn = (variables) => fetch$1({
349
- url: "/db/{dbBranchName}/tables/{tableName}/columns",
350
- method: "post",
351
- ...variables
352
- });
353
- const getColumn = (variables) => fetch$1({
552
+ const addTableColumn = (variables, signal) => dataPlaneFetch(
553
+ { url: "/db/{dbBranchName}/tables/{tableName}/columns", method: "post", ...variables, signal }
554
+ );
555
+ const getColumn = (variables, signal) => dataPlaneFetch({
354
556
  url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
355
557
  method: "get",
356
- ...variables
558
+ ...variables,
559
+ signal
357
560
  });
358
- const deleteColumn = (variables) => fetch$1({
561
+ const updateColumn = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}", method: "patch", ...variables, signal });
562
+ const deleteColumn = (variables, signal) => dataPlaneFetch({
359
563
  url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
360
564
  method: "delete",
361
- ...variables
565
+ ...variables,
566
+ signal
362
567
  });
363
- const updateColumn = (variables) => fetch$1({
364
- url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
365
- method: "patch",
366
- ...variables
367
- });
368
- const insertRecord = (variables) => fetch$1({
369
- url: "/db/{dbBranchName}/tables/{tableName}/data",
370
- method: "post",
371
- ...variables
372
- });
373
- const insertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables });
374
- const updateRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables });
375
- const upsertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables });
376
- const deleteRecord = (variables) => fetch$1({
377
- url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
378
- method: "delete",
379
- ...variables
380
- });
381
- const getRecord = (variables) => fetch$1({
568
+ const insertRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
569
+ const getRecord = (variables, signal) => dataPlaneFetch({
382
570
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
383
571
  method: "get",
384
- ...variables
572
+ ...variables,
573
+ signal
385
574
  });
386
- const bulkInsertTableRecords = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/bulk", method: "post", ...variables });
387
- const queryTable = (variables) => fetch$1({
575
+ const insertRecordWithID = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables, signal });
576
+ const updateRecordWithID = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables, signal });
577
+ const upsertRecordWithID = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables, signal });
578
+ const deleteRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "delete", ...variables, signal });
579
+ const bulkInsertTableRecords = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/bulk", method: "post", ...variables, signal });
580
+ const queryTable = (variables, signal) => dataPlaneFetch({
388
581
  url: "/db/{dbBranchName}/tables/{tableName}/query",
389
582
  method: "post",
390
- ...variables
583
+ ...variables,
584
+ signal
391
585
  });
392
- const searchTable = (variables) => fetch$1({
393
- url: "/db/{dbBranchName}/tables/{tableName}/search",
586
+ const searchBranch = (variables, signal) => dataPlaneFetch({
587
+ url: "/db/{dbBranchName}/search",
394
588
  method: "post",
395
- ...variables
589
+ ...variables,
590
+ signal
396
591
  });
397
- const searchBranch = (variables) => fetch$1({
398
- url: "/db/{dbBranchName}/search",
592
+ const searchTable = (variables, signal) => dataPlaneFetch({
593
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
399
594
  method: "post",
400
- ...variables
595
+ ...variables,
596
+ signal
401
597
  });
402
- const operationsByTag = {
403
- users: { getUser, updateUser, deleteUser, getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
404
- workspaces: {
405
- createWorkspace,
406
- getWorkspacesList,
407
- getWorkspace,
408
- updateWorkspace,
409
- deleteWorkspace,
410
- getWorkspaceMembersList,
411
- updateWorkspaceMemberRole,
412
- removeWorkspaceMember,
413
- inviteWorkspaceMember,
414
- cancelWorkspaceMemberInvite,
415
- resendWorkspaceMemberInvite,
416
- acceptWorkspaceMemberInvite
417
- },
598
+ const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
599
+ const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
600
+ const operationsByTag$2 = {
418
601
  database: {
419
- getDatabaseList,
420
- createDatabase,
421
- deleteDatabase,
422
- getGitBranchesMapping,
423
- addGitBranchesEntry,
424
- removeGitBranchesEntry,
425
- resolveBranch
602
+ dEPRECATEDgetDatabaseList,
603
+ dEPRECATEDcreateDatabase,
604
+ dEPRECATEDdeleteDatabase,
605
+ dEPRECATEDgetDatabaseMetadata,
606
+ dEPRECATEDupdateDatabaseMetadata
426
607
  },
427
608
  branch: {
428
609
  getBranchList,
@@ -431,10 +612,42 @@ const operationsByTag = {
431
612
  deleteBranch,
432
613
  updateBranchMetadata,
433
614
  getBranchMetadata,
615
+ getBranchStats,
616
+ getGitBranchesMapping,
617
+ addGitBranchesEntry,
618
+ removeGitBranchesEntry,
619
+ resolveBranch
620
+ },
621
+ migrations: {
434
622
  getBranchMigrationHistory,
435
- executeBranchMigrationPlan,
436
623
  getBranchMigrationPlan,
437
- getBranchStats
624
+ executeBranchMigrationPlan,
625
+ getBranchSchemaHistory,
626
+ compareBranchWithUserSchema,
627
+ compareBranchSchemas,
628
+ updateBranchSchema,
629
+ previewBranchSchemaEdit,
630
+ applyBranchSchemaEdit
631
+ },
632
+ records: {
633
+ branchTransaction,
634
+ insertRecord,
635
+ getRecord,
636
+ insertRecordWithID,
637
+ updateRecordWithID,
638
+ upsertRecordWithID,
639
+ deleteRecord,
640
+ bulkInsertTableRecords
641
+ },
642
+ migrationRequests: {
643
+ queryMigrationRequests,
644
+ createMigrationRequest,
645
+ getMigrationRequest,
646
+ updateMigrationRequest,
647
+ listMigrationRequestsCommits,
648
+ compareMigrationRequest,
649
+ getMigrationRequestIsMerged,
650
+ mergeMigrationRequest
438
651
  },
439
652
  table: {
440
653
  createTable,
@@ -445,27 +658,150 @@ const operationsByTag = {
445
658
  getTableColumns,
446
659
  addTableColumn,
447
660
  getColumn,
448
- deleteColumn,
449
- updateColumn
661
+ updateColumn,
662
+ deleteColumn
450
663
  },
451
- records: {
452
- insertRecord,
453
- insertRecordWithID,
454
- updateRecordWithID,
455
- upsertRecordWithID,
456
- deleteRecord,
457
- getRecord,
458
- bulkInsertTableRecords,
459
- queryTable,
460
- searchTable,
461
- searchBranch
664
+ searchAndFilter: { queryTable, searchBranch, searchTable, summarizeTable, aggregateTable }
665
+ };
666
+
667
+ const controlPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "controlPlane" });
668
+
669
+ const getUser = (variables, signal) => controlPlaneFetch({
670
+ url: "/user",
671
+ method: "get",
672
+ ...variables,
673
+ signal
674
+ });
675
+ const updateUser = (variables, signal) => controlPlaneFetch({
676
+ url: "/user",
677
+ method: "put",
678
+ ...variables,
679
+ signal
680
+ });
681
+ const deleteUser = (variables, signal) => controlPlaneFetch({
682
+ url: "/user",
683
+ method: "delete",
684
+ ...variables,
685
+ signal
686
+ });
687
+ const getUserAPIKeys = (variables, signal) => controlPlaneFetch({
688
+ url: "/user/keys",
689
+ method: "get",
690
+ ...variables,
691
+ signal
692
+ });
693
+ const createUserAPIKey = (variables, signal) => controlPlaneFetch({
694
+ url: "/user/keys/{keyName}",
695
+ method: "post",
696
+ ...variables,
697
+ signal
698
+ });
699
+ const deleteUserAPIKey = (variables, signal) => controlPlaneFetch({
700
+ url: "/user/keys/{keyName}",
701
+ method: "delete",
702
+ ...variables,
703
+ signal
704
+ });
705
+ const getWorkspacesList = (variables, signal) => controlPlaneFetch({
706
+ url: "/workspaces",
707
+ method: "get",
708
+ ...variables,
709
+ signal
710
+ });
711
+ const createWorkspace = (variables, signal) => controlPlaneFetch({
712
+ url: "/workspaces",
713
+ method: "post",
714
+ ...variables,
715
+ signal
716
+ });
717
+ const getWorkspace = (variables, signal) => controlPlaneFetch({
718
+ url: "/workspaces/{workspaceId}",
719
+ method: "get",
720
+ ...variables,
721
+ signal
722
+ });
723
+ const updateWorkspace = (variables, signal) => controlPlaneFetch({
724
+ url: "/workspaces/{workspaceId}",
725
+ method: "put",
726
+ ...variables,
727
+ signal
728
+ });
729
+ const deleteWorkspace = (variables, signal) => controlPlaneFetch({
730
+ url: "/workspaces/{workspaceId}",
731
+ method: "delete",
732
+ ...variables,
733
+ signal
734
+ });
735
+ const getWorkspaceMembersList = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/members", method: "get", ...variables, signal });
736
+ const updateWorkspaceMemberRole = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/members/{userId}", method: "put", ...variables, signal });
737
+ const removeWorkspaceMember = (variables, signal) => controlPlaneFetch({
738
+ url: "/workspaces/{workspaceId}/members/{userId}",
739
+ method: "delete",
740
+ ...variables,
741
+ signal
742
+ });
743
+ const inviteWorkspaceMember = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables, signal });
744
+ const updateWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables, signal });
745
+ const cancelWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "delete", ...variables, signal });
746
+ const acceptWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept", method: "post", ...variables, signal });
747
+ const resendWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}/resend", method: "post", ...variables, signal });
748
+ const getDatabaseList = (variables, signal) => controlPlaneFetch({
749
+ url: "/workspaces/{workspaceId}/dbs",
750
+ method: "get",
751
+ ...variables,
752
+ signal
753
+ });
754
+ const createDatabase = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "put", ...variables, signal });
755
+ const deleteDatabase = (variables, signal) => controlPlaneFetch({
756
+ url: "/workspaces/{workspaceId}/dbs/{dbName}",
757
+ method: "delete",
758
+ ...variables,
759
+ signal
760
+ });
761
+ const getDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "get", ...variables, signal });
762
+ const updateDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "patch", ...variables, signal });
763
+ const listRegions = (variables, signal) => controlPlaneFetch({
764
+ url: "/workspaces/{workspaceId}/regions",
765
+ method: "get",
766
+ ...variables,
767
+ signal
768
+ });
769
+ const operationsByTag$1 = {
770
+ users: { getUser, updateUser, deleteUser },
771
+ authentication: { getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
772
+ workspaces: {
773
+ getWorkspacesList,
774
+ createWorkspace,
775
+ getWorkspace,
776
+ updateWorkspace,
777
+ deleteWorkspace,
778
+ getWorkspaceMembersList,
779
+ updateWorkspaceMemberRole,
780
+ removeWorkspaceMember
781
+ },
782
+ invites: {
783
+ inviteWorkspaceMember,
784
+ updateWorkspaceMemberInvite,
785
+ cancelWorkspaceMemberInvite,
786
+ acceptWorkspaceMemberInvite,
787
+ resendWorkspaceMemberInvite
788
+ },
789
+ databases: {
790
+ getDatabaseList,
791
+ createDatabase,
792
+ deleteDatabase,
793
+ getDatabaseMetadata,
794
+ updateDatabaseMetadata,
795
+ listRegions
462
796
  }
463
797
  };
464
798
 
799
+ const operationsByTag = deepMerge(operationsByTag$2, operationsByTag$1);
800
+
465
801
  function getHostUrl(provider, type) {
466
- if (isValidAlias(provider)) {
802
+ if (isHostProviderAlias(provider)) {
467
803
  return providers[provider][type];
468
- } else if (isValidBuilder(provider)) {
804
+ } else if (isHostProviderBuilder(provider)) {
469
805
  return provider[type];
470
806
  }
471
807
  throw new Error("Invalid API provider");
@@ -473,19 +809,38 @@ function getHostUrl(provider, type) {
473
809
  const providers = {
474
810
  production: {
475
811
  main: "https://api.xata.io",
476
- workspaces: "https://{workspaceId}.xata.sh"
812
+ workspaces: "https://{workspaceId}.{region}.xata.sh"
477
813
  },
478
814
  staging: {
479
815
  main: "https://staging.xatabase.co",
480
- workspaces: "https://{workspaceId}.staging.xatabase.co"
816
+ workspaces: "https://{workspaceId}.staging.{region}.xatabase.co"
481
817
  }
482
818
  };
483
- function isValidAlias(alias) {
819
+ function isHostProviderAlias(alias) {
484
820
  return isString(alias) && Object.keys(providers).includes(alias);
485
821
  }
486
- function isValidBuilder(builder) {
822
+ function isHostProviderBuilder(builder) {
487
823
  return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
488
824
  }
825
+ function parseProviderString(provider = "production") {
826
+ if (isHostProviderAlias(provider)) {
827
+ return provider;
828
+ }
829
+ const [main, workspaces] = provider.split(",");
830
+ if (!main || !workspaces)
831
+ return null;
832
+ return { main, workspaces };
833
+ }
834
+ function parseWorkspacesUrlParts(url) {
835
+ if (!isString(url))
836
+ return null;
837
+ const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))?\.xata\.sh.*/;
838
+ const regexStaging = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))?\.xatabase\.co.*/;
839
+ const match = url.match(regex) || url.match(regexStaging);
840
+ if (!match)
841
+ return null;
842
+ return { workspace: match[1], region: match[2] ?? "eu-west-1" };
843
+ }
489
844
 
490
845
  var __accessCheck$7 = (obj, member, msg) => {
491
846
  if (!member.has(obj))
@@ -500,7 +855,7 @@ var __privateAdd$7 = (obj, member, value) => {
500
855
  throw TypeError("Cannot add the same private member more than once");
501
856
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
502
857
  };
503
- var __privateSet$6 = (obj, member, value, setter) => {
858
+ var __privateSet$7 = (obj, member, value, setter) => {
504
859
  __accessCheck$7(obj, member, "write to private field");
505
860
  setter ? setter.call(obj, value) : member.set(obj, value);
506
861
  return value;
@@ -511,15 +866,17 @@ class XataApiClient {
511
866
  __privateAdd$7(this, _extraProps, void 0);
512
867
  __privateAdd$7(this, _namespaces, {});
513
868
  const provider = options.host ?? "production";
514
- const apiKey = options?.apiKey ?? getAPIKey();
869
+ const apiKey = options.apiKey ?? getAPIKey();
870
+ const trace = options.trace ?? defaultTrace;
515
871
  if (!apiKey) {
516
872
  throw new Error("Could not resolve a valid apiKey");
517
873
  }
518
- __privateSet$6(this, _extraProps, {
874
+ __privateSet$7(this, _extraProps, {
519
875
  apiUrl: getHostUrl(provider, "main"),
520
876
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
521
877
  fetchImpl: getFetchImplementation(options.fetch),
522
- apiKey
878
+ apiKey,
879
+ trace
523
880
  });
524
881
  }
525
882
  get user() {
@@ -527,21 +884,41 @@ class XataApiClient {
527
884
  __privateGet$7(this, _namespaces).user = new UserApi(__privateGet$7(this, _extraProps));
528
885
  return __privateGet$7(this, _namespaces).user;
529
886
  }
887
+ get authentication() {
888
+ if (!__privateGet$7(this, _namespaces).authentication)
889
+ __privateGet$7(this, _namespaces).authentication = new AuthenticationApi(__privateGet$7(this, _extraProps));
890
+ return __privateGet$7(this, _namespaces).authentication;
891
+ }
530
892
  get workspaces() {
531
893
  if (!__privateGet$7(this, _namespaces).workspaces)
532
894
  __privateGet$7(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$7(this, _extraProps));
533
895
  return __privateGet$7(this, _namespaces).workspaces;
534
896
  }
535
- get databases() {
536
- if (!__privateGet$7(this, _namespaces).databases)
537
- __privateGet$7(this, _namespaces).databases = new DatabaseApi(__privateGet$7(this, _extraProps));
538
- return __privateGet$7(this, _namespaces).databases;
897
+ get invites() {
898
+ if (!__privateGet$7(this, _namespaces).invites)
899
+ __privateGet$7(this, _namespaces).invites = new InvitesApi(__privateGet$7(this, _extraProps));
900
+ return __privateGet$7(this, _namespaces).invites;
901
+ }
902
+ get database() {
903
+ if (!__privateGet$7(this, _namespaces).database)
904
+ __privateGet$7(this, _namespaces).database = new DatabaseApi(__privateGet$7(this, _extraProps));
905
+ return __privateGet$7(this, _namespaces).database;
539
906
  }
540
907
  get branches() {
541
908
  if (!__privateGet$7(this, _namespaces).branches)
542
909
  __privateGet$7(this, _namespaces).branches = new BranchApi(__privateGet$7(this, _extraProps));
543
910
  return __privateGet$7(this, _namespaces).branches;
544
911
  }
912
+ get migrations() {
913
+ if (!__privateGet$7(this, _namespaces).migrations)
914
+ __privateGet$7(this, _namespaces).migrations = new MigrationsApi(__privateGet$7(this, _extraProps));
915
+ return __privateGet$7(this, _namespaces).migrations;
916
+ }
917
+ get migrationRequests() {
918
+ if (!__privateGet$7(this, _namespaces).migrationRequests)
919
+ __privateGet$7(this, _namespaces).migrationRequests = new MigrationRequestsApi(__privateGet$7(this, _extraProps));
920
+ return __privateGet$7(this, _namespaces).migrationRequests;
921
+ }
545
922
  get tables() {
546
923
  if (!__privateGet$7(this, _namespaces).tables)
547
924
  __privateGet$7(this, _namespaces).tables = new TableApi(__privateGet$7(this, _extraProps));
@@ -552,6 +929,11 @@ class XataApiClient {
552
929
  __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
553
930
  return __privateGet$7(this, _namespaces).records;
554
931
  }
932
+ get searchAndFilter() {
933
+ if (!__privateGet$7(this, _namespaces).searchAndFilter)
934
+ __privateGet$7(this, _namespaces).searchAndFilter = new SearchAndFilterApi(__privateGet$7(this, _extraProps));
935
+ return __privateGet$7(this, _namespaces).searchAndFilter;
936
+ }
555
937
  }
556
938
  _extraProps = new WeakMap();
557
939
  _namespaces = new WeakMap();
@@ -562,24 +944,29 @@ class UserApi {
562
944
  getUser() {
563
945
  return operationsByTag.users.getUser({ ...this.extraProps });
564
946
  }
565
- updateUser(user) {
947
+ updateUser({ user }) {
566
948
  return operationsByTag.users.updateUser({ body: user, ...this.extraProps });
567
949
  }
568
950
  deleteUser() {
569
951
  return operationsByTag.users.deleteUser({ ...this.extraProps });
570
952
  }
953
+ }
954
+ class AuthenticationApi {
955
+ constructor(extraProps) {
956
+ this.extraProps = extraProps;
957
+ }
571
958
  getUserAPIKeys() {
572
- return operationsByTag.users.getUserAPIKeys({ ...this.extraProps });
959
+ return operationsByTag.authentication.getUserAPIKeys({ ...this.extraProps });
573
960
  }
574
- createUserAPIKey(keyName) {
575
- return operationsByTag.users.createUserAPIKey({
576
- pathParams: { keyName },
961
+ createUserAPIKey({ name }) {
962
+ return operationsByTag.authentication.createUserAPIKey({
963
+ pathParams: { keyName: name },
577
964
  ...this.extraProps
578
965
  });
579
966
  }
580
- deleteUserAPIKey(keyName) {
581
- return operationsByTag.users.deleteUserAPIKey({
582
- pathParams: { keyName },
967
+ deleteUserAPIKey({ name }) {
968
+ return operationsByTag.authentication.deleteUserAPIKey({
969
+ pathParams: { keyName: name },
583
970
  ...this.extraProps
584
971
  });
585
972
  }
@@ -588,342 +975,897 @@ class WorkspaceApi {
588
975
  constructor(extraProps) {
589
976
  this.extraProps = extraProps;
590
977
  }
591
- createWorkspace(workspaceMeta) {
978
+ getWorkspacesList() {
979
+ return operationsByTag.workspaces.getWorkspacesList({ ...this.extraProps });
980
+ }
981
+ createWorkspace({ data }) {
592
982
  return operationsByTag.workspaces.createWorkspace({
593
- body: workspaceMeta,
983
+ body: data,
594
984
  ...this.extraProps
595
985
  });
596
986
  }
597
- getWorkspacesList() {
598
- return operationsByTag.workspaces.getWorkspacesList({ ...this.extraProps });
599
- }
600
- getWorkspace(workspaceId) {
987
+ getWorkspace({ workspace }) {
601
988
  return operationsByTag.workspaces.getWorkspace({
602
- pathParams: { workspaceId },
989
+ pathParams: { workspaceId: workspace },
603
990
  ...this.extraProps
604
991
  });
605
992
  }
606
- updateWorkspace(workspaceId, workspaceMeta) {
993
+ updateWorkspace({
994
+ workspace,
995
+ update
996
+ }) {
607
997
  return operationsByTag.workspaces.updateWorkspace({
608
- pathParams: { workspaceId },
609
- body: workspaceMeta,
998
+ pathParams: { workspaceId: workspace },
999
+ body: update,
610
1000
  ...this.extraProps
611
1001
  });
612
1002
  }
613
- deleteWorkspace(workspaceId) {
1003
+ deleteWorkspace({ workspace }) {
614
1004
  return operationsByTag.workspaces.deleteWorkspace({
615
- pathParams: { workspaceId },
1005
+ pathParams: { workspaceId: workspace },
616
1006
  ...this.extraProps
617
1007
  });
618
1008
  }
619
- getWorkspaceMembersList(workspaceId) {
1009
+ getWorkspaceMembersList({ workspace }) {
620
1010
  return operationsByTag.workspaces.getWorkspaceMembersList({
621
- pathParams: { workspaceId },
1011
+ pathParams: { workspaceId: workspace },
622
1012
  ...this.extraProps
623
1013
  });
624
1014
  }
625
- updateWorkspaceMemberRole(workspaceId, userId, role) {
1015
+ updateWorkspaceMemberRole({
1016
+ workspace,
1017
+ user,
1018
+ role
1019
+ }) {
626
1020
  return operationsByTag.workspaces.updateWorkspaceMemberRole({
627
- pathParams: { workspaceId, userId },
1021
+ pathParams: { workspaceId: workspace, userId: user },
628
1022
  body: { role },
629
1023
  ...this.extraProps
630
1024
  });
631
1025
  }
632
- removeWorkspaceMember(workspaceId, userId) {
1026
+ removeWorkspaceMember({
1027
+ workspace,
1028
+ user
1029
+ }) {
633
1030
  return operationsByTag.workspaces.removeWorkspaceMember({
634
- pathParams: { workspaceId, userId },
1031
+ pathParams: { workspaceId: workspace, userId: user },
635
1032
  ...this.extraProps
636
1033
  });
637
1034
  }
638
- inviteWorkspaceMember(workspaceId, email, role) {
639
- return operationsByTag.workspaces.inviteWorkspaceMember({
640
- pathParams: { workspaceId },
1035
+ }
1036
+ class InvitesApi {
1037
+ constructor(extraProps) {
1038
+ this.extraProps = extraProps;
1039
+ }
1040
+ inviteWorkspaceMember({
1041
+ workspace,
1042
+ email,
1043
+ role
1044
+ }) {
1045
+ return operationsByTag.invites.inviteWorkspaceMember({
1046
+ pathParams: { workspaceId: workspace },
641
1047
  body: { email, role },
642
1048
  ...this.extraProps
643
1049
  });
644
1050
  }
645
- cancelWorkspaceMemberInvite(workspaceId, inviteId) {
646
- return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
647
- pathParams: { workspaceId, inviteId },
1051
+ updateWorkspaceMemberInvite({
1052
+ workspace,
1053
+ invite,
1054
+ role
1055
+ }) {
1056
+ return operationsByTag.invites.updateWorkspaceMemberInvite({
1057
+ pathParams: { workspaceId: workspace, inviteId: invite },
1058
+ body: { role },
648
1059
  ...this.extraProps
649
1060
  });
650
1061
  }
651
- resendWorkspaceMemberInvite(workspaceId, inviteId) {
652
- return operationsByTag.workspaces.resendWorkspaceMemberInvite({
653
- pathParams: { workspaceId, inviteId },
1062
+ cancelWorkspaceMemberInvite({
1063
+ workspace,
1064
+ invite
1065
+ }) {
1066
+ return operationsByTag.invites.cancelWorkspaceMemberInvite({
1067
+ pathParams: { workspaceId: workspace, inviteId: invite },
1068
+ ...this.extraProps
1069
+ });
1070
+ }
1071
+ acceptWorkspaceMemberInvite({
1072
+ workspace,
1073
+ key
1074
+ }) {
1075
+ return operationsByTag.invites.acceptWorkspaceMemberInvite({
1076
+ pathParams: { workspaceId: workspace, inviteKey: key },
654
1077
  ...this.extraProps
655
1078
  });
656
1079
  }
657
- acceptWorkspaceMemberInvite(workspaceId, inviteKey) {
658
- return operationsByTag.workspaces.acceptWorkspaceMemberInvite({
659
- pathParams: { workspaceId, inviteKey },
1080
+ resendWorkspaceMemberInvite({
1081
+ workspace,
1082
+ invite
1083
+ }) {
1084
+ return operationsByTag.invites.resendWorkspaceMemberInvite({
1085
+ pathParams: { workspaceId: workspace, inviteId: invite },
660
1086
  ...this.extraProps
661
1087
  });
662
1088
  }
663
1089
  }
664
- class DatabaseApi {
1090
+ class BranchApi {
665
1091
  constructor(extraProps) {
666
1092
  this.extraProps = extraProps;
667
1093
  }
668
- getDatabaseList(workspace) {
669
- return operationsByTag.database.getDatabaseList({
670
- pathParams: { workspace },
1094
+ getBranchList({
1095
+ workspace,
1096
+ region,
1097
+ database
1098
+ }) {
1099
+ return operationsByTag.branch.getBranchList({
1100
+ pathParams: { workspace, region, dbName: database },
671
1101
  ...this.extraProps
672
1102
  });
673
1103
  }
674
- createDatabase(workspace, dbName, options = {}) {
675
- return operationsByTag.database.createDatabase({
676
- pathParams: { workspace, dbName },
677
- body: options,
1104
+ getBranchDetails({
1105
+ workspace,
1106
+ region,
1107
+ database,
1108
+ branch
1109
+ }) {
1110
+ return operationsByTag.branch.getBranchDetails({
1111
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
678
1112
  ...this.extraProps
679
1113
  });
680
1114
  }
681
- deleteDatabase(workspace, dbName) {
682
- return operationsByTag.database.deleteDatabase({
683
- pathParams: { workspace, dbName },
1115
+ createBranch({
1116
+ workspace,
1117
+ region,
1118
+ database,
1119
+ branch,
1120
+ from,
1121
+ metadata
1122
+ }) {
1123
+ return operationsByTag.branch.createBranch({
1124
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1125
+ body: { from, metadata },
684
1126
  ...this.extraProps
685
1127
  });
686
1128
  }
687
- getGitBranchesMapping(workspace, dbName) {
688
- return operationsByTag.database.getGitBranchesMapping({
689
- pathParams: { workspace, dbName },
1129
+ deleteBranch({
1130
+ workspace,
1131
+ region,
1132
+ database,
1133
+ branch
1134
+ }) {
1135
+ return operationsByTag.branch.deleteBranch({
1136
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
690
1137
  ...this.extraProps
691
1138
  });
692
1139
  }
693
- addGitBranchesEntry(workspace, dbName, body) {
694
- return operationsByTag.database.addGitBranchesEntry({
695
- pathParams: { workspace, dbName },
696
- body,
1140
+ updateBranchMetadata({
1141
+ workspace,
1142
+ region,
1143
+ database,
1144
+ branch,
1145
+ metadata
1146
+ }) {
1147
+ return operationsByTag.branch.updateBranchMetadata({
1148
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1149
+ body: metadata,
1150
+ ...this.extraProps
1151
+ });
1152
+ }
1153
+ getBranchMetadata({
1154
+ workspace,
1155
+ region,
1156
+ database,
1157
+ branch
1158
+ }) {
1159
+ return operationsByTag.branch.getBranchMetadata({
1160
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
697
1161
  ...this.extraProps
698
1162
  });
699
1163
  }
700
- removeGitBranchesEntry(workspace, dbName, gitBranch) {
701
- return operationsByTag.database.removeGitBranchesEntry({
702
- pathParams: { workspace, dbName },
1164
+ getBranchStats({
1165
+ workspace,
1166
+ region,
1167
+ database,
1168
+ branch
1169
+ }) {
1170
+ return operationsByTag.branch.getBranchStats({
1171
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1172
+ ...this.extraProps
1173
+ });
1174
+ }
1175
+ getGitBranchesMapping({
1176
+ workspace,
1177
+ region,
1178
+ database
1179
+ }) {
1180
+ return operationsByTag.branch.getGitBranchesMapping({
1181
+ pathParams: { workspace, region, dbName: database },
1182
+ ...this.extraProps
1183
+ });
1184
+ }
1185
+ addGitBranchesEntry({
1186
+ workspace,
1187
+ region,
1188
+ database,
1189
+ gitBranch,
1190
+ xataBranch
1191
+ }) {
1192
+ return operationsByTag.branch.addGitBranchesEntry({
1193
+ pathParams: { workspace, region, dbName: database },
1194
+ body: { gitBranch, xataBranch },
1195
+ ...this.extraProps
1196
+ });
1197
+ }
1198
+ removeGitBranchesEntry({
1199
+ workspace,
1200
+ region,
1201
+ database,
1202
+ gitBranch
1203
+ }) {
1204
+ return operationsByTag.branch.removeGitBranchesEntry({
1205
+ pathParams: { workspace, region, dbName: database },
703
1206
  queryParams: { gitBranch },
704
1207
  ...this.extraProps
705
1208
  });
706
1209
  }
707
- resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
708
- return operationsByTag.database.resolveBranch({
709
- pathParams: { workspace, dbName },
1210
+ resolveBranch({
1211
+ workspace,
1212
+ region,
1213
+ database,
1214
+ gitBranch,
1215
+ fallbackBranch
1216
+ }) {
1217
+ return operationsByTag.branch.resolveBranch({
1218
+ pathParams: { workspace, region, dbName: database },
710
1219
  queryParams: { gitBranch, fallbackBranch },
711
1220
  ...this.extraProps
712
1221
  });
713
1222
  }
714
1223
  }
715
- class BranchApi {
1224
+ class TableApi {
716
1225
  constructor(extraProps) {
717
1226
  this.extraProps = extraProps;
718
1227
  }
719
- getBranchList(workspace, dbName) {
720
- return operationsByTag.branch.getBranchList({
721
- pathParams: { workspace, dbName },
1228
+ createTable({
1229
+ workspace,
1230
+ region,
1231
+ database,
1232
+ branch,
1233
+ table
1234
+ }) {
1235
+ return operationsByTag.table.createTable({
1236
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
722
1237
  ...this.extraProps
723
1238
  });
724
1239
  }
725
- getBranchDetails(workspace, database, branch) {
726
- return operationsByTag.branch.getBranchDetails({
727
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1240
+ deleteTable({
1241
+ workspace,
1242
+ region,
1243
+ database,
1244
+ branch,
1245
+ table
1246
+ }) {
1247
+ return operationsByTag.table.deleteTable({
1248
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
728
1249
  ...this.extraProps
729
1250
  });
730
1251
  }
731
- createBranch(workspace, database, branch, from, options = {}) {
732
- return operationsByTag.branch.createBranch({
733
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
734
- queryParams: isString(from) ? { from } : void 0,
735
- body: options,
1252
+ updateTable({
1253
+ workspace,
1254
+ region,
1255
+ database,
1256
+ branch,
1257
+ table,
1258
+ update
1259
+ }) {
1260
+ return operationsByTag.table.updateTable({
1261
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1262
+ body: update,
736
1263
  ...this.extraProps
737
1264
  });
738
1265
  }
739
- deleteBranch(workspace, database, branch) {
740
- return operationsByTag.branch.deleteBranch({
741
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1266
+ getTableSchema({
1267
+ workspace,
1268
+ region,
1269
+ database,
1270
+ branch,
1271
+ table
1272
+ }) {
1273
+ return operationsByTag.table.getTableSchema({
1274
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
742
1275
  ...this.extraProps
743
1276
  });
744
1277
  }
745
- updateBranchMetadata(workspace, database, branch, metadata = {}) {
746
- return operationsByTag.branch.updateBranchMetadata({
747
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
748
- body: metadata,
1278
+ setTableSchema({
1279
+ workspace,
1280
+ region,
1281
+ database,
1282
+ branch,
1283
+ table,
1284
+ schema
1285
+ }) {
1286
+ return operationsByTag.table.setTableSchema({
1287
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1288
+ body: schema,
749
1289
  ...this.extraProps
750
1290
  });
751
1291
  }
752
- getBranchMetadata(workspace, database, branch) {
753
- return operationsByTag.branch.getBranchMetadata({
754
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1292
+ getTableColumns({
1293
+ workspace,
1294
+ region,
1295
+ database,
1296
+ branch,
1297
+ table
1298
+ }) {
1299
+ return operationsByTag.table.getTableColumns({
1300
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
755
1301
  ...this.extraProps
756
1302
  });
757
1303
  }
758
- getBranchMigrationHistory(workspace, database, branch, options = {}) {
759
- return operationsByTag.branch.getBranchMigrationHistory({
760
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
761
- body: options,
1304
+ addTableColumn({
1305
+ workspace,
1306
+ region,
1307
+ database,
1308
+ branch,
1309
+ table,
1310
+ column
1311
+ }) {
1312
+ return operationsByTag.table.addTableColumn({
1313
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1314
+ body: column,
762
1315
  ...this.extraProps
763
1316
  });
764
1317
  }
765
- executeBranchMigrationPlan(workspace, database, branch, migrationPlan) {
766
- return operationsByTag.branch.executeBranchMigrationPlan({
767
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
768
- body: migrationPlan,
1318
+ getColumn({
1319
+ workspace,
1320
+ region,
1321
+ database,
1322
+ branch,
1323
+ table,
1324
+ column
1325
+ }) {
1326
+ return operationsByTag.table.getColumn({
1327
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, columnName: column },
769
1328
  ...this.extraProps
770
1329
  });
771
1330
  }
772
- getBranchMigrationPlan(workspace, database, branch, schema) {
773
- return operationsByTag.branch.getBranchMigrationPlan({
774
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
775
- body: schema,
1331
+ updateColumn({
1332
+ workspace,
1333
+ region,
1334
+ database,
1335
+ branch,
1336
+ table,
1337
+ column,
1338
+ update
1339
+ }) {
1340
+ return operationsByTag.table.updateColumn({
1341
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, columnName: column },
1342
+ body: update,
776
1343
  ...this.extraProps
777
1344
  });
778
1345
  }
779
- getBranchStats(workspace, database, branch) {
780
- return operationsByTag.branch.getBranchStats({
781
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
1346
+ deleteColumn({
1347
+ workspace,
1348
+ region,
1349
+ database,
1350
+ branch,
1351
+ table,
1352
+ column
1353
+ }) {
1354
+ return operationsByTag.table.deleteColumn({
1355
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, columnName: column },
782
1356
  ...this.extraProps
783
1357
  });
784
1358
  }
785
1359
  }
786
- class TableApi {
1360
+ class RecordsApi {
787
1361
  constructor(extraProps) {
788
1362
  this.extraProps = extraProps;
789
1363
  }
790
- createTable(workspace, database, branch, tableName) {
791
- return operationsByTag.table.createTable({
792
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1364
+ insertRecord({
1365
+ workspace,
1366
+ region,
1367
+ database,
1368
+ branch,
1369
+ table,
1370
+ record,
1371
+ columns
1372
+ }) {
1373
+ return operationsByTag.records.insertRecord({
1374
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1375
+ queryParams: { columns },
1376
+ body: record,
793
1377
  ...this.extraProps
794
1378
  });
795
1379
  }
796
- deleteTable(workspace, database, branch, tableName) {
797
- return operationsByTag.table.deleteTable({
798
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1380
+ getRecord({
1381
+ workspace,
1382
+ region,
1383
+ database,
1384
+ branch,
1385
+ table,
1386
+ id,
1387
+ columns
1388
+ }) {
1389
+ return operationsByTag.records.getRecord({
1390
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, recordId: id },
1391
+ queryParams: { columns },
799
1392
  ...this.extraProps
800
1393
  });
801
1394
  }
802
- updateTable(workspace, database, branch, tableName, options) {
803
- return operationsByTag.table.updateTable({
804
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
805
- body: options,
1395
+ insertRecordWithID({
1396
+ workspace,
1397
+ region,
1398
+ database,
1399
+ branch,
1400
+ table,
1401
+ id,
1402
+ record,
1403
+ columns,
1404
+ createOnly,
1405
+ ifVersion
1406
+ }) {
1407
+ return operationsByTag.records.insertRecordWithID({
1408
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, recordId: id },
1409
+ queryParams: { columns, createOnly, ifVersion },
1410
+ body: record,
1411
+ ...this.extraProps
1412
+ });
1413
+ }
1414
+ updateRecordWithID({
1415
+ workspace,
1416
+ region,
1417
+ database,
1418
+ branch,
1419
+ table,
1420
+ id,
1421
+ record,
1422
+ columns,
1423
+ ifVersion
1424
+ }) {
1425
+ return operationsByTag.records.updateRecordWithID({
1426
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, recordId: id },
1427
+ queryParams: { columns, ifVersion },
1428
+ body: record,
1429
+ ...this.extraProps
1430
+ });
1431
+ }
1432
+ upsertRecordWithID({
1433
+ workspace,
1434
+ region,
1435
+ database,
1436
+ branch,
1437
+ table,
1438
+ id,
1439
+ record,
1440
+ columns,
1441
+ ifVersion
1442
+ }) {
1443
+ return operationsByTag.records.upsertRecordWithID({
1444
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, recordId: id },
1445
+ queryParams: { columns, ifVersion },
1446
+ body: record,
1447
+ ...this.extraProps
1448
+ });
1449
+ }
1450
+ deleteRecord({
1451
+ workspace,
1452
+ region,
1453
+ database,
1454
+ branch,
1455
+ table,
1456
+ id,
1457
+ columns
1458
+ }) {
1459
+ return operationsByTag.records.deleteRecord({
1460
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, recordId: id },
1461
+ queryParams: { columns },
1462
+ ...this.extraProps
1463
+ });
1464
+ }
1465
+ bulkInsertTableRecords({
1466
+ workspace,
1467
+ region,
1468
+ database,
1469
+ branch,
1470
+ table,
1471
+ records,
1472
+ columns
1473
+ }) {
1474
+ return operationsByTag.records.bulkInsertTableRecords({
1475
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1476
+ queryParams: { columns },
1477
+ body: { records },
1478
+ ...this.extraProps
1479
+ });
1480
+ }
1481
+ branchTransaction({
1482
+ workspace,
1483
+ region,
1484
+ database,
1485
+ branch,
1486
+ operations
1487
+ }) {
1488
+ return operationsByTag.records.branchTransaction({
1489
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1490
+ body: { operations },
1491
+ ...this.extraProps
1492
+ });
1493
+ }
1494
+ }
1495
+ class SearchAndFilterApi {
1496
+ constructor(extraProps) {
1497
+ this.extraProps = extraProps;
1498
+ }
1499
+ queryTable({
1500
+ workspace,
1501
+ region,
1502
+ database,
1503
+ branch,
1504
+ table,
1505
+ filter,
1506
+ sort,
1507
+ page,
1508
+ columns,
1509
+ consistency
1510
+ }) {
1511
+ return operationsByTag.searchAndFilter.queryTable({
1512
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1513
+ body: { filter, sort, page, columns, consistency },
1514
+ ...this.extraProps
1515
+ });
1516
+ }
1517
+ searchTable({
1518
+ workspace,
1519
+ region,
1520
+ database,
1521
+ branch,
1522
+ table,
1523
+ query,
1524
+ fuzziness,
1525
+ target,
1526
+ prefix,
1527
+ filter,
1528
+ highlight,
1529
+ boosters
1530
+ }) {
1531
+ return operationsByTag.searchAndFilter.searchTable({
1532
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1533
+ body: { query, fuzziness, target, prefix, filter, highlight, boosters },
1534
+ ...this.extraProps
1535
+ });
1536
+ }
1537
+ searchBranch({
1538
+ workspace,
1539
+ region,
1540
+ database,
1541
+ branch,
1542
+ tables,
1543
+ query,
1544
+ fuzziness,
1545
+ prefix,
1546
+ highlight
1547
+ }) {
1548
+ return operationsByTag.searchAndFilter.searchBranch({
1549
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1550
+ body: { tables, query, fuzziness, prefix, highlight },
1551
+ ...this.extraProps
1552
+ });
1553
+ }
1554
+ summarizeTable({
1555
+ workspace,
1556
+ region,
1557
+ database,
1558
+ branch,
1559
+ table,
1560
+ filter,
1561
+ columns,
1562
+ summaries,
1563
+ sort,
1564
+ summariesFilter,
1565
+ page,
1566
+ consistency
1567
+ }) {
1568
+ return operationsByTag.searchAndFilter.summarizeTable({
1569
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1570
+ body: { filter, columns, summaries, sort, summariesFilter, page, consistency },
1571
+ ...this.extraProps
1572
+ });
1573
+ }
1574
+ aggregateTable({
1575
+ workspace,
1576
+ region,
1577
+ database,
1578
+ branch,
1579
+ table,
1580
+ filter,
1581
+ aggs
1582
+ }) {
1583
+ return operationsByTag.searchAndFilter.aggregateTable({
1584
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1585
+ body: { filter, aggs },
1586
+ ...this.extraProps
1587
+ });
1588
+ }
1589
+ }
1590
+ class MigrationRequestsApi {
1591
+ constructor(extraProps) {
1592
+ this.extraProps = extraProps;
1593
+ }
1594
+ queryMigrationRequests({
1595
+ workspace,
1596
+ region,
1597
+ database,
1598
+ filter,
1599
+ sort,
1600
+ page,
1601
+ columns
1602
+ }) {
1603
+ return operationsByTag.migrationRequests.queryMigrationRequests({
1604
+ pathParams: { workspace, region, dbName: database },
1605
+ body: { filter, sort, page, columns },
1606
+ ...this.extraProps
1607
+ });
1608
+ }
1609
+ createMigrationRequest({
1610
+ workspace,
1611
+ region,
1612
+ database,
1613
+ migration
1614
+ }) {
1615
+ return operationsByTag.migrationRequests.createMigrationRequest({
1616
+ pathParams: { workspace, region, dbName: database },
1617
+ body: migration,
1618
+ ...this.extraProps
1619
+ });
1620
+ }
1621
+ getMigrationRequest({
1622
+ workspace,
1623
+ region,
1624
+ database,
1625
+ migrationRequest
1626
+ }) {
1627
+ return operationsByTag.migrationRequests.getMigrationRequest({
1628
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
1629
+ ...this.extraProps
1630
+ });
1631
+ }
1632
+ updateMigrationRequest({
1633
+ workspace,
1634
+ region,
1635
+ database,
1636
+ migrationRequest,
1637
+ update
1638
+ }) {
1639
+ return operationsByTag.migrationRequests.updateMigrationRequest({
1640
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
1641
+ body: update,
1642
+ ...this.extraProps
1643
+ });
1644
+ }
1645
+ listMigrationRequestsCommits({
1646
+ workspace,
1647
+ region,
1648
+ database,
1649
+ migrationRequest,
1650
+ page
1651
+ }) {
1652
+ return operationsByTag.migrationRequests.listMigrationRequestsCommits({
1653
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
1654
+ body: { page },
1655
+ ...this.extraProps
1656
+ });
1657
+ }
1658
+ compareMigrationRequest({
1659
+ workspace,
1660
+ region,
1661
+ database,
1662
+ migrationRequest
1663
+ }) {
1664
+ return operationsByTag.migrationRequests.compareMigrationRequest({
1665
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
806
1666
  ...this.extraProps
807
1667
  });
808
1668
  }
809
- getTableSchema(workspace, database, branch, tableName) {
810
- return operationsByTag.table.getTableSchema({
811
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1669
+ getMigrationRequestIsMerged({
1670
+ workspace,
1671
+ region,
1672
+ database,
1673
+ migrationRequest
1674
+ }) {
1675
+ return operationsByTag.migrationRequests.getMigrationRequestIsMerged({
1676
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
812
1677
  ...this.extraProps
813
1678
  });
814
1679
  }
815
- setTableSchema(workspace, database, branch, tableName, options) {
816
- return operationsByTag.table.setTableSchema({
817
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
818
- body: options,
1680
+ mergeMigrationRequest({
1681
+ workspace,
1682
+ region,
1683
+ database,
1684
+ migrationRequest
1685
+ }) {
1686
+ return operationsByTag.migrationRequests.mergeMigrationRequest({
1687
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
819
1688
  ...this.extraProps
820
1689
  });
821
1690
  }
822
- getTableColumns(workspace, database, branch, tableName) {
823
- return operationsByTag.table.getTableColumns({
824
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1691
+ }
1692
+ class MigrationsApi {
1693
+ constructor(extraProps) {
1694
+ this.extraProps = extraProps;
1695
+ }
1696
+ getBranchMigrationHistory({
1697
+ workspace,
1698
+ region,
1699
+ database,
1700
+ branch,
1701
+ limit,
1702
+ startFrom
1703
+ }) {
1704
+ return operationsByTag.migrations.getBranchMigrationHistory({
1705
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1706
+ body: { limit, startFrom },
825
1707
  ...this.extraProps
826
1708
  });
827
1709
  }
828
- addTableColumn(workspace, database, branch, tableName, column) {
829
- return operationsByTag.table.addTableColumn({
830
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
831
- body: column,
1710
+ getBranchMigrationPlan({
1711
+ workspace,
1712
+ region,
1713
+ database,
1714
+ branch,
1715
+ schema
1716
+ }) {
1717
+ return operationsByTag.migrations.getBranchMigrationPlan({
1718
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1719
+ body: schema,
832
1720
  ...this.extraProps
833
1721
  });
834
1722
  }
835
- getColumn(workspace, database, branch, tableName, columnName) {
836
- return operationsByTag.table.getColumn({
837
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, columnName },
1723
+ executeBranchMigrationPlan({
1724
+ workspace,
1725
+ region,
1726
+ database,
1727
+ branch,
1728
+ plan
1729
+ }) {
1730
+ return operationsByTag.migrations.executeBranchMigrationPlan({
1731
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1732
+ body: plan,
838
1733
  ...this.extraProps
839
1734
  });
840
1735
  }
841
- deleteColumn(workspace, database, branch, tableName, columnName) {
842
- return operationsByTag.table.deleteColumn({
843
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, columnName },
1736
+ getBranchSchemaHistory({
1737
+ workspace,
1738
+ region,
1739
+ database,
1740
+ branch,
1741
+ page
1742
+ }) {
1743
+ return operationsByTag.migrations.getBranchSchemaHistory({
1744
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1745
+ body: { page },
844
1746
  ...this.extraProps
845
1747
  });
846
1748
  }
847
- updateColumn(workspace, database, branch, tableName, columnName, options) {
848
- return operationsByTag.table.updateColumn({
849
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, columnName },
850
- body: options,
1749
+ compareBranchWithUserSchema({
1750
+ workspace,
1751
+ region,
1752
+ database,
1753
+ branch,
1754
+ schema
1755
+ }) {
1756
+ return operationsByTag.migrations.compareBranchWithUserSchema({
1757
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1758
+ body: { schema },
851
1759
  ...this.extraProps
852
1760
  });
853
1761
  }
854
- }
855
- class RecordsApi {
856
- constructor(extraProps) {
857
- this.extraProps = extraProps;
858
- }
859
- insertRecord(workspace, database, branch, tableName, record) {
860
- return operationsByTag.records.insertRecord({
861
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
862
- body: record,
1762
+ compareBranchSchemas({
1763
+ workspace,
1764
+ region,
1765
+ database,
1766
+ branch,
1767
+ compare,
1768
+ schema
1769
+ }) {
1770
+ return operationsByTag.migrations.compareBranchSchemas({
1771
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, branchName: compare },
1772
+ body: { schema },
863
1773
  ...this.extraProps
864
1774
  });
865
1775
  }
866
- insertRecordWithID(workspace, database, branch, tableName, recordId, record, options = {}) {
867
- return operationsByTag.records.insertRecordWithID({
868
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
869
- queryParams: options,
870
- body: record,
1776
+ updateBranchSchema({
1777
+ workspace,
1778
+ region,
1779
+ database,
1780
+ branch,
1781
+ migration
1782
+ }) {
1783
+ return operationsByTag.migrations.updateBranchSchema({
1784
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1785
+ body: migration,
871
1786
  ...this.extraProps
872
1787
  });
873
1788
  }
874
- updateRecordWithID(workspace, database, branch, tableName, recordId, record, options = {}) {
875
- return operationsByTag.records.updateRecordWithID({
876
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
877
- queryParams: options,
878
- body: record,
1789
+ previewBranchSchemaEdit({
1790
+ workspace,
1791
+ region,
1792
+ database,
1793
+ branch,
1794
+ data
1795
+ }) {
1796
+ return operationsByTag.migrations.previewBranchSchemaEdit({
1797
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1798
+ body: data,
879
1799
  ...this.extraProps
880
1800
  });
881
1801
  }
882
- upsertRecordWithID(workspace, database, branch, tableName, recordId, record, options = {}) {
883
- return operationsByTag.records.upsertRecordWithID({
884
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
885
- queryParams: options,
886
- body: record,
1802
+ applyBranchSchemaEdit({
1803
+ workspace,
1804
+ region,
1805
+ database,
1806
+ branch,
1807
+ edits
1808
+ }) {
1809
+ return operationsByTag.migrations.applyBranchSchemaEdit({
1810
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1811
+ body: { edits },
887
1812
  ...this.extraProps
888
1813
  });
889
1814
  }
890
- deleteRecord(workspace, database, branch, tableName, recordId) {
891
- return operationsByTag.records.deleteRecord({
892
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1815
+ }
1816
+ class DatabaseApi {
1817
+ constructor(extraProps) {
1818
+ this.extraProps = extraProps;
1819
+ }
1820
+ getDatabaseList({ workspace }) {
1821
+ return operationsByTag.databases.getDatabaseList({
1822
+ pathParams: { workspaceId: workspace },
893
1823
  ...this.extraProps
894
1824
  });
895
1825
  }
896
- getRecord(workspace, database, branch, tableName, recordId, options = {}) {
897
- return operationsByTag.records.getRecord({
898
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1826
+ createDatabase({
1827
+ workspace,
1828
+ database,
1829
+ data
1830
+ }) {
1831
+ return operationsByTag.databases.createDatabase({
1832
+ pathParams: { workspaceId: workspace, dbName: database },
1833
+ body: data,
899
1834
  ...this.extraProps
900
1835
  });
901
1836
  }
902
- bulkInsertTableRecords(workspace, database, branch, tableName, records) {
903
- return operationsByTag.records.bulkInsertTableRecords({
904
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
905
- body: { records },
1837
+ deleteDatabase({
1838
+ workspace,
1839
+ database
1840
+ }) {
1841
+ return operationsByTag.databases.deleteDatabase({
1842
+ pathParams: { workspaceId: workspace, dbName: database },
906
1843
  ...this.extraProps
907
1844
  });
908
1845
  }
909
- queryTable(workspace, database, branch, tableName, query) {
910
- return operationsByTag.records.queryTable({
911
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
912
- body: query,
1846
+ getDatabaseMetadata({
1847
+ workspace,
1848
+ database
1849
+ }) {
1850
+ return operationsByTag.databases.getDatabaseMetadata({
1851
+ pathParams: { workspaceId: workspace, dbName: database },
913
1852
  ...this.extraProps
914
1853
  });
915
1854
  }
916
- searchTable(workspace, database, branch, tableName, query) {
917
- return operationsByTag.records.searchTable({
918
- pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
919
- body: query,
1855
+ updateDatabaseMetadata({
1856
+ workspace,
1857
+ database,
1858
+ metadata
1859
+ }) {
1860
+ return operationsByTag.databases.updateDatabaseMetadata({
1861
+ pathParams: { workspaceId: workspace, dbName: database },
1862
+ body: metadata,
920
1863
  ...this.extraProps
921
1864
  });
922
1865
  }
923
- searchBranch(workspace, database, branch, query) {
924
- return operationsByTag.records.searchBranch({
925
- pathParams: { workspace, dbBranchName: `${database}:${branch}` },
926
- body: query,
1866
+ listRegions({ workspace }) {
1867
+ return operationsByTag.databases.listRegions({
1868
+ pathParams: { workspaceId: workspace },
927
1869
  ...this.extraProps
928
1870
  });
929
1871
  }
@@ -939,6 +1881,20 @@ class XataApiPlugin {
939
1881
  class XataPlugin {
940
1882
  }
941
1883
 
1884
+ function generateUUID() {
1885
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
1886
+ const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
1887
+ return v.toString(16);
1888
+ });
1889
+ }
1890
+
1891
+ function cleanFilter(filter) {
1892
+ if (!filter)
1893
+ return void 0;
1894
+ const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
1895
+ return values.length > 0 ? filter : void 0;
1896
+ }
1897
+
942
1898
  var __accessCheck$6 = (obj, member, msg) => {
943
1899
  if (!member.has(obj))
944
1900
  throw TypeError("Cannot " + msg);
@@ -952,7 +1908,7 @@ var __privateAdd$6 = (obj, member, value) => {
952
1908
  throw TypeError("Cannot add the same private member more than once");
953
1909
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
954
1910
  };
955
- var __privateSet$5 = (obj, member, value, setter) => {
1911
+ var __privateSet$6 = (obj, member, value, setter) => {
956
1912
  __accessCheck$6(obj, member, "write to private field");
957
1913
  setter ? setter.call(obj, value) : member.set(obj, value);
958
1914
  return value;
@@ -961,7 +1917,7 @@ var _query, _page;
961
1917
  class Page {
962
1918
  constructor(query, meta, records = []) {
963
1919
  __privateAdd$6(this, _query, void 0);
964
- __privateSet$5(this, _query, query);
1920
+ __privateSet$6(this, _query, query);
965
1921
  this.meta = meta;
966
1922
  this.records = new RecordArray(this, records);
967
1923
  }
@@ -971,11 +1927,11 @@ class Page {
971
1927
  async previousPage(size, offset) {
972
1928
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
973
1929
  }
974
- async firstPage(size, offset) {
975
- return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
1930
+ async startPage(size, offset) {
1931
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, start: this.meta.page.cursor } });
976
1932
  }
977
- async lastPage(size, offset) {
978
- return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
1933
+ async endPage(size, offset) {
1934
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, end: this.meta.page.cursor } });
979
1935
  }
980
1936
  hasNextPage() {
981
1937
  return this.meta.page.more;
@@ -987,13 +1943,13 @@ const PAGINATION_DEFAULT_SIZE = 20;
987
1943
  const PAGINATION_MAX_OFFSET = 800;
988
1944
  const PAGINATION_DEFAULT_OFFSET = 0;
989
1945
  function isCursorPaginationOptions(options) {
990
- return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
1946
+ return isDefined(options) && (isDefined(options.start) || isDefined(options.end) || isDefined(options.after) || isDefined(options.before));
991
1947
  }
992
1948
  const _RecordArray = class extends Array {
993
- constructor(page, overrideRecords) {
994
- super(..._RecordArray.parseConstructorParams(page, overrideRecords));
1949
+ constructor(...args) {
1950
+ super(..._RecordArray.parseConstructorParams(...args));
995
1951
  __privateAdd$6(this, _page, void 0);
996
- __privateSet$5(this, _page, page);
1952
+ __privateSet$6(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
997
1953
  }
998
1954
  static parseConstructorParams(...args) {
999
1955
  if (args.length === 1 && typeof args[0] === "number") {
@@ -1005,6 +1961,12 @@ const _RecordArray = class extends Array {
1005
1961
  }
1006
1962
  return new Array(...args);
1007
1963
  }
1964
+ toArray() {
1965
+ return new Array(...this);
1966
+ }
1967
+ map(callbackfn, thisArg) {
1968
+ return this.toArray().map(callbackfn, thisArg);
1969
+ }
1008
1970
  async nextPage(size, offset) {
1009
1971
  const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1010
1972
  return new _RecordArray(newPage);
@@ -1013,12 +1975,12 @@ const _RecordArray = class extends Array {
1013
1975
  const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1014
1976
  return new _RecordArray(newPage);
1015
1977
  }
1016
- async firstPage(size, offset) {
1017
- const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1978
+ async startPage(size, offset) {
1979
+ const newPage = await __privateGet$6(this, _page).startPage(size, offset);
1018
1980
  return new _RecordArray(newPage);
1019
1981
  }
1020
- async lastPage(size, offset) {
1021
- const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1982
+ async endPage(size, offset) {
1983
+ const newPage = await __privateGet$6(this, _page).endPage(size, offset);
1022
1984
  return new _RecordArray(newPage);
1023
1985
  }
1024
1986
  hasNextPage() {
@@ -1041,24 +2003,29 @@ var __privateAdd$5 = (obj, member, value) => {
1041
2003
  throw TypeError("Cannot add the same private member more than once");
1042
2004
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1043
2005
  };
1044
- var __privateSet$4 = (obj, member, value, setter) => {
2006
+ var __privateSet$5 = (obj, member, value, setter) => {
1045
2007
  __accessCheck$5(obj, member, "write to private field");
1046
2008
  setter ? setter.call(obj, value) : member.set(obj, value);
1047
2009
  return value;
1048
2010
  };
1049
- var _table$1, _repository, _data;
2011
+ var __privateMethod$3 = (obj, member, method) => {
2012
+ __accessCheck$5(obj, member, "access private method");
2013
+ return method;
2014
+ };
2015
+ var _table$1, _repository, _data, _cleanFilterConstraint, cleanFilterConstraint_fn;
1050
2016
  const _Query = class {
1051
2017
  constructor(repository, table, data, rawParent) {
2018
+ __privateAdd$5(this, _cleanFilterConstraint);
1052
2019
  __privateAdd$5(this, _table$1, void 0);
1053
2020
  __privateAdd$5(this, _repository, void 0);
1054
2021
  __privateAdd$5(this, _data, { filter: {} });
1055
2022
  this.meta = { page: { cursor: "start", more: true } };
1056
2023
  this.records = new RecordArray(this, []);
1057
- __privateSet$4(this, _table$1, table);
2024
+ __privateSet$5(this, _table$1, table);
1058
2025
  if (repository) {
1059
- __privateSet$4(this, _repository, repository);
2026
+ __privateSet$5(this, _repository, repository);
1060
2027
  } else {
1061
- __privateSet$4(this, _repository, this);
2028
+ __privateSet$5(this, _repository, this);
1062
2029
  }
1063
2030
  const parent = cleanParent(data, rawParent);
1064
2031
  __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
@@ -1067,9 +2034,10 @@ const _Query = class {
1067
2034
  __privateGet$5(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
1068
2035
  __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1069
2036
  __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1070
- __privateGet$5(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
2037
+ __privateGet$5(this, _data).columns = data.columns ?? parent?.columns;
1071
2038
  __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1072
2039
  __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
2040
+ __privateGet$5(this, _data).fetchOptions = data.fetchOptions ?? parent?.fetchOptions;
1073
2041
  this.any = this.any.bind(this);
1074
2042
  this.all = this.all.bind(this);
1075
2043
  this.not = this.not.bind(this);
@@ -1105,21 +2073,29 @@ const _Query = class {
1105
2073
  }
1106
2074
  filter(a, b) {
1107
2075
  if (arguments.length === 1) {
1108
- const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
2076
+ const constraints = Object.entries(a ?? {}).map(([column, constraint]) => ({
2077
+ [column]: __privateMethod$3(this, _cleanFilterConstraint, cleanFilterConstraint_fn).call(this, column, constraint)
2078
+ }));
1109
2079
  const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1110
2080
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1111
2081
  } else {
1112
- const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
2082
+ const constraints = isDefined(a) && isDefined(b) ? [{ [a]: __privateMethod$3(this, _cleanFilterConstraint, cleanFilterConstraint_fn).call(this, a, b) }] : void 0;
2083
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1113
2084
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1114
2085
  }
1115
2086
  }
1116
- sort(column, direction) {
2087
+ sort(column, direction = "asc") {
1117
2088
  const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
1118
2089
  const sort = [...originalSort, { column, direction }];
1119
2090
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
1120
2091
  }
1121
2092
  select(columns) {
1122
- return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { columns }, __privateGet$5(this, _data));
2093
+ return new _Query(
2094
+ __privateGet$5(this, _repository),
2095
+ __privateGet$5(this, _table$1),
2096
+ { columns },
2097
+ __privateGet$5(this, _data)
2098
+ );
1123
2099
  }
1124
2100
  getPaginated(options = {}) {
1125
2101
  const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
@@ -1142,11 +2118,20 @@ const _Query = class {
1142
2118
  }
1143
2119
  }
1144
2120
  async getMany(options = {}) {
1145
- const page = await this.getPaginated(options);
2121
+ const { pagination = {}, ...rest } = options;
2122
+ const { size = PAGINATION_DEFAULT_SIZE, offset } = pagination;
2123
+ const batchSize = size <= PAGINATION_MAX_SIZE ? size : PAGINATION_MAX_SIZE;
2124
+ let page = await this.getPaginated({ ...rest, pagination: { size: batchSize, offset } });
2125
+ const results = [...page.records];
2126
+ while (page.hasNextPage() && results.length < size) {
2127
+ page = await page.nextPage();
2128
+ results.push(...page.records);
2129
+ }
1146
2130
  if (page.hasNextPage() && options.pagination?.size === void 0) {
1147
2131
  console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1148
2132
  }
1149
- return page.records;
2133
+ const array = new RecordArray(page, results.slice(0, size));
2134
+ return array;
1150
2135
  }
1151
2136
  async getAll(options = {}) {
1152
2137
  const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
@@ -1160,19 +2145,35 @@ const _Query = class {
1160
2145
  const records = await this.getMany({ ...options, pagination: { size: 1 } });
1161
2146
  return records[0] ?? null;
1162
2147
  }
2148
+ async getFirstOrThrow(options = {}) {
2149
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
2150
+ if (records[0] === void 0)
2151
+ throw new Error("No results found.");
2152
+ return records[0];
2153
+ }
2154
+ async summarize(params = {}) {
2155
+ const { summaries, summariesFilter, ...options } = params;
2156
+ const query = new _Query(
2157
+ __privateGet$5(this, _repository),
2158
+ __privateGet$5(this, _table$1),
2159
+ options,
2160
+ __privateGet$5(this, _data)
2161
+ );
2162
+ return __privateGet$5(this, _repository).summarizeTable(query, summaries, summariesFilter);
2163
+ }
1163
2164
  cache(ttl) {
1164
2165
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1165
2166
  }
1166
2167
  nextPage(size, offset) {
1167
- return this.firstPage(size, offset);
2168
+ return this.startPage(size, offset);
1168
2169
  }
1169
2170
  previousPage(size, offset) {
1170
- return this.firstPage(size, offset);
2171
+ return this.startPage(size, offset);
1171
2172
  }
1172
- firstPage(size, offset) {
2173
+ startPage(size, offset) {
1173
2174
  return this.getPaginated({ pagination: { size, offset } });
1174
2175
  }
1175
- lastPage(size, offset) {
2176
+ endPage(size, offset) {
1176
2177
  return this.getPaginated({ pagination: { size, offset, before: "end" } });
1177
2178
  }
1178
2179
  hasNextPage() {
@@ -1183,9 +2184,20 @@ let Query = _Query;
1183
2184
  _table$1 = new WeakMap();
1184
2185
  _repository = new WeakMap();
1185
2186
  _data = new WeakMap();
2187
+ _cleanFilterConstraint = new WeakSet();
2188
+ cleanFilterConstraint_fn = function(column, value) {
2189
+ const columnType = __privateGet$5(this, _table$1).schema?.columns.find(({ name }) => name === column)?.type;
2190
+ if (columnType === "multiple" && (isString(value) || isStringArray(value))) {
2191
+ return { $includes: value };
2192
+ }
2193
+ if (columnType === "link" && isObject(value) && isString(value.id)) {
2194
+ return value.id;
2195
+ }
2196
+ return value;
2197
+ };
1186
2198
  function cleanParent(data, parent) {
1187
2199
  if (isCursorPaginationOptions(data.pagination)) {
1188
- return { ...parent, sorting: void 0, filter: void 0 };
2200
+ return { ...parent, sort: void 0, filter: void 0 };
1189
2201
  }
1190
2202
  return parent;
1191
2203
  }
@@ -1235,7 +2247,7 @@ var __privateAdd$4 = (obj, member, value) => {
1235
2247
  throw TypeError("Cannot add the same private member more than once");
1236
2248
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1237
2249
  };
1238
- var __privateSet$3 = (obj, member, value, setter) => {
2250
+ var __privateSet$4 = (obj, member, value, setter) => {
1239
2251
  __accessCheck$4(obj, member, "write to private field");
1240
2252
  setter ? setter.call(obj, value) : member.set(obj, value);
1241
2253
  return value;
@@ -1244,332 +2256,564 @@ var __privateMethod$2 = (obj, member, method) => {
1244
2256
  __accessCheck$4(obj, member, "access private method");
1245
2257
  return method;
1246
2258
  };
1247
- var _table, _getFetchProps, _cache, _schema$1, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _invalidateCache, invalidateCache_fn, _setCacheRecord, setCacheRecord_fn, _getCacheRecord, getCacheRecord_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchema$1, getSchema_fn$1;
2259
+ var _table, _getFetchProps, _db, _cache, _schemaTables$2, _trace, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _insertRecords, insertRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _updateRecords, updateRecords_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _deleteRecords, deleteRecords_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaTables$1, getSchemaTables_fn$1;
2260
+ const BULK_OPERATION_MAX_SIZE = 1e3;
1248
2261
  class Repository extends Query {
1249
2262
  }
1250
2263
  class RestRepository extends Query {
1251
2264
  constructor(options) {
1252
- super(null, options.table, {});
2265
+ super(
2266
+ null,
2267
+ { name: options.table, schema: options.schemaTables?.find((table) => table.name === options.table) },
2268
+ {}
2269
+ );
1253
2270
  __privateAdd$4(this, _insertRecordWithoutId);
1254
2271
  __privateAdd$4(this, _insertRecordWithId);
1255
- __privateAdd$4(this, _bulkInsertTableRecords);
2272
+ __privateAdd$4(this, _insertRecords);
1256
2273
  __privateAdd$4(this, _updateRecordWithID);
2274
+ __privateAdd$4(this, _updateRecords);
1257
2275
  __privateAdd$4(this, _upsertRecordWithID);
1258
2276
  __privateAdd$4(this, _deleteRecord);
1259
- __privateAdd$4(this, _invalidateCache);
1260
- __privateAdd$4(this, _setCacheRecord);
1261
- __privateAdd$4(this, _getCacheRecord);
2277
+ __privateAdd$4(this, _deleteRecords);
1262
2278
  __privateAdd$4(this, _setCacheQuery);
1263
2279
  __privateAdd$4(this, _getCacheQuery);
1264
- __privateAdd$4(this, _getSchema$1);
2280
+ __privateAdd$4(this, _getSchemaTables$1);
1265
2281
  __privateAdd$4(this, _table, void 0);
1266
2282
  __privateAdd$4(this, _getFetchProps, void 0);
2283
+ __privateAdd$4(this, _db, void 0);
1267
2284
  __privateAdd$4(this, _cache, void 0);
1268
- __privateAdd$4(this, _schema$1, void 0);
1269
- __privateSet$3(this, _table, options.table);
1270
- __privateSet$3(this, _getFetchProps, options.pluginOptions.getFetchProps);
1271
- this.db = options.db;
1272
- __privateSet$3(this, _cache, options.pluginOptions.cache);
1273
- }
1274
- async create(a, b) {
1275
- if (Array.isArray(a)) {
1276
- if (a.length === 0)
1277
- return [];
1278
- const [itemsWithoutIds, itemsWithIds, order] = a.reduce(([accWithoutIds, accWithIds, accOrder], item) => {
1279
- const condition = isString(item.id);
1280
- accOrder.push(condition);
1281
- if (condition) {
1282
- accWithIds.push(item);
1283
- } else {
1284
- accWithoutIds.push(item);
2285
+ __privateAdd$4(this, _schemaTables$2, void 0);
2286
+ __privateAdd$4(this, _trace, void 0);
2287
+ __privateSet$4(this, _table, options.table);
2288
+ __privateSet$4(this, _db, options.db);
2289
+ __privateSet$4(this, _cache, options.pluginOptions.cache);
2290
+ __privateSet$4(this, _schemaTables$2, options.schemaTables);
2291
+ __privateSet$4(this, _getFetchProps, async () => {
2292
+ const props = await options.pluginOptions.getFetchProps();
2293
+ return { ...props, sessionID: generateUUID() };
2294
+ });
2295
+ const trace = options.pluginOptions.trace ?? defaultTrace;
2296
+ __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
2297
+ return trace(name, fn, {
2298
+ ...options2,
2299
+ [TraceAttributes.TABLE]: __privateGet$4(this, _table),
2300
+ [TraceAttributes.KIND]: "sdk-operation",
2301
+ [TraceAttributes.VERSION]: VERSION
2302
+ });
2303
+ });
2304
+ }
2305
+ async create(a, b, c, d) {
2306
+ return __privateGet$4(this, _trace).call(this, "create", async () => {
2307
+ const ifVersion = parseIfVersion(b, c, d);
2308
+ if (Array.isArray(a)) {
2309
+ if (a.length === 0)
2310
+ return [];
2311
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: true });
2312
+ const columns = isStringArray(b) ? b : ["*"];
2313
+ const result = await this.read(ids, columns);
2314
+ return result;
2315
+ }
2316
+ if (isString(a) && isObject(b)) {
2317
+ if (a === "")
2318
+ throw new Error("The id can't be empty");
2319
+ const columns = isStringArray(c) ? c : void 0;
2320
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
2321
+ }
2322
+ if (isObject(a) && isString(a.id)) {
2323
+ if (a.id === "")
2324
+ throw new Error("The id can't be empty");
2325
+ const columns = isStringArray(b) ? b : void 0;
2326
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
2327
+ }
2328
+ if (isObject(a)) {
2329
+ const columns = isStringArray(b) ? b : void 0;
2330
+ return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
2331
+ }
2332
+ throw new Error("Invalid arguments for create method");
2333
+ });
2334
+ }
2335
+ async read(a, b) {
2336
+ return __privateGet$4(this, _trace).call(this, "read", async () => {
2337
+ const columns = isStringArray(b) ? b : ["*"];
2338
+ if (Array.isArray(a)) {
2339
+ if (a.length === 0)
2340
+ return [];
2341
+ const ids = a.map((item) => extractId(item));
2342
+ const finalObjects = await this.getAll({ filter: { id: { $any: compact(ids) } }, columns });
2343
+ const dictionary = finalObjects.reduce((acc, object) => {
2344
+ acc[object.id] = object;
2345
+ return acc;
2346
+ }, {});
2347
+ return ids.map((id2) => dictionary[id2 ?? ""] ?? null);
2348
+ }
2349
+ const id = extractId(a);
2350
+ if (id) {
2351
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2352
+ try {
2353
+ const response = await getRecord({
2354
+ pathParams: {
2355
+ workspace: "{workspaceId}",
2356
+ dbBranchName: "{dbBranch}",
2357
+ region: "{region}",
2358
+ tableName: __privateGet$4(this, _table),
2359
+ recordId: id
2360
+ },
2361
+ queryParams: { columns },
2362
+ ...fetchProps
2363
+ });
2364
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2365
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2366
+ } catch (e) {
2367
+ if (isObject(e) && e.status === 404) {
2368
+ return null;
2369
+ }
2370
+ throw e;
1285
2371
  }
1286
- return [accWithoutIds, accWithIds, accOrder];
1287
- }, [[], [], []]);
1288
- const recordsWithoutId = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, itemsWithoutIds);
1289
- await Promise.all(recordsWithoutId.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1290
- if (itemsWithIds.length > 100) {
1291
- console.warn("Bulk create operation with id is not optimized in the Xata API yet, this request might be slow");
1292
2372
  }
1293
- const recordsWithId = await Promise.all(itemsWithIds.map((object) => this.create(object)));
1294
- return order.map((condition) => {
1295
- if (condition) {
1296
- return recordsWithId.shift();
1297
- } else {
1298
- return recordsWithoutId.shift();
2373
+ return null;
2374
+ });
2375
+ }
2376
+ async readOrThrow(a, b) {
2377
+ return __privateGet$4(this, _trace).call(this, "readOrThrow", async () => {
2378
+ const result = await this.read(a, b);
2379
+ if (Array.isArray(result)) {
2380
+ const missingIds = compact(
2381
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
2382
+ );
2383
+ if (missingIds.length > 0) {
2384
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
1299
2385
  }
1300
- }).filter((record) => !!record);
1301
- }
1302
- if (isString(a) && isObject(b)) {
1303
- if (a === "")
1304
- throw new Error("The id can't be empty");
1305
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1306
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1307
- return record;
1308
- }
1309
- if (isObject(a) && isString(a.id)) {
1310
- if (a.id === "")
1311
- throw new Error("The id can't be empty");
1312
- const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1313
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1314
- return record;
1315
- }
1316
- if (isObject(a)) {
1317
- const record = await __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1318
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1319
- return record;
1320
- }
1321
- throw new Error("Invalid arguments for create method");
1322
- }
1323
- async read(a) {
1324
- if (Array.isArray(a)) {
1325
- if (a.length === 0)
1326
- return [];
1327
- const ids = a.map((item) => isString(item) ? item : item.id).filter((id2) => isString(id2));
1328
- return this.getAll({ filter: { id: { $any: ids } } });
1329
- }
1330
- const id = isString(a) ? a : a.id;
1331
- if (isString(id)) {
1332
- const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, id);
1333
- if (cacheRecord)
1334
- return cacheRecord;
1335
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1336
- try {
1337
- const response = await getRecord({
1338
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId: id },
1339
- ...fetchProps
2386
+ return result;
2387
+ }
2388
+ if (result === null) {
2389
+ const id = extractId(a) ?? "unknown";
2390
+ throw new Error(`Record with id ${id} not found`);
2391
+ }
2392
+ return result;
2393
+ });
2394
+ }
2395
+ async update(a, b, c, d) {
2396
+ return __privateGet$4(this, _trace).call(this, "update", async () => {
2397
+ const ifVersion = parseIfVersion(b, c, d);
2398
+ if (Array.isArray(a)) {
2399
+ if (a.length === 0)
2400
+ return [];
2401
+ const existing = await this.read(a, ["id"]);
2402
+ const updates = a.filter((_item, index) => existing[index] !== null);
2403
+ await __privateMethod$2(this, _updateRecords, updateRecords_fn).call(this, updates, {
2404
+ ifVersion,
2405
+ upsert: false
1340
2406
  });
1341
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1342
- return initObject(this.db, schema, __privateGet$4(this, _table), response);
1343
- } catch (e) {
1344
- if (isObject(e) && e.status === 404) {
1345
- return null;
2407
+ const columns = isStringArray(b) ? b : ["*"];
2408
+ const result = await this.read(a, columns);
2409
+ return result;
2410
+ }
2411
+ if (isString(a) && isObject(b)) {
2412
+ const columns = isStringArray(c) ? c : void 0;
2413
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2414
+ }
2415
+ if (isObject(a) && isString(a.id)) {
2416
+ const columns = isStringArray(b) ? b : void 0;
2417
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
2418
+ }
2419
+ throw new Error("Invalid arguments for update method");
2420
+ });
2421
+ }
2422
+ async updateOrThrow(a, b, c, d) {
2423
+ return __privateGet$4(this, _trace).call(this, "updateOrThrow", async () => {
2424
+ const result = await this.update(a, b, c, d);
2425
+ if (Array.isArray(result)) {
2426
+ const missingIds = compact(
2427
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
2428
+ );
2429
+ if (missingIds.length > 0) {
2430
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
1346
2431
  }
1347
- throw e;
2432
+ return result;
1348
2433
  }
1349
- }
2434
+ if (result === null) {
2435
+ const id = extractId(a) ?? "unknown";
2436
+ throw new Error(`Record with id ${id} not found`);
2437
+ }
2438
+ return result;
2439
+ });
1350
2440
  }
1351
- async update(a, b) {
1352
- if (Array.isArray(a)) {
1353
- if (a.length === 0)
1354
- return [];
1355
- if (a.length > 100) {
1356
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
2441
+ async createOrUpdate(a, b, c, d) {
2442
+ return __privateGet$4(this, _trace).call(this, "createOrUpdate", async () => {
2443
+ const ifVersion = parseIfVersion(b, c, d);
2444
+ if (Array.isArray(a)) {
2445
+ if (a.length === 0)
2446
+ return [];
2447
+ await __privateMethod$2(this, _updateRecords, updateRecords_fn).call(this, a, {
2448
+ ifVersion,
2449
+ upsert: true
2450
+ });
2451
+ const columns = isStringArray(b) ? b : ["*"];
2452
+ const result = await this.read(a, columns);
2453
+ return result;
1357
2454
  }
1358
- return Promise.all(a.map((object) => this.update(object)));
1359
- }
1360
- if (isString(a) && isObject(b)) {
1361
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1362
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1363
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1364
- return record;
1365
- }
1366
- if (isObject(a) && isString(a.id)) {
1367
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1368
- const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1369
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1370
- return record;
1371
- }
1372
- throw new Error("Invalid arguments for update method");
1373
- }
1374
- async createOrUpdate(a, b) {
1375
- if (Array.isArray(a)) {
1376
- if (a.length === 0)
1377
- return [];
1378
- if (a.length > 100) {
1379
- console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
2455
+ if (isString(a) && isObject(b)) {
2456
+ const columns = isStringArray(c) ? c : void 0;
2457
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
1380
2458
  }
1381
- return Promise.all(a.map((object) => this.createOrUpdate(object)));
1382
- }
1383
- if (isString(a) && isObject(b)) {
1384
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1385
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1386
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1387
- return record;
1388
- }
1389
- if (isObject(a) && isString(a.id)) {
1390
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1391
- const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1392
- await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1393
- return record;
1394
- }
1395
- throw new Error("Invalid arguments for createOrUpdate method");
1396
- }
1397
- async delete(a) {
1398
- if (Array.isArray(a)) {
1399
- if (a.length === 0)
1400
- return;
1401
- if (a.length > 100) {
1402
- console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
2459
+ if (isObject(a) && isString(a.id)) {
2460
+ const columns = isStringArray(c) ? c : void 0;
2461
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
1403
2462
  }
1404
- await Promise.all(a.map((id) => this.delete(id)));
1405
- return;
1406
- }
1407
- if (isString(a)) {
1408
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1409
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1410
- return;
1411
- }
1412
- if (isObject(a) && isString(a.id)) {
1413
- await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1414
- await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1415
- return;
1416
- }
1417
- throw new Error("Invalid arguments for delete method");
2463
+ throw new Error("Invalid arguments for createOrUpdate method");
2464
+ });
2465
+ }
2466
+ async createOrReplace(a, b, c, d) {
2467
+ return __privateGet$4(this, _trace).call(this, "createOrReplace", async () => {
2468
+ const ifVersion = parseIfVersion(b, c, d);
2469
+ if (Array.isArray(a)) {
2470
+ if (a.length === 0)
2471
+ return [];
2472
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: false });
2473
+ const columns = isStringArray(b) ? b : ["*"];
2474
+ const result = await this.read(ids, columns);
2475
+ return result;
2476
+ }
2477
+ if (isString(a) && isObject(b)) {
2478
+ const columns = isStringArray(c) ? c : void 0;
2479
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
2480
+ }
2481
+ if (isObject(a) && isString(a.id)) {
2482
+ const columns = isStringArray(c) ? c : void 0;
2483
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
2484
+ }
2485
+ throw new Error("Invalid arguments for createOrReplace method");
2486
+ });
2487
+ }
2488
+ async delete(a, b) {
2489
+ return __privateGet$4(this, _trace).call(this, "delete", async () => {
2490
+ if (Array.isArray(a)) {
2491
+ if (a.length === 0)
2492
+ return [];
2493
+ const ids = a.map((o) => {
2494
+ if (isString(o))
2495
+ return o;
2496
+ if (isString(o.id))
2497
+ return o.id;
2498
+ throw new Error("Invalid arguments for delete method");
2499
+ });
2500
+ const columns = isStringArray(b) ? b : ["*"];
2501
+ const result = await this.read(a, columns);
2502
+ await __privateMethod$2(this, _deleteRecords, deleteRecords_fn).call(this, ids);
2503
+ return result;
2504
+ }
2505
+ if (isString(a)) {
2506
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
2507
+ }
2508
+ if (isObject(a) && isString(a.id)) {
2509
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id, b);
2510
+ }
2511
+ throw new Error("Invalid arguments for delete method");
2512
+ });
2513
+ }
2514
+ async deleteOrThrow(a, b) {
2515
+ return __privateGet$4(this, _trace).call(this, "deleteOrThrow", async () => {
2516
+ const result = await this.delete(a, b);
2517
+ if (Array.isArray(result)) {
2518
+ const missingIds = compact(
2519
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
2520
+ );
2521
+ if (missingIds.length > 0) {
2522
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
2523
+ }
2524
+ return result;
2525
+ } else if (result === null) {
2526
+ const id = extractId(a) ?? "unknown";
2527
+ throw new Error(`Record with id ${id} not found`);
2528
+ }
2529
+ return result;
2530
+ });
1418
2531
  }
1419
2532
  async search(query, options = {}) {
1420
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1421
- const { records } = await searchTable({
1422
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1423
- body: {
1424
- query,
1425
- fuzziness: options.fuzziness,
1426
- highlight: options.highlight,
1427
- filter: options.filter
1428
- },
1429
- ...fetchProps
2533
+ return __privateGet$4(this, _trace).call(this, "search", async () => {
2534
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2535
+ const { records } = await searchTable({
2536
+ pathParams: {
2537
+ workspace: "{workspaceId}",
2538
+ dbBranchName: "{dbBranch}",
2539
+ region: "{region}",
2540
+ tableName: __privateGet$4(this, _table)
2541
+ },
2542
+ body: {
2543
+ query,
2544
+ fuzziness: options.fuzziness,
2545
+ prefix: options.prefix,
2546
+ highlight: options.highlight,
2547
+ filter: options.filter,
2548
+ boosters: options.boosters
2549
+ },
2550
+ ...fetchProps
2551
+ });
2552
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2553
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
2554
+ });
2555
+ }
2556
+ async aggregate(aggs, filter) {
2557
+ return __privateGet$4(this, _trace).call(this, "aggregate", async () => {
2558
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2559
+ const result = await aggregateTable({
2560
+ pathParams: {
2561
+ workspace: "{workspaceId}",
2562
+ dbBranchName: "{dbBranch}",
2563
+ region: "{region}",
2564
+ tableName: __privateGet$4(this, _table)
2565
+ },
2566
+ body: { aggs, filter },
2567
+ ...fetchProps
2568
+ });
2569
+ return result;
1430
2570
  });
1431
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1432
- return records.map((item) => initObject(this.db, schema, __privateGet$4(this, _table), item));
1433
2571
  }
1434
2572
  async query(query) {
1435
- const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1436
- if (cacheQuery)
1437
- return new Page(query, cacheQuery.meta, cacheQuery.records);
1438
- const data = query.getQueryOptions();
1439
- const body = {
1440
- filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1441
- sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1442
- page: data.pagination,
1443
- columns: data.columns
1444
- };
1445
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1446
- const { meta, records: objects } = await queryTable({
1447
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1448
- body,
1449
- ...fetchProps
2573
+ return __privateGet$4(this, _trace).call(this, "query", async () => {
2574
+ const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
2575
+ if (cacheQuery)
2576
+ return new Page(query, cacheQuery.meta, cacheQuery.records);
2577
+ const data = query.getQueryOptions();
2578
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2579
+ const { meta, records: objects } = await queryTable({
2580
+ pathParams: {
2581
+ workspace: "{workspaceId}",
2582
+ dbBranchName: "{dbBranch}",
2583
+ region: "{region}",
2584
+ tableName: __privateGet$4(this, _table)
2585
+ },
2586
+ body: {
2587
+ filter: cleanFilter(data.filter),
2588
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2589
+ page: data.pagination,
2590
+ columns: data.columns ?? ["*"]
2591
+ },
2592
+ fetchOptions: data.fetchOptions,
2593
+ ...fetchProps
2594
+ });
2595
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2596
+ const records = objects.map(
2597
+ (record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record, data.columns ?? ["*"])
2598
+ );
2599
+ await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
2600
+ return new Page(query, meta, records);
2601
+ });
2602
+ }
2603
+ async summarizeTable(query, summaries, summariesFilter) {
2604
+ return __privateGet$4(this, _trace).call(this, "summarize", async () => {
2605
+ const data = query.getQueryOptions();
2606
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2607
+ const result = await summarizeTable({
2608
+ pathParams: {
2609
+ workspace: "{workspaceId}",
2610
+ dbBranchName: "{dbBranch}",
2611
+ region: "{region}",
2612
+ tableName: __privateGet$4(this, _table)
2613
+ },
2614
+ body: {
2615
+ filter: cleanFilter(data.filter),
2616
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
2617
+ columns: data.columns,
2618
+ page: data.pagination?.size !== void 0 ? { size: data.pagination?.size } : void 0,
2619
+ summaries,
2620
+ summariesFilter
2621
+ },
2622
+ ...fetchProps
2623
+ });
2624
+ return result;
1450
2625
  });
1451
- const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1452
- const records = objects.map((record) => initObject(this.db, schema, __privateGet$4(this, _table), record));
1453
- await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1454
- return new Page(query, meta, records);
1455
2626
  }
1456
2627
  }
1457
2628
  _table = new WeakMap();
1458
2629
  _getFetchProps = new WeakMap();
2630
+ _db = new WeakMap();
1459
2631
  _cache = new WeakMap();
1460
- _schema$1 = new WeakMap();
2632
+ _schemaTables$2 = new WeakMap();
2633
+ _trace = new WeakMap();
1461
2634
  _insertRecordWithoutId = new WeakSet();
1462
- insertRecordWithoutId_fn = async function(object) {
2635
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1463
2636
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1464
2637
  const record = transformObjectLinks(object);
1465
2638
  const response = await insertRecord({
1466
2639
  pathParams: {
1467
2640
  workspace: "{workspaceId}",
1468
2641
  dbBranchName: "{dbBranch}",
2642
+ region: "{region}",
1469
2643
  tableName: __privateGet$4(this, _table)
1470
2644
  },
2645
+ queryParams: { columns },
1471
2646
  body: record,
1472
2647
  ...fetchProps
1473
2648
  });
1474
- const finalObject = await this.read(response.id);
1475
- if (!finalObject) {
1476
- throw new Error("The server failed to save the record");
1477
- }
1478
- return finalObject;
2649
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2650
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
1479
2651
  };
1480
2652
  _insertRecordWithId = new WeakSet();
1481
- insertRecordWithId_fn = async function(recordId, object) {
2653
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { createOnly, ifVersion }) {
1482
2654
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1483
2655
  const record = transformObjectLinks(object);
1484
2656
  const response = await insertRecordWithID({
1485
2657
  pathParams: {
1486
2658
  workspace: "{workspaceId}",
1487
2659
  dbBranchName: "{dbBranch}",
2660
+ region: "{region}",
1488
2661
  tableName: __privateGet$4(this, _table),
1489
2662
  recordId
1490
2663
  },
1491
2664
  body: record,
1492
- queryParams: { createOnly: true },
2665
+ queryParams: { createOnly, columns, ifVersion },
1493
2666
  ...fetchProps
1494
2667
  });
1495
- const finalObject = await this.read(response.id);
1496
- if (!finalObject) {
1497
- throw new Error("The server failed to save the record");
1498
- }
1499
- return finalObject;
2668
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2669
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
1500
2670
  };
1501
- _bulkInsertTableRecords = new WeakSet();
1502
- bulkInsertTableRecords_fn = async function(objects) {
2671
+ _insertRecords = new WeakSet();
2672
+ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
1503
2673
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1504
- const records = objects.map((object) => transformObjectLinks(object));
1505
- const response = await bulkInsertTableRecords({
1506
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1507
- body: { records },
1508
- ...fetchProps
1509
- });
1510
- const finalObjects = await this.read(response.recordIDs);
1511
- if (finalObjects.length !== objects.length) {
1512
- throw new Error("The server failed to save some records");
2674
+ const chunkedOperations = chunk(
2675
+ objects.map((object) => ({
2676
+ insert: { table: __privateGet$4(this, _table), record: transformObjectLinks(object), createOnly, ifVersion }
2677
+ })),
2678
+ BULK_OPERATION_MAX_SIZE
2679
+ );
2680
+ const ids = [];
2681
+ for (const operations of chunkedOperations) {
2682
+ const { results } = await branchTransaction({
2683
+ pathParams: {
2684
+ workspace: "{workspaceId}",
2685
+ dbBranchName: "{dbBranch}",
2686
+ region: "{region}"
2687
+ },
2688
+ body: { operations },
2689
+ ...fetchProps
2690
+ });
2691
+ for (const result of results) {
2692
+ if (result.operation === "insert") {
2693
+ ids.push(result.id);
2694
+ } else {
2695
+ ids.push(null);
2696
+ }
2697
+ }
1513
2698
  }
1514
- return finalObjects;
2699
+ return ids;
1515
2700
  };
1516
2701
  _updateRecordWithID = new WeakSet();
1517
- updateRecordWithID_fn = async function(recordId, object) {
2702
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
1518
2703
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1519
- const record = transformObjectLinks(object);
1520
- const response = await updateRecordWithID({
1521
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1522
- body: record,
1523
- ...fetchProps
1524
- });
1525
- const item = await this.read(response.id);
1526
- if (!item)
1527
- throw new Error("The server failed to save the record");
1528
- return item;
2704
+ const { id: _id, ...record } = transformObjectLinks(object);
2705
+ try {
2706
+ const response = await updateRecordWithID({
2707
+ pathParams: {
2708
+ workspace: "{workspaceId}",
2709
+ dbBranchName: "{dbBranch}",
2710
+ region: "{region}",
2711
+ tableName: __privateGet$4(this, _table),
2712
+ recordId
2713
+ },
2714
+ queryParams: { columns, ifVersion },
2715
+ body: record,
2716
+ ...fetchProps
2717
+ });
2718
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2719
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2720
+ } catch (e) {
2721
+ if (isObject(e) && e.status === 404) {
2722
+ return null;
2723
+ }
2724
+ throw e;
2725
+ }
2726
+ };
2727
+ _updateRecords = new WeakSet();
2728
+ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2729
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2730
+ const chunkedOperations = chunk(
2731
+ objects.map(({ id, ...object }) => ({
2732
+ update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields: transformObjectLinks(object) }
2733
+ })),
2734
+ BULK_OPERATION_MAX_SIZE
2735
+ );
2736
+ const ids = [];
2737
+ for (const operations of chunkedOperations) {
2738
+ const { results } = await branchTransaction({
2739
+ pathParams: {
2740
+ workspace: "{workspaceId}",
2741
+ dbBranchName: "{dbBranch}",
2742
+ region: "{region}"
2743
+ },
2744
+ body: { operations },
2745
+ ...fetchProps
2746
+ });
2747
+ for (const result of results) {
2748
+ if (result.operation === "update") {
2749
+ ids.push(result.id);
2750
+ } else {
2751
+ ids.push(null);
2752
+ }
2753
+ }
2754
+ }
2755
+ return ids;
1529
2756
  };
1530
2757
  _upsertRecordWithID = new WeakSet();
1531
- upsertRecordWithID_fn = async function(recordId, object) {
2758
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
1532
2759
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1533
2760
  const response = await upsertRecordWithID({
1534
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
2761
+ pathParams: {
2762
+ workspace: "{workspaceId}",
2763
+ dbBranchName: "{dbBranch}",
2764
+ region: "{region}",
2765
+ tableName: __privateGet$4(this, _table),
2766
+ recordId
2767
+ },
2768
+ queryParams: { columns, ifVersion },
1535
2769
  body: object,
1536
2770
  ...fetchProps
1537
2771
  });
1538
- const item = await this.read(response.id);
1539
- if (!item)
1540
- throw new Error("The server failed to save the record");
1541
- return item;
2772
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2773
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
1542
2774
  };
1543
2775
  _deleteRecord = new WeakSet();
1544
- deleteRecord_fn = async function(recordId) {
2776
+ deleteRecord_fn = async function(recordId, columns = ["*"]) {
1545
2777
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1546
- await deleteRecord({
1547
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1548
- ...fetchProps
1549
- });
2778
+ try {
2779
+ const response = await deleteRecord({
2780
+ pathParams: {
2781
+ workspace: "{workspaceId}",
2782
+ dbBranchName: "{dbBranch}",
2783
+ region: "{region}",
2784
+ tableName: __privateGet$4(this, _table),
2785
+ recordId
2786
+ },
2787
+ queryParams: { columns },
2788
+ ...fetchProps
2789
+ });
2790
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2791
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2792
+ } catch (e) {
2793
+ if (isObject(e) && e.status === 404) {
2794
+ return null;
2795
+ }
2796
+ throw e;
2797
+ }
1550
2798
  };
1551
- _invalidateCache = new WeakSet();
1552
- invalidateCache_fn = async function(recordId) {
1553
- await __privateGet$4(this, _cache).delete(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1554
- const cacheItems = await __privateGet$4(this, _cache).getAll();
1555
- const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1556
- for (const [key, value] of queries) {
1557
- const ids = getIds(value);
1558
- if (ids.includes(recordId))
1559
- await __privateGet$4(this, _cache).delete(key);
1560
- }
1561
- };
1562
- _setCacheRecord = new WeakSet();
1563
- setCacheRecord_fn = async function(record) {
1564
- if (!__privateGet$4(this, _cache).cacheRecords)
1565
- return;
1566
- await __privateGet$4(this, _cache).set(`rec_${__privateGet$4(this, _table)}:${record.id}`, record);
1567
- };
1568
- _getCacheRecord = new WeakSet();
1569
- getCacheRecord_fn = async function(recordId) {
1570
- if (!__privateGet$4(this, _cache).cacheRecords)
1571
- return null;
1572
- return __privateGet$4(this, _cache).get(`rec_${__privateGet$4(this, _table)}:${recordId}`);
2799
+ _deleteRecords = new WeakSet();
2800
+ deleteRecords_fn = async function(recordIds) {
2801
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2802
+ const chunkedOperations = chunk(
2803
+ recordIds.map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
2804
+ BULK_OPERATION_MAX_SIZE
2805
+ );
2806
+ for (const operations of chunkedOperations) {
2807
+ await branchTransaction({
2808
+ pathParams: {
2809
+ workspace: "{workspaceId}",
2810
+ dbBranchName: "{dbBranch}",
2811
+ region: "{region}"
2812
+ },
2813
+ body: { operations },
2814
+ ...fetchProps
2815
+ });
2816
+ }
1573
2817
  };
1574
2818
  _setCacheQuery = new WeakSet();
1575
2819
  setCacheQuery_fn = async function(query, meta, records) {
@@ -1587,17 +2831,17 @@ getCacheQuery_fn = async function(query) {
1587
2831
  const hasExpired = result.date.getTime() + ttl < Date.now();
1588
2832
  return hasExpired ? null : result;
1589
2833
  };
1590
- _getSchema$1 = new WeakSet();
1591
- getSchema_fn$1 = async function() {
1592
- if (__privateGet$4(this, _schema$1))
1593
- return __privateGet$4(this, _schema$1);
2834
+ _getSchemaTables$1 = new WeakSet();
2835
+ getSchemaTables_fn$1 = async function() {
2836
+ if (__privateGet$4(this, _schemaTables$2))
2837
+ return __privateGet$4(this, _schemaTables$2);
1594
2838
  const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1595
2839
  const { schema } = await getBranchDetails({
1596
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
2840
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
1597
2841
  ...fetchProps
1598
2842
  });
1599
- __privateSet$3(this, _schema$1, schema);
1600
- return schema;
2843
+ __privateSet$4(this, _schemaTables$2, schema.tables);
2844
+ return schema.tables;
1601
2845
  };
1602
2846
  const transformObjectLinks = (object) => {
1603
2847
  return Object.entries(object).reduce((acc, [key, value]) => {
@@ -1606,14 +2850,16 @@ const transformObjectLinks = (object) => {
1606
2850
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1607
2851
  }, {});
1608
2852
  };
1609
- const initObject = (db, schema, table, object) => {
2853
+ const initObject = (db, schemaTables, table, object, selectedColumns) => {
1610
2854
  const result = {};
1611
2855
  const { xata, ...rest } = object ?? {};
1612
2856
  Object.assign(result, rest);
1613
- const { columns } = schema.tables.find(({ name }) => name === table) ?? {};
2857
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
1614
2858
  if (!columns)
1615
2859
  console.error(`Table ${table} not found in schema`);
1616
2860
  for (const column of columns ?? []) {
2861
+ if (!isValidColumn(selectedColumns, column))
2862
+ continue;
1617
2863
  const value = result[column.name];
1618
2864
  switch (column.type) {
1619
2865
  case "datetime": {
@@ -1630,17 +2876,42 @@ const initObject = (db, schema, table, object) => {
1630
2876
  if (!linkTable) {
1631
2877
  console.error(`Failed to parse link for field ${column.name}`);
1632
2878
  } else if (isObject(value)) {
1633
- result[column.name] = initObject(db, schema, linkTable, value);
2879
+ const selectedLinkColumns = selectedColumns.reduce((acc, item) => {
2880
+ if (item === column.name) {
2881
+ return [...acc, "*"];
2882
+ }
2883
+ if (item.startsWith(`${column.name}.`)) {
2884
+ const [, ...path] = item.split(".");
2885
+ return [...acc, path.join(".")];
2886
+ }
2887
+ return acc;
2888
+ }, []);
2889
+ result[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
2890
+ } else {
2891
+ result[column.name] = null;
1634
2892
  }
1635
2893
  break;
1636
2894
  }
2895
+ default:
2896
+ result[column.name] = value ?? null;
2897
+ if (column.notNull === true && value === null) {
2898
+ console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
2899
+ }
2900
+ break;
1637
2901
  }
1638
2902
  }
1639
- result.read = function() {
1640
- return db[table].read(result["id"]);
2903
+ result.read = function(columns2) {
2904
+ return db[table].read(result["id"], columns2);
1641
2905
  };
1642
- result.update = function(data) {
1643
- return db[table].update(result["id"], data);
2906
+ result.update = function(data, b, c) {
2907
+ const columns2 = isStringArray(b) ? b : ["*"];
2908
+ const ifVersion = parseIfVersion(b, c);
2909
+ return db[table].update(result["id"], data, columns2, { ifVersion });
2910
+ };
2911
+ result.replace = function(data, b, c) {
2912
+ const columns2 = isStringArray(b) ? b : ["*"];
2913
+ const ifVersion = parseIfVersion(b, c);
2914
+ return db[table].createOrReplace(result["id"], data, columns2, { ifVersion });
1644
2915
  };
1645
2916
  result.delete = function() {
1646
2917
  return db[table].delete(result["id"]);
@@ -1648,20 +2919,35 @@ const initObject = (db, schema, table, object) => {
1648
2919
  result.getMetadata = function() {
1649
2920
  return xata;
1650
2921
  };
1651
- for (const prop of ["read", "update", "delete", "getMetadata"]) {
2922
+ for (const prop of ["read", "update", "replace", "delete", "getMetadata"]) {
1652
2923
  Object.defineProperty(result, prop, { enumerable: false });
1653
2924
  }
1654
2925
  Object.freeze(result);
1655
2926
  return result;
1656
2927
  };
1657
- function getIds(value) {
1658
- if (Array.isArray(value)) {
1659
- return value.map((item) => getIds(item)).flat();
2928
+ function extractId(value) {
2929
+ if (isString(value))
2930
+ return value;
2931
+ if (isObject(value) && isString(value.id))
2932
+ return value.id;
2933
+ return void 0;
2934
+ }
2935
+ function isValidColumn(columns, column) {
2936
+ if (columns.includes("*"))
2937
+ return true;
2938
+ if (column.type === "link") {
2939
+ const linkColumns = columns.filter((item) => item.startsWith(column.name));
2940
+ return linkColumns.length > 0;
2941
+ }
2942
+ return columns.includes(column.name);
2943
+ }
2944
+ function parseIfVersion(...args) {
2945
+ for (const arg of args) {
2946
+ if (isObject(arg) && isNumber(arg.ifVersion)) {
2947
+ return arg.ifVersion;
2948
+ }
1660
2949
  }
1661
- if (!isObject(value))
1662
- return [];
1663
- const nestedIds = Object.values(value).map((item) => getIds(item)).flat();
1664
- return isString(value.id) ? [value.id, ...nestedIds] : nestedIds;
2950
+ return void 0;
1665
2951
  }
1666
2952
 
1667
2953
  var __accessCheck$3 = (obj, member, msg) => {
@@ -1677,7 +2963,7 @@ var __privateAdd$3 = (obj, member, value) => {
1677
2963
  throw TypeError("Cannot add the same private member more than once");
1678
2964
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1679
2965
  };
1680
- var __privateSet$2 = (obj, member, value, setter) => {
2966
+ var __privateSet$3 = (obj, member, value, setter) => {
1681
2967
  __accessCheck$3(obj, member, "write to private field");
1682
2968
  setter ? setter.call(obj, value) : member.set(obj, value);
1683
2969
  return value;
@@ -1686,9 +2972,8 @@ var _map;
1686
2972
  class SimpleCache {
1687
2973
  constructor(options = {}) {
1688
2974
  __privateAdd$3(this, _map, void 0);
1689
- __privateSet$2(this, _map, /* @__PURE__ */ new Map());
2975
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1690
2976
  this.capacity = options.max ?? 500;
1691
- this.cacheRecords = options.cacheRecords ?? true;
1692
2977
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1693
2978
  }
1694
2979
  async getAll() {
@@ -1714,18 +2999,25 @@ class SimpleCache {
1714
2999
  }
1715
3000
  _map = new WeakMap();
1716
3001
 
1717
- const gt = (value) => ({ $gt: value });
1718
- const ge = (value) => ({ $ge: value });
1719
- const gte = (value) => ({ $ge: value });
1720
- const lt = (value) => ({ $lt: value });
1721
- const lte = (value) => ({ $le: value });
1722
- const le = (value) => ({ $le: value });
3002
+ const greaterThan = (value) => ({ $gt: value });
3003
+ const gt = greaterThan;
3004
+ const greaterThanEquals = (value) => ({ $ge: value });
3005
+ const greaterEquals = greaterThanEquals;
3006
+ const gte = greaterThanEquals;
3007
+ const ge = greaterThanEquals;
3008
+ const lessThan = (value) => ({ $lt: value });
3009
+ const lt = lessThan;
3010
+ const lessThanEquals = (value) => ({ $le: value });
3011
+ const lessEquals = lessThanEquals;
3012
+ const lte = lessThanEquals;
3013
+ const le = lessThanEquals;
1723
3014
  const exists = (column) => ({ $exists: column });
1724
3015
  const notExists = (column) => ({ $notExists: column });
1725
3016
  const startsWith = (value) => ({ $startsWith: value });
1726
3017
  const endsWith = (value) => ({ $endsWith: value });
1727
3018
  const pattern = (value) => ({ $pattern: value });
1728
3019
  const is = (value) => ({ $is: value });
3020
+ const equals = is;
1729
3021
  const isNot = (value) => ({ $isNot: value });
1730
3022
  const contains = (value) => ({ $contains: value });
1731
3023
  const includes = (value) => ({ $includes: value });
@@ -1746,31 +3038,42 @@ var __privateAdd$2 = (obj, member, value) => {
1746
3038
  throw TypeError("Cannot add the same private member more than once");
1747
3039
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1748
3040
  };
1749
- var _tables;
3041
+ var __privateSet$2 = (obj, member, value, setter) => {
3042
+ __accessCheck$2(obj, member, "write to private field");
3043
+ setter ? setter.call(obj, value) : member.set(obj, value);
3044
+ return value;
3045
+ };
3046
+ var _tables, _schemaTables$1;
1750
3047
  class SchemaPlugin extends XataPlugin {
1751
- constructor(tableNames) {
3048
+ constructor(schemaTables) {
1752
3049
  super();
1753
- this.tableNames = tableNames;
1754
3050
  __privateAdd$2(this, _tables, {});
3051
+ __privateAdd$2(this, _schemaTables$1, void 0);
3052
+ __privateSet$2(this, _schemaTables$1, schemaTables);
1755
3053
  }
1756
3054
  build(pluginOptions) {
1757
- const db = new Proxy({}, {
1758
- get: (_target, table) => {
1759
- if (!isString(table))
1760
- throw new Error("Invalid table name");
1761
- if (__privateGet$2(this, _tables)[table] === void 0) {
1762
- __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table });
3055
+ const db = new Proxy(
3056
+ {},
3057
+ {
3058
+ get: (_target, table) => {
3059
+ if (!isString(table))
3060
+ throw new Error("Invalid table name");
3061
+ if (__privateGet$2(this, _tables)[table] === void 0) {
3062
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
3063
+ }
3064
+ return __privateGet$2(this, _tables)[table];
1763
3065
  }
1764
- return __privateGet$2(this, _tables)[table];
1765
3066
  }
1766
- });
1767
- for (const table of this.tableNames ?? []) {
1768
- db[table] = new RestRepository({ db, pluginOptions, table });
3067
+ );
3068
+ const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
3069
+ for (const table of tableNames) {
3070
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1769
3071
  }
1770
3072
  return db;
1771
3073
  }
1772
3074
  }
1773
3075
  _tables = new WeakMap();
3076
+ _schemaTables$1 = new WeakMap();
1774
3077
 
1775
3078
  var __accessCheck$1 = (obj, member, msg) => {
1776
3079
  if (!member.has(obj))
@@ -1794,82 +3097,77 @@ var __privateMethod$1 = (obj, member, method) => {
1794
3097
  __accessCheck$1(obj, member, "access private method");
1795
3098
  return method;
1796
3099
  };
1797
- var _schema, _search, search_fn, _getSchema, getSchema_fn;
3100
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1798
3101
  class SearchPlugin extends XataPlugin {
1799
- constructor(db) {
3102
+ constructor(db, schemaTables) {
1800
3103
  super();
1801
3104
  this.db = db;
1802
3105
  __privateAdd$1(this, _search);
1803
- __privateAdd$1(this, _getSchema);
1804
- __privateAdd$1(this, _schema, void 0);
3106
+ __privateAdd$1(this, _getSchemaTables);
3107
+ __privateAdd$1(this, _schemaTables, void 0);
3108
+ __privateSet$1(this, _schemaTables, schemaTables);
1805
3109
  }
1806
3110
  build({ getFetchProps }) {
1807
3111
  return {
1808
3112
  all: async (query, options = {}) => {
1809
3113
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1810
- const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
3114
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1811
3115
  return records.map((record) => {
1812
3116
  const { table = "orphan" } = record.xata;
1813
- return { table, record: initObject(this.db, schema, table, record) };
3117
+ return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
1814
3118
  });
1815
3119
  },
1816
3120
  byTable: async (query, options = {}) => {
1817
3121
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1818
- const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
3122
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1819
3123
  return records.reduce((acc, record) => {
1820
3124
  const { table = "orphan" } = record.xata;
1821
3125
  const items = acc[table] ?? [];
1822
- const item = initObject(this.db, schema, table, record);
3126
+ const item = initObject(this.db, schemaTables, table, record, ["*"]);
1823
3127
  return { ...acc, [table]: [...items, item] };
1824
3128
  }, {});
1825
3129
  }
1826
3130
  };
1827
3131
  }
1828
3132
  }
1829
- _schema = new WeakMap();
3133
+ _schemaTables = new WeakMap();
1830
3134
  _search = new WeakSet();
1831
3135
  search_fn = async function(query, options, getFetchProps) {
1832
3136
  const fetchProps = await getFetchProps();
1833
- const { tables, fuzziness, highlight } = options ?? {};
3137
+ const { tables, fuzziness, highlight, prefix } = options ?? {};
1834
3138
  const { records } = await searchBranch({
1835
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1836
- body: { tables, query, fuzziness, highlight },
3139
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3140
+ body: { tables, query, fuzziness, prefix, highlight },
1837
3141
  ...fetchProps
1838
3142
  });
1839
3143
  return records;
1840
3144
  };
1841
- _getSchema = new WeakSet();
1842
- getSchema_fn = async function(getFetchProps) {
1843
- if (__privateGet$1(this, _schema))
1844
- return __privateGet$1(this, _schema);
3145
+ _getSchemaTables = new WeakSet();
3146
+ getSchemaTables_fn = async function(getFetchProps) {
3147
+ if (__privateGet$1(this, _schemaTables))
3148
+ return __privateGet$1(this, _schemaTables);
1845
3149
  const fetchProps = await getFetchProps();
1846
3150
  const { schema } = await getBranchDetails({
1847
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
3151
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
1848
3152
  ...fetchProps
1849
3153
  });
1850
- __privateSet$1(this, _schema, schema);
1851
- return schema;
3154
+ __privateSet$1(this, _schemaTables, schema.tables);
3155
+ return schema.tables;
1852
3156
  };
1853
3157
 
1854
3158
  const isBranchStrategyBuilder = (strategy) => {
1855
3159
  return typeof strategy === "function";
1856
3160
  };
1857
3161
 
1858
- const envBranchNames = [
1859
- "XATA_BRANCH",
1860
- "VERCEL_GIT_COMMIT_REF",
1861
- "CF_PAGES_BRANCH",
1862
- "BRANCH"
1863
- ];
1864
3162
  async function getCurrentBranchName(options) {
1865
- const env = getBranchByEnvVariable();
1866
- if (env) {
1867
- const details = await getDatabaseBranch(env, options);
3163
+ const { branch, envBranch } = getEnvironment();
3164
+ if (branch) {
3165
+ const details = await getDatabaseBranch(branch, options);
1868
3166
  if (details)
1869
- return env;
1870
- console.warn(`Branch ${env} not found in Xata. Ignoring...`);
3167
+ return branch;
3168
+ console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
1871
3169
  }
1872
- const gitBranch = await getGitBranch();
3170
+ const gitBranch = envBranch || await getGitBranch();
1873
3171
  return resolveXataBranch(gitBranch, options);
1874
3172
  }
1875
3173
  async function getCurrentBranchDetails(options) {
@@ -1880,18 +3178,27 @@ async function resolveXataBranch(gitBranch, options) {
1880
3178
  const databaseURL = options?.databaseURL || getDatabaseURL();
1881
3179
  const apiKey = options?.apiKey || getAPIKey();
1882
3180
  if (!databaseURL)
1883
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
3181
+ throw new Error(
3182
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
3183
+ );
1884
3184
  if (!apiKey)
1885
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
3185
+ throw new Error(
3186
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
3187
+ );
1886
3188
  const [protocol, , host, , dbName] = databaseURL.split("/");
1887
- const [workspace] = host.split(".");
3189
+ const urlParts = parseWorkspacesUrlParts(host);
3190
+ if (!urlParts)
3191
+ throw new Error(`Unable to parse workspace and region: ${databaseURL}`);
3192
+ const { workspace, region } = urlParts;
3193
+ const { fallbackBranch } = getEnvironment();
1888
3194
  const { branch } = await resolveBranch({
1889
3195
  apiKey,
1890
3196
  apiUrl: databaseURL,
1891
3197
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1892
3198
  workspacesApiUrl: `${protocol}//${host}`,
1893
- pathParams: { dbName, workspace },
1894
- queryParams: { gitBranch, fallbackBranch: getEnvVariable("XATA_FALLBACK_BRANCH") }
3199
+ pathParams: { dbName, workspace, region },
3200
+ queryParams: { gitBranch, fallbackBranch },
3201
+ trace: defaultTrace
1895
3202
  });
1896
3203
  return branch;
1897
3204
  }
@@ -1899,19 +3206,26 @@ async function getDatabaseBranch(branch, options) {
1899
3206
  const databaseURL = options?.databaseURL || getDatabaseURL();
1900
3207
  const apiKey = options?.apiKey || getAPIKey();
1901
3208
  if (!databaseURL)
1902
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
3209
+ throw new Error(
3210
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
3211
+ );
1903
3212
  if (!apiKey)
1904
- throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
3213
+ throw new Error(
3214
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
3215
+ );
1905
3216
  const [protocol, , host, , database] = databaseURL.split("/");
1906
- const [workspace] = host.split(".");
1907
- const dbBranchName = `${database}:${branch}`;
3217
+ const urlParts = parseWorkspacesUrlParts(host);
3218
+ if (!urlParts)
3219
+ throw new Error(`Unable to parse workspace and region: ${databaseURL}`);
3220
+ const { workspace, region } = urlParts;
1908
3221
  try {
1909
3222
  return await getBranchDetails({
1910
3223
  apiKey,
1911
3224
  apiUrl: databaseURL,
1912
3225
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1913
3226
  workspacesApiUrl: `${protocol}//${host}`,
1914
- pathParams: { dbBranchName, workspace }
3227
+ pathParams: { dbBranchName: `${database}:${branch}`, workspace, region },
3228
+ trace: defaultTrace
1915
3229
  });
1916
3230
  } catch (err) {
1917
3231
  if (isObject(err) && err.status === 404)
@@ -1919,21 +3233,10 @@ async function getDatabaseBranch(branch, options) {
1919
3233
  throw err;
1920
3234
  }
1921
3235
  }
1922
- function getBranchByEnvVariable() {
1923
- for (const name of envBranchNames) {
1924
- const value = getEnvVariable(name);
1925
- if (value) {
1926
- return value;
1927
- }
1928
- }
1929
- try {
1930
- return XATA_BRANCH;
1931
- } catch (err) {
1932
- }
1933
- }
1934
3236
  function getDatabaseURL() {
1935
3237
  try {
1936
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
3238
+ const { databaseURL } = getEnvironment();
3239
+ return databaseURL;
1937
3240
  } catch (err) {
1938
3241
  return void 0;
1939
3242
  }
@@ -1962,20 +3265,23 @@ var __privateMethod = (obj, member, method) => {
1962
3265
  return method;
1963
3266
  };
1964
3267
  const buildClient = (plugins) => {
1965
- var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
3268
+ var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1966
3269
  return _a = class {
1967
- constructor(options = {}, tables) {
3270
+ constructor(options = {}, schemaTables) {
1968
3271
  __privateAdd(this, _parseOptions);
1969
3272
  __privateAdd(this, _getFetchProps);
1970
3273
  __privateAdd(this, _evaluateBranch);
1971
3274
  __privateAdd(this, _branch, void 0);
3275
+ __privateAdd(this, _options, void 0);
1972
3276
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
3277
+ __privateSet(this, _options, safeOptions);
1973
3278
  const pluginOptions = {
1974
3279
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1975
- cache: safeOptions.cache
3280
+ cache: safeOptions.cache,
3281
+ trace: safeOptions.trace
1976
3282
  };
1977
- const db = new SchemaPlugin(tables).build(pluginOptions);
1978
- const search = new SearchPlugin(db).build(pluginOptions);
3283
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
3284
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1979
3285
  this.db = db;
1980
3286
  this.search = search;
1981
3287
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
@@ -1991,22 +3297,33 @@ const buildClient = (plugins) => {
1991
3297
  }
1992
3298
  }
1993
3299
  }
1994
- }, _branch = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3300
+ async getConfig() {
3301
+ const databaseURL = __privateGet(this, _options).databaseURL;
3302
+ const branch = await __privateGet(this, _options).branch();
3303
+ return { databaseURL, branch };
3304
+ }
3305
+ }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3306
+ const enableBrowser = options?.enableBrowser ?? getEnableBrowserVariable() ?? false;
3307
+ const isBrowser = typeof window !== "undefined";
3308
+ if (isBrowser && !enableBrowser) {
3309
+ throw new Error(
3310
+ "You are trying to use Xata from the browser, which is potentially a non-secure environment. If you understand the security concerns, such as leaking your credentials, pass `enableBrowser: true` to the client options to remove this error."
3311
+ );
3312
+ }
1995
3313
  const fetch = getFetchImplementation(options?.fetch);
1996
3314
  const databaseURL = options?.databaseURL || getDatabaseURL();
1997
3315
  const apiKey = options?.apiKey || getAPIKey();
1998
- const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
3316
+ const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
3317
+ const trace = options?.trace ?? defaultTrace;
1999
3318
  const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
2000
- if (!databaseURL || !apiKey) {
2001
- throw new Error("Options databaseURL and apiKey are required");
3319
+ if (!apiKey) {
3320
+ throw new Error("Option apiKey is required");
2002
3321
  }
2003
- return { fetch, databaseURL, apiKey, branch, cache };
2004
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
2005
- fetch,
2006
- apiKey,
2007
- databaseURL,
2008
- branch
2009
- }) {
3322
+ if (!databaseURL) {
3323
+ throw new Error("Option databaseURL is required");
3324
+ }
3325
+ return { fetch, databaseURL, apiKey, branch, cache, trace, clientID: generateUUID(), enableBrowser };
3326
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace, clientID }) {
2010
3327
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
2011
3328
  if (!branchValue)
2012
3329
  throw new Error("Unable to resolve branch value");
@@ -2016,9 +3333,11 @@ const buildClient = (plugins) => {
2016
3333
  apiUrl: "",
2017
3334
  workspacesApiUrl: (path, params) => {
2018
3335
  const hasBranch = params.dbBranchName ?? params.branch;
2019
- const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branchValue}` : "");
3336
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branchValue}` : "");
2020
3337
  return databaseURL + newPath;
2021
- }
3338
+ },
3339
+ trace,
3340
+ clientID
2022
3341
  };
2023
3342
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
2024
3343
  if (__privateGet(this, _branch))
@@ -2041,6 +3360,88 @@ const buildClient = (plugins) => {
2041
3360
  class BaseClient extends buildClient() {
2042
3361
  }
2043
3362
 
3363
+ const META = "__";
3364
+ const VALUE = "___";
3365
+ class Serializer {
3366
+ constructor() {
3367
+ this.classes = {};
3368
+ }
3369
+ add(clazz) {
3370
+ this.classes[clazz.name] = clazz;
3371
+ }
3372
+ toJSON(data) {
3373
+ function visit(obj) {
3374
+ if (Array.isArray(obj))
3375
+ return obj.map(visit);
3376
+ const type = typeof obj;
3377
+ if (type === "undefined")
3378
+ return { [META]: "undefined" };
3379
+ if (type === "bigint")
3380
+ return { [META]: "bigint", [VALUE]: obj.toString() };
3381
+ if (obj === null || type !== "object")
3382
+ return obj;
3383
+ const constructor = obj.constructor;
3384
+ const o = { [META]: constructor.name };
3385
+ for (const [key, value] of Object.entries(obj)) {
3386
+ o[key] = visit(value);
3387
+ }
3388
+ if (constructor === Date)
3389
+ o[VALUE] = obj.toISOString();
3390
+ if (constructor === Map)
3391
+ o[VALUE] = Object.fromEntries(obj);
3392
+ if (constructor === Set)
3393
+ o[VALUE] = [...obj];
3394
+ return o;
3395
+ }
3396
+ return JSON.stringify(visit(data));
3397
+ }
3398
+ fromJSON(json) {
3399
+ return JSON.parse(json, (key, value) => {
3400
+ if (value && typeof value === "object" && !Array.isArray(value)) {
3401
+ const { [META]: clazz, [VALUE]: val, ...rest } = value;
3402
+ const constructor = this.classes[clazz];
3403
+ if (constructor) {
3404
+ return Object.assign(Object.create(constructor.prototype), rest);
3405
+ }
3406
+ if (clazz === "Date")
3407
+ return new Date(val);
3408
+ if (clazz === "Set")
3409
+ return new Set(val);
3410
+ if (clazz === "Map")
3411
+ return new Map(Object.entries(val));
3412
+ if (clazz === "bigint")
3413
+ return BigInt(val);
3414
+ if (clazz === "undefined")
3415
+ return void 0;
3416
+ return rest;
3417
+ }
3418
+ return value;
3419
+ });
3420
+ }
3421
+ }
3422
+ const defaultSerializer = new Serializer();
3423
+ const serialize = (data) => {
3424
+ return defaultSerializer.toJSON(data);
3425
+ };
3426
+ const deserialize = (json) => {
3427
+ return defaultSerializer.fromJSON(json);
3428
+ };
3429
+
3430
+ function buildWorkerRunner(config) {
3431
+ return function xataWorker(name, _worker) {
3432
+ return async (...args) => {
3433
+ const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
3434
+ const result = await fetch(url, {
3435
+ method: "POST",
3436
+ headers: { "Content-Type": "application/json" },
3437
+ body: serialize({ args })
3438
+ });
3439
+ const text = await result.text();
3440
+ return deserialize(text);
3441
+ };
3442
+ };
3443
+ }
3444
+
2044
3445
  class XataError extends Error {
2045
3446
  constructor(message, status) {
2046
3447
  super(message);
@@ -2048,5 +3449,5 @@ class XataError extends Error {
2048
3449
  }
2049
3450
  }
2050
3451
 
2051
- export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, buildClient, bulkInsertTableRecords, cancelWorkspaceMemberInvite, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, endsWith, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseURL, getGitBranchesMapping, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isIdentifiable, isNot, isXataRecord, le, lt, lte, notExists, operationsByTag, pattern, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberRole, upsertRecordWithID };
3452
+ export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, Serializer, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, aggregateTable, applyBranchSchemaEdit, branchTransaction, buildClient, buildWorkerRunner, bulkInsertTableRecords, cancelWorkspaceMemberInvite, compareBranchSchemas, compareBranchWithUserSchema, compareMigrationRequest, contains, createBranch, createDatabase, createMigrationRequest, createTable, createUserAPIKey, createWorkspace, dEPRECATEDcreateDatabase, dEPRECATEDdeleteDatabase, dEPRECATEDgetDatabaseList, dEPRECATEDgetDatabaseMetadata, dEPRECATEDupdateDatabaseMetadata, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, deserialize, endsWith, equals, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchSchemaHistory, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseMetadata, getDatabaseURL, getGitBranchesMapping, getHostUrl, getMigrationRequest, getMigrationRequestIsMerged, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, greaterEquals, greaterThan, greaterThanEquals, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isHostProviderAlias, isHostProviderBuilder, isIdentifiable, isNot, isXataRecord, le, lessEquals, lessThan, lessThanEquals, listMigrationRequestsCommits, listRegions, lt, lte, mergeMigrationRequest, notExists, operationsByTag, parseProviderString, parseWorkspacesUrlParts, pattern, previewBranchSchemaEdit, queryMigrationRequests, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, serialize, setTableSchema, startsWith, summarizeTable, updateBranchMetadata, updateBranchSchema, updateColumn, updateDatabaseMetadata, updateMigrationRequest, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID };
2052
3453
  //# sourceMappingURL=index.mjs.map