@xata.io/client 0.0.0-alpha.vfde9dcf → 0.0.0-alpha.vfe07d64

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