@xata.io/client 0.0.0-alpha.vf3081bb → 0.0.0-alpha.vf331c3f

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