@xata.io/client 0.0.0-alpha.vf9d4e41 → 0.0.0-alpha.vfa22996

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