@xata.io/client 0.0.0-alpha.vf2043e7 → 0.0.0-alpha.vf217b0e

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