@xata.io/client 0.0.0-alpha.vf7b5320 → 0.0.0-alpha.vf7b8bd4

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