@xata.io/client 0.0.0-alpha.vfbde008 → 0.0.0-alpha.vfc037e5fcc7638c56843d5834ef8a7d04c8d451b

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