@xata.io/client 0.0.0-alpha.vf9f8d99 → 0.0.0-alpha.vfa1407e

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.cjs CHANGED
@@ -20,7 +20,8 @@ const TraceAttributes = {
20
20
  HTTP_METHOD: "http.method",
21
21
  HTTP_URL: "http.url",
22
22
  HTTP_ROUTE: "http.route",
23
- HTTP_TARGET: "http.target"
23
+ HTTP_TARGET: "http.target",
24
+ CLOUDFLARE_RAY_ID: "cf.ray"
24
25
  };
25
26
 
26
27
  function notEmpty(value) {
@@ -29,8 +30,18 @@ function notEmpty(value) {
29
30
  function compact(arr) {
30
31
  return arr.filter(notEmpty);
31
32
  }
33
+ function compactObject(obj) {
34
+ return Object.fromEntries(Object.entries(obj).filter(([, value]) => notEmpty(value)));
35
+ }
36
+ function isBlob(value) {
37
+ try {
38
+ return value instanceof Blob;
39
+ } catch (error) {
40
+ return false;
41
+ }
42
+ }
32
43
  function isObject(value) {
33
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
44
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date) && !isBlob(value);
34
45
  }
35
46
  function isDefined(value) {
36
47
  return value !== null && value !== void 0;
@@ -85,6 +96,27 @@ function chunk(array, chunkSize) {
85
96
  async function timeout(ms) {
86
97
  return new Promise((resolve) => setTimeout(resolve, ms));
87
98
  }
99
+ function timeoutWithCancel(ms) {
100
+ let timeoutId;
101
+ const promise = new Promise((resolve) => {
102
+ timeoutId = setTimeout(() => {
103
+ resolve();
104
+ }, ms);
105
+ });
106
+ return {
107
+ cancel: () => clearTimeout(timeoutId),
108
+ promise
109
+ };
110
+ }
111
+ function promiseMap(inputValues, mapper) {
112
+ const reducer = (acc$, inputValue) => acc$.then(
113
+ (acc) => mapper(inputValue).then((result) => {
114
+ acc.push(result);
115
+ return acc;
116
+ })
117
+ );
118
+ return inputValues.reduce(reducer, Promise.resolve([]));
119
+ }
88
120
 
89
121
  function getEnvironment() {
90
122
  try {
@@ -93,8 +125,10 @@ function getEnvironment() {
93
125
  apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
94
126
  databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
95
127
  branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
96
- envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
97
- fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
128
+ deployPreview: process.env.XATA_PREVIEW,
129
+ deployPreviewBranch: process.env.XATA_PREVIEW_BRANCH,
130
+ vercelGitCommitRef: process.env.VERCEL_GIT_COMMIT_REF,
131
+ vercelGitRepoOwner: process.env.VERCEL_GIT_REPO_OWNER
98
132
  };
99
133
  }
100
134
  } catch (err) {
@@ -105,8 +139,10 @@ function getEnvironment() {
105
139
  apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
106
140
  databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
107
141
  branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
108
- envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
109
- fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
142
+ deployPreview: Deno.env.get("XATA_PREVIEW"),
143
+ deployPreviewBranch: Deno.env.get("XATA_PREVIEW_BRANCH"),
144
+ vercelGitCommitRef: Deno.env.get("VERCEL_GIT_COMMIT_REF"),
145
+ vercelGitRepoOwner: Deno.env.get("VERCEL_GIT_REPO_OWNER")
110
146
  };
111
147
  }
112
148
  } catch (err) {
@@ -115,8 +151,10 @@ function getEnvironment() {
115
151
  apiKey: getGlobalApiKey(),
116
152
  databaseURL: getGlobalDatabaseURL(),
117
153
  branch: getGlobalBranch(),
118
- envBranch: void 0,
119
- fallbackBranch: getGlobalFallbackBranch()
154
+ deployPreview: void 0,
155
+ deployPreviewBranch: void 0,
156
+ vercelGitCommitRef: void 0,
157
+ vercelGitRepoOwner: void 0
120
158
  };
121
159
  }
122
160
  function getEnableBrowserVariable() {
@@ -159,39 +197,59 @@ function getGlobalBranch() {
159
197
  return void 0;
160
198
  }
161
199
  }
162
- function getGlobalFallbackBranch() {
200
+ function getDatabaseURL() {
163
201
  try {
164
- return XATA_FALLBACK_BRANCH;
202
+ const { databaseURL } = getEnvironment();
203
+ return databaseURL;
165
204
  } catch (err) {
166
205
  return void 0;
167
206
  }
168
207
  }
169
- function getDatabaseURL() {
208
+ function getAPIKey() {
170
209
  try {
171
- const { databaseURL } = getEnvironment();
172
- return databaseURL;
210
+ const { apiKey } = getEnvironment();
211
+ return apiKey;
173
212
  } catch (err) {
174
213
  return void 0;
175
214
  }
176
215
  }
177
216
  function getBranch() {
178
217
  try {
179
- const { branch, envBranch } = getEnvironment();
180
- return branch ?? envBranch;
218
+ const { branch } = getEnvironment();
219
+ return branch;
181
220
  } catch (err) {
182
221
  return void 0;
183
222
  }
184
223
  }
185
-
186
- function getAPIKey() {
224
+ function buildPreviewBranchName({ org, branch }) {
225
+ return `preview-${org}-${branch}`;
226
+ }
227
+ function getPreviewBranch() {
187
228
  try {
188
- const { apiKey } = getEnvironment();
189
- return apiKey;
229
+ const { deployPreview, deployPreviewBranch, vercelGitCommitRef, vercelGitRepoOwner } = getEnvironment();
230
+ if (deployPreviewBranch)
231
+ return deployPreviewBranch;
232
+ switch (deployPreview) {
233
+ case "vercel": {
234
+ if (!vercelGitCommitRef || !vercelGitRepoOwner) {
235
+ console.warn("XATA_PREVIEW=vercel but VERCEL_GIT_COMMIT_REF or VERCEL_GIT_REPO_OWNER is not valid");
236
+ return void 0;
237
+ }
238
+ return buildPreviewBranchName({ org: vercelGitRepoOwner, branch: vercelGitCommitRef });
239
+ }
240
+ }
241
+ return void 0;
190
242
  } catch (err) {
191
243
  return void 0;
192
244
  }
193
245
  }
194
246
 
247
+ var __defProp$8 = Object.defineProperty;
248
+ var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
249
+ var __publicField$8 = (obj, key, value) => {
250
+ __defNormalProp$8(obj, typeof key !== "symbol" ? key + "" : key, value);
251
+ return value;
252
+ };
195
253
  var __accessCheck$8 = (obj, member, msg) => {
196
254
  if (!member.has(obj))
197
255
  throw TypeError("Cannot " + msg);
@@ -215,13 +273,13 @@ var __privateMethod$4 = (obj, member, method) => {
215
273
  return method;
216
274
  };
217
275
  var _fetch, _queue, _concurrency, _enqueue, enqueue_fn;
276
+ const REQUEST_TIMEOUT = 5 * 60 * 1e3;
218
277
  function getFetchImplementation(userFetch) {
219
278
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
220
- const fetchImpl = userFetch ?? globalFetch;
279
+ const globalThisFetch = typeof globalThis !== "undefined" ? globalThis.fetch : void 0;
280
+ const fetchImpl = userFetch ?? globalFetch ?? globalThisFetch;
221
281
  if (!fetchImpl) {
222
- throw new Error(
223
- `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
224
- );
282
+ throw new Error(`Couldn't find a global \`fetch\`. Pass a fetch implementation explicitly.`);
225
283
  }
226
284
  return fetchImpl;
227
285
  }
@@ -231,6 +289,8 @@ class ApiRequestPool {
231
289
  __privateAdd$8(this, _fetch, void 0);
232
290
  __privateAdd$8(this, _queue, void 0);
233
291
  __privateAdd$8(this, _concurrency, void 0);
292
+ __publicField$8(this, "running");
293
+ __publicField$8(this, "started");
234
294
  __privateSet$8(this, _queue, []);
235
295
  __privateSet$8(this, _concurrency, concurrency);
236
296
  this.running = 0;
@@ -246,18 +306,22 @@ class ApiRequestPool {
246
306
  return __privateGet$8(this, _fetch);
247
307
  }
248
308
  request(url, options) {
249
- const start = new Date();
250
- const fetch2 = this.getFetch();
309
+ const start = /* @__PURE__ */ new Date();
310
+ const fetchImpl = this.getFetch();
251
311
  const runRequest = async (stalled = false) => {
252
- const response = await fetch2(url, options);
312
+ const { promise, cancel } = timeoutWithCancel(REQUEST_TIMEOUT);
313
+ const response = await Promise.race([fetchImpl(url, options), promise.then(() => null)]).finally(cancel);
314
+ if (!response) {
315
+ throw new Error("Request timed out");
316
+ }
253
317
  if (response.status === 429) {
254
318
  const rateLimitReset = parseNumber(response.headers?.get("x-ratelimit-reset")) ?? 1;
255
319
  await timeout(rateLimitReset * 1e3);
256
320
  return await runRequest(true);
257
321
  }
258
322
  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`);
323
+ const stalledTime = (/* @__PURE__ */ new Date()).getTime() - start.getTime();
324
+ console.warn(`A request to Xata hit branch rate limits, was retried and stalled for ${stalledTime}ms`);
261
325
  }
262
326
  return response;
263
327
  };
@@ -299,16 +363,199 @@ function generateUUID() {
299
363
  });
300
364
  }
301
365
 
302
- const VERSION = "0.22.3";
366
+ async function getBytes(stream, onChunk) {
367
+ const reader = stream.getReader();
368
+ let result;
369
+ while (!(result = await reader.read()).done) {
370
+ onChunk(result.value);
371
+ }
372
+ }
373
+ function getLines(onLine) {
374
+ let buffer;
375
+ let position;
376
+ let fieldLength;
377
+ let discardTrailingNewline = false;
378
+ return function onChunk(arr) {
379
+ if (buffer === void 0) {
380
+ buffer = arr;
381
+ position = 0;
382
+ fieldLength = -1;
383
+ } else {
384
+ buffer = concat(buffer, arr);
385
+ }
386
+ const bufLength = buffer.length;
387
+ let lineStart = 0;
388
+ while (position < bufLength) {
389
+ if (discardTrailingNewline) {
390
+ if (buffer[position] === 10 /* NewLine */) {
391
+ lineStart = ++position;
392
+ }
393
+ discardTrailingNewline = false;
394
+ }
395
+ let lineEnd = -1;
396
+ for (; position < bufLength && lineEnd === -1; ++position) {
397
+ switch (buffer[position]) {
398
+ case 58 /* Colon */:
399
+ if (fieldLength === -1) {
400
+ fieldLength = position - lineStart;
401
+ }
402
+ break;
403
+ case 13 /* CarriageReturn */:
404
+ discardTrailingNewline = true;
405
+ case 10 /* NewLine */:
406
+ lineEnd = position;
407
+ break;
408
+ }
409
+ }
410
+ if (lineEnd === -1) {
411
+ break;
412
+ }
413
+ onLine(buffer.subarray(lineStart, lineEnd), fieldLength);
414
+ lineStart = position;
415
+ fieldLength = -1;
416
+ }
417
+ if (lineStart === bufLength) {
418
+ buffer = void 0;
419
+ } else if (lineStart !== 0) {
420
+ buffer = buffer.subarray(lineStart);
421
+ position -= lineStart;
422
+ }
423
+ };
424
+ }
425
+ function getMessages(onId, onRetry, onMessage) {
426
+ let message = newMessage();
427
+ const decoder = new TextDecoder();
428
+ return function onLine(line, fieldLength) {
429
+ if (line.length === 0) {
430
+ onMessage?.(message);
431
+ message = newMessage();
432
+ } else if (fieldLength > 0) {
433
+ const field = decoder.decode(line.subarray(0, fieldLength));
434
+ const valueOffset = fieldLength + (line[fieldLength + 1] === 32 /* Space */ ? 2 : 1);
435
+ const value = decoder.decode(line.subarray(valueOffset));
436
+ switch (field) {
437
+ case "data":
438
+ message.data = message.data ? message.data + "\n" + value : value;
439
+ break;
440
+ case "event":
441
+ message.event = value;
442
+ break;
443
+ case "id":
444
+ onId(message.id = value);
445
+ break;
446
+ case "retry":
447
+ const retry = parseInt(value, 10);
448
+ if (!isNaN(retry)) {
449
+ onRetry(message.retry = retry);
450
+ }
451
+ break;
452
+ }
453
+ }
454
+ };
455
+ }
456
+ function concat(a, b) {
457
+ const res = new Uint8Array(a.length + b.length);
458
+ res.set(a);
459
+ res.set(b, a.length);
460
+ return res;
461
+ }
462
+ function newMessage() {
463
+ return {
464
+ data: "",
465
+ event: "",
466
+ id: "",
467
+ retry: void 0
468
+ };
469
+ }
470
+ const EventStreamContentType = "text/event-stream";
471
+ const LastEventId = "last-event-id";
472
+ function fetchEventSource(input, {
473
+ signal: inputSignal,
474
+ headers: inputHeaders,
475
+ onopen: inputOnOpen,
476
+ onmessage,
477
+ onclose,
478
+ onerror,
479
+ fetch: inputFetch,
480
+ ...rest
481
+ }) {
482
+ return new Promise((resolve, reject) => {
483
+ const headers = { ...inputHeaders };
484
+ if (!headers.accept) {
485
+ headers.accept = EventStreamContentType;
486
+ }
487
+ let curRequestController;
488
+ function dispose() {
489
+ curRequestController.abort();
490
+ }
491
+ inputSignal?.addEventListener("abort", () => {
492
+ dispose();
493
+ resolve();
494
+ });
495
+ const fetchImpl = inputFetch ?? fetch;
496
+ const onopen = inputOnOpen ?? defaultOnOpen;
497
+ async function create() {
498
+ curRequestController = new AbortController();
499
+ try {
500
+ const response = await fetchImpl(input, {
501
+ ...rest,
502
+ headers,
503
+ signal: curRequestController.signal
504
+ });
505
+ await onopen(response);
506
+ await getBytes(
507
+ response.body,
508
+ getLines(
509
+ getMessages(
510
+ (id) => {
511
+ if (id) {
512
+ headers[LastEventId] = id;
513
+ } else {
514
+ delete headers[LastEventId];
515
+ }
516
+ },
517
+ (_retry) => {
518
+ },
519
+ onmessage
520
+ )
521
+ )
522
+ );
523
+ onclose?.();
524
+ dispose();
525
+ resolve();
526
+ } catch (err) {
527
+ }
528
+ }
529
+ create();
530
+ });
531
+ }
532
+ function defaultOnOpen(response) {
533
+ const contentType = response.headers?.get("content-type");
534
+ if (!contentType?.startsWith(EventStreamContentType)) {
535
+ throw new Error(`Expected content-type to be ${EventStreamContentType}, Actual: ${contentType}`);
536
+ }
537
+ }
538
+
539
+ const VERSION = "0.26.5";
303
540
 
541
+ var __defProp$7 = Object.defineProperty;
542
+ var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
543
+ var __publicField$7 = (obj, key, value) => {
544
+ __defNormalProp$7(obj, typeof key !== "symbol" ? key + "" : key, value);
545
+ return value;
546
+ };
304
547
  class ErrorWithCause extends Error {
305
548
  constructor(message, options) {
306
549
  super(message, options);
550
+ __publicField$7(this, "cause");
307
551
  }
308
552
  }
309
553
  class FetcherError extends ErrorWithCause {
310
554
  constructor(status, data, requestId) {
311
555
  super(getMessage(data));
556
+ __publicField$7(this, "status");
557
+ __publicField$7(this, "requestId");
558
+ __publicField$7(this, "errors");
312
559
  this.status = status;
313
560
  this.errors = isBulkError(data) ? data.errors : [{ message: getMessage(data), status }];
314
561
  this.requestId = requestId;
@@ -375,6 +622,18 @@ function hostHeader(url) {
375
622
  const { groups } = pattern.exec(url) ?? {};
376
623
  return groups?.host ? { Host: groups.host } : {};
377
624
  }
625
+ async function parseBody(body, headers) {
626
+ if (!isDefined(body))
627
+ return void 0;
628
+ if (isBlob(body) || typeof body.text === "function") {
629
+ return body;
630
+ }
631
+ const { "Content-Type": contentType } = headers ?? {};
632
+ if (String(contentType).toLowerCase() === "application/json" && isObject(body)) {
633
+ return JSON.stringify(body);
634
+ }
635
+ return body;
636
+ }
378
637
  const defaultClientID = generateUUID();
379
638
  async function fetch$1({
380
639
  url: path,
@@ -394,7 +653,8 @@ async function fetch$1({
394
653
  sessionID,
395
654
  clientName,
396
655
  xataAgentExtra,
397
- fetchOptions = {}
656
+ fetchOptions = {},
657
+ rawResponse = false
398
658
  }) {
399
659
  pool.setFetch(fetch2);
400
660
  return await trace(
@@ -413,7 +673,7 @@ async function fetch$1({
413
673
  isDefined(clientName) ? ["service", clientName] : void 0,
414
674
  ...Object.entries(xataAgentExtra ?? {})
415
675
  ]).map(([key, value]) => `${key}=${value}`).join("; ");
416
- const headers = {
676
+ const headers = compactObject({
417
677
  "Accept-Encoding": "identity",
418
678
  "Content-Type": "application/json",
419
679
  "X-Xata-Client-ID": clientID ?? defaultClientID,
@@ -422,11 +682,11 @@ async function fetch$1({
422
682
  ...customHeaders,
423
683
  ...hostHeader(fullUrl),
424
684
  Authorization: `Bearer ${apiKey}`
425
- };
685
+ });
426
686
  const response = await pool.request(url, {
427
687
  ...fetchOptions,
428
688
  method: method.toUpperCase(),
429
- body: body ? JSON.stringify(body) : void 0,
689
+ body: await parseBody(body, headers),
430
690
  headers,
431
691
  signal
432
692
  });
@@ -437,8 +697,12 @@ async function fetch$1({
437
697
  [TraceAttributes.HTTP_REQUEST_ID]: requestId,
438
698
  [TraceAttributes.HTTP_STATUS_CODE]: response.status,
439
699
  [TraceAttributes.HTTP_HOST]: host,
440
- [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
700
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", ""),
701
+ [TraceAttributes.CLOUDFLARE_RAY_ID]: response.headers?.get("cf-ray") ?? void 0
441
702
  });
703
+ const message = response.headers?.get("x-xata-message");
704
+ if (message)
705
+ console.warn(message);
442
706
  if (response.status === 204) {
443
707
  return {};
444
708
  }
@@ -446,7 +710,7 @@ async function fetch$1({
446
710
  throw new FetcherError(response.status, "Rate limit exceeded", requestId);
447
711
  }
448
712
  try {
449
- const jsonResponse = await response.json();
713
+ const jsonResponse = rawResponse ? await response.blob() : await response.json();
450
714
  if (response.ok) {
451
715
  return jsonResponse;
452
716
  }
@@ -458,6 +722,59 @@ async function fetch$1({
458
722
  { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
459
723
  );
460
724
  }
725
+ function fetchSSERequest({
726
+ url: path,
727
+ method,
728
+ body,
729
+ headers: customHeaders,
730
+ pathParams,
731
+ queryParams,
732
+ fetch: fetch2,
733
+ apiKey,
734
+ endpoint,
735
+ apiUrl,
736
+ workspacesApiUrl,
737
+ onMessage,
738
+ onError,
739
+ onClose,
740
+ signal,
741
+ clientID,
742
+ sessionID,
743
+ clientName,
744
+ xataAgentExtra
745
+ }) {
746
+ const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
747
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
748
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
749
+ void fetchEventSource(url, {
750
+ method,
751
+ body: JSON.stringify(body),
752
+ fetch: fetch2,
753
+ signal,
754
+ headers: {
755
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
756
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
757
+ "X-Xata-Agent": compact([
758
+ ["client", "TS_SDK"],
759
+ ["version", VERSION],
760
+ isDefined(clientName) ? ["service", clientName] : void 0,
761
+ ...Object.entries(xataAgentExtra ?? {})
762
+ ]).map(([key, value]) => `${key}=${value}`).join("; "),
763
+ ...customHeaders,
764
+ Authorization: `Bearer ${apiKey}`,
765
+ "Content-Type": "application/json"
766
+ },
767
+ onmessage(ev) {
768
+ onMessage?.(JSON.parse(ev.data));
769
+ },
770
+ onerror(ev) {
771
+ onError?.(JSON.parse(ev.data));
772
+ },
773
+ onclose() {
774
+ onClose?.();
775
+ }
776
+ });
777
+ }
461
778
  function parseUrl(url) {
462
779
  try {
463
780
  const { host, protocol } = new URL(url);
@@ -488,6 +805,12 @@ const deleteBranch = (variables, signal) => dataPlaneFetch({
488
805
  ...variables,
489
806
  signal
490
807
  });
808
+ const copyBranch = (variables, signal) => dataPlaneFetch({
809
+ url: "/db/{dbBranchName}/copy",
810
+ method: "post",
811
+ ...variables,
812
+ signal
813
+ });
491
814
  const updateBranchMetadata = (variables, signal) => dataPlaneFetch({
492
815
  url: "/db/{dbBranchName}/metadata",
493
816
  method: "put",
@@ -537,6 +860,7 @@ const compareBranchSchemas = (variables, signal) => dataPlaneFetch({ url: "/db/{
537
860
  const updateBranchSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/update", method: "post", ...variables, signal });
538
861
  const previewBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables, signal });
539
862
  const applyBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables, signal });
863
+ const pushBranchMigrations = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/push", method: "post", ...variables, signal });
540
864
  const createTable = (variables, signal) => dataPlaneFetch({
541
865
  url: "/db/{dbBranchName}/tables/{tableName}",
542
866
  method: "put",
@@ -581,6 +905,42 @@ const deleteColumn = (variables, signal) => dataPlaneFetch({
581
905
  });
582
906
  const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
583
907
  const insertRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
908
+ const getFileItem = (variables, signal) => dataPlaneFetch({
909
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
910
+ method: "get",
911
+ ...variables,
912
+ signal
913
+ });
914
+ const putFileItem = (variables, signal) => dataPlaneFetch({
915
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
916
+ method: "put",
917
+ ...variables,
918
+ signal
919
+ });
920
+ const deleteFileItem = (variables, signal) => dataPlaneFetch({
921
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
922
+ method: "delete",
923
+ ...variables,
924
+ signal
925
+ });
926
+ const getFile = (variables, signal) => dataPlaneFetch({
927
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
928
+ method: "get",
929
+ ...variables,
930
+ signal
931
+ });
932
+ const putFile = (variables, signal) => dataPlaneFetch({
933
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
934
+ method: "put",
935
+ ...variables,
936
+ signal
937
+ });
938
+ const deleteFile = (variables, signal) => dataPlaneFetch({
939
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
940
+ method: "delete",
941
+ ...variables,
942
+ signal
943
+ });
584
944
  const getRecord = (variables, signal) => dataPlaneFetch({
585
945
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
586
946
  method: "get",
@@ -617,14 +977,28 @@ const askTable = (variables, signal) => dataPlaneFetch({
617
977
  ...variables,
618
978
  signal
619
979
  });
980
+ const askTableSession = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}", method: "post", ...variables, signal });
620
981
  const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
621
982
  const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
983
+ const fileAccess = (variables, signal) => dataPlaneFetch({
984
+ url: "/file/{fileId}",
985
+ method: "get",
986
+ ...variables,
987
+ signal
988
+ });
989
+ const sqlQuery = (variables, signal) => dataPlaneFetch({
990
+ url: "/db/{dbBranchName}/sql",
991
+ method: "post",
992
+ ...variables,
993
+ signal
994
+ });
622
995
  const operationsByTag$2 = {
623
996
  branch: {
624
997
  getBranchList,
625
998
  getBranchDetails,
626
999
  createBranch,
627
1000
  deleteBranch,
1001
+ copyBranch,
628
1002
  updateBranchMetadata,
629
1003
  getBranchMetadata,
630
1004
  getBranchStats,
@@ -642,7 +1016,8 @@ const operationsByTag$2 = {
642
1016
  compareBranchSchemas,
643
1017
  updateBranchSchema,
644
1018
  previewBranchSchemaEdit,
645
- applyBranchSchemaEdit
1019
+ applyBranchSchemaEdit,
1020
+ pushBranchMigrations
646
1021
  },
647
1022
  migrationRequests: {
648
1023
  queryMigrationRequests,
@@ -676,19 +1051,24 @@ const operationsByTag$2 = {
676
1051
  deleteRecord,
677
1052
  bulkInsertTableRecords
678
1053
  },
1054
+ files: { getFileItem, putFileItem, deleteFileItem, getFile, putFile, deleteFile, fileAccess },
679
1055
  searchAndFilter: {
680
1056
  queryTable,
681
1057
  searchBranch,
682
1058
  searchTable,
683
1059
  vectorSearchTable,
684
1060
  askTable,
1061
+ askTableSession,
685
1062
  summarizeTable,
686
1063
  aggregateTable
687
- }
1064
+ },
1065
+ sql: { sqlQuery }
688
1066
  };
689
1067
 
690
1068
  const controlPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "controlPlane" });
691
1069
 
1070
+ const getAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "get", ...variables, signal });
1071
+ const grantAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "post", ...variables, signal });
692
1072
  const getUser = (variables, signal) => controlPlaneFetch({
693
1073
  url: "/user",
694
1074
  method: "get",
@@ -725,6 +1105,31 @@ const deleteUserAPIKey = (variables, signal) => controlPlaneFetch({
725
1105
  ...variables,
726
1106
  signal
727
1107
  });
1108
+ const getUserOAuthClients = (variables, signal) => controlPlaneFetch({
1109
+ url: "/user/oauth/clients",
1110
+ method: "get",
1111
+ ...variables,
1112
+ signal
1113
+ });
1114
+ const deleteUserOAuthClient = (variables, signal) => controlPlaneFetch({
1115
+ url: "/user/oauth/clients/{clientId}",
1116
+ method: "delete",
1117
+ ...variables,
1118
+ signal
1119
+ });
1120
+ const getUserOAuthAccessTokens = (variables, signal) => controlPlaneFetch({
1121
+ url: "/user/oauth/tokens",
1122
+ method: "get",
1123
+ ...variables,
1124
+ signal
1125
+ });
1126
+ const deleteOAuthAccessToken = (variables, signal) => controlPlaneFetch({
1127
+ url: "/user/oauth/tokens/{token}",
1128
+ method: "delete",
1129
+ ...variables,
1130
+ signal
1131
+ });
1132
+ const updateOAuthAccessToken = (variables, signal) => controlPlaneFetch({ url: "/user/oauth/tokens/{token}", method: "patch", ...variables, signal });
728
1133
  const getWorkspacesList = (variables, signal) => controlPlaneFetch({
729
1134
  url: "/workspaces",
730
1135
  method: "get",
@@ -783,6 +1188,7 @@ const deleteDatabase = (variables, signal) => controlPlaneFetch({
783
1188
  });
784
1189
  const getDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "get", ...variables, signal });
785
1190
  const updateDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "patch", ...variables, signal });
1191
+ const renameDatabase = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/rename", method: "post", ...variables, signal });
786
1192
  const getDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "get", ...variables, signal });
787
1193
  const updateDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "put", ...variables, signal });
788
1194
  const deleteDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "delete", ...variables, signal });
@@ -793,6 +1199,15 @@ const listRegions = (variables, signal) => controlPlaneFetch({
793
1199
  signal
794
1200
  });
795
1201
  const operationsByTag$1 = {
1202
+ oAuth: {
1203
+ getAuthorizationCode,
1204
+ grantAuthorizationCode,
1205
+ getUserOAuthClients,
1206
+ deleteUserOAuthClient,
1207
+ getUserOAuthAccessTokens,
1208
+ deleteOAuthAccessToken,
1209
+ updateOAuthAccessToken
1210
+ },
796
1211
  users: { getUser, updateUser, deleteUser },
797
1212
  authentication: { getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
798
1213
  workspaces: {
@@ -818,6 +1233,7 @@ const operationsByTag$1 = {
818
1233
  deleteDatabase,
819
1234
  getDatabaseMetadata,
820
1235
  updateDatabaseMetadata,
1236
+ renameDatabase,
821
1237
  getDatabaseGithubSettings,
822
1238
  updateDatabaseGithubSettings,
823
1239
  deleteDatabaseGithubSettings,
@@ -843,6 +1259,10 @@ const providers = {
843
1259
  staging: {
844
1260
  main: "https://api.staging-xata.dev",
845
1261
  workspaces: "https://{workspaceId}.{region}.staging-xata.dev"
1262
+ },
1263
+ dev: {
1264
+ main: "https://api.dev-xata.dev",
1265
+ workspaces: "https://{workspaceId}.{region}.dev-xata.dev"
846
1266
  }
847
1267
  };
848
1268
  function isHostProviderAlias(alias) {
@@ -860,6 +1280,11 @@ function parseProviderString(provider = "production") {
860
1280
  return null;
861
1281
  return { main, workspaces };
862
1282
  }
1283
+ function buildProviderString(provider) {
1284
+ if (isHostProviderAlias(provider))
1285
+ return provider;
1286
+ return `${provider.main},${provider.workspaces}`;
1287
+ }
863
1288
  function parseWorkspacesUrlParts(url) {
864
1289
  if (!isString(url))
865
1290
  return null;
@@ -964,6 +1389,11 @@ class XataApiClient {
964
1389
  __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
965
1390
  return __privateGet$7(this, _namespaces).records;
966
1391
  }
1392
+ get files() {
1393
+ if (!__privateGet$7(this, _namespaces).files)
1394
+ __privateGet$7(this, _namespaces).files = new FilesApi(__privateGet$7(this, _extraProps));
1395
+ return __privateGet$7(this, _namespaces).files;
1396
+ }
967
1397
  get searchAndFilter() {
968
1398
  if (!__privateGet$7(this, _namespaces).searchAndFilter)
969
1399
  __privateGet$7(this, _namespaces).searchAndFilter = new SearchAndFilterApi(__privateGet$7(this, _extraProps));
@@ -1172,6 +1602,20 @@ class BranchApi {
1172
1602
  ...this.extraProps
1173
1603
  });
1174
1604
  }
1605
+ copyBranch({
1606
+ workspace,
1607
+ region,
1608
+ database,
1609
+ branch,
1610
+ destinationBranch,
1611
+ limit
1612
+ }) {
1613
+ return operationsByTag.branch.copyBranch({
1614
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1615
+ body: { destinationBranch, limit },
1616
+ ...this.extraProps
1617
+ });
1618
+ }
1175
1619
  updateBranchMetadata({
1176
1620
  workspace,
1177
1621
  region,
@@ -1527,6 +1971,164 @@ class RecordsApi {
1527
1971
  });
1528
1972
  }
1529
1973
  }
1974
+ class FilesApi {
1975
+ constructor(extraProps) {
1976
+ this.extraProps = extraProps;
1977
+ }
1978
+ getFileItem({
1979
+ workspace,
1980
+ region,
1981
+ database,
1982
+ branch,
1983
+ table,
1984
+ record,
1985
+ column,
1986
+ fileId
1987
+ }) {
1988
+ return operationsByTag.files.getFileItem({
1989
+ pathParams: {
1990
+ workspace,
1991
+ region,
1992
+ dbBranchName: `${database}:${branch}`,
1993
+ tableName: table,
1994
+ recordId: record,
1995
+ columnName: column,
1996
+ fileId
1997
+ },
1998
+ ...this.extraProps
1999
+ });
2000
+ }
2001
+ putFileItem({
2002
+ workspace,
2003
+ region,
2004
+ database,
2005
+ branch,
2006
+ table,
2007
+ record,
2008
+ column,
2009
+ fileId,
2010
+ file
2011
+ }) {
2012
+ return operationsByTag.files.putFileItem({
2013
+ pathParams: {
2014
+ workspace,
2015
+ region,
2016
+ dbBranchName: `${database}:${branch}`,
2017
+ tableName: table,
2018
+ recordId: record,
2019
+ columnName: column,
2020
+ fileId
2021
+ },
2022
+ // @ts-ignore
2023
+ body: file,
2024
+ ...this.extraProps
2025
+ });
2026
+ }
2027
+ deleteFileItem({
2028
+ workspace,
2029
+ region,
2030
+ database,
2031
+ branch,
2032
+ table,
2033
+ record,
2034
+ column,
2035
+ fileId
2036
+ }) {
2037
+ return operationsByTag.files.deleteFileItem({
2038
+ pathParams: {
2039
+ workspace,
2040
+ region,
2041
+ dbBranchName: `${database}:${branch}`,
2042
+ tableName: table,
2043
+ recordId: record,
2044
+ columnName: column,
2045
+ fileId
2046
+ },
2047
+ ...this.extraProps
2048
+ });
2049
+ }
2050
+ getFile({
2051
+ workspace,
2052
+ region,
2053
+ database,
2054
+ branch,
2055
+ table,
2056
+ record,
2057
+ column
2058
+ }) {
2059
+ return operationsByTag.files.getFile({
2060
+ pathParams: {
2061
+ workspace,
2062
+ region,
2063
+ dbBranchName: `${database}:${branch}`,
2064
+ tableName: table,
2065
+ recordId: record,
2066
+ columnName: column
2067
+ },
2068
+ ...this.extraProps
2069
+ });
2070
+ }
2071
+ putFile({
2072
+ workspace,
2073
+ region,
2074
+ database,
2075
+ branch,
2076
+ table,
2077
+ record,
2078
+ column,
2079
+ file
2080
+ }) {
2081
+ return operationsByTag.files.putFile({
2082
+ pathParams: {
2083
+ workspace,
2084
+ region,
2085
+ dbBranchName: `${database}:${branch}`,
2086
+ tableName: table,
2087
+ recordId: record,
2088
+ columnName: column
2089
+ },
2090
+ body: file,
2091
+ ...this.extraProps
2092
+ });
2093
+ }
2094
+ deleteFile({
2095
+ workspace,
2096
+ region,
2097
+ database,
2098
+ branch,
2099
+ table,
2100
+ record,
2101
+ column
2102
+ }) {
2103
+ return operationsByTag.files.deleteFile({
2104
+ pathParams: {
2105
+ workspace,
2106
+ region,
2107
+ dbBranchName: `${database}:${branch}`,
2108
+ tableName: table,
2109
+ recordId: record,
2110
+ columnName: column
2111
+ },
2112
+ ...this.extraProps
2113
+ });
2114
+ }
2115
+ fileAccess({
2116
+ workspace,
2117
+ region,
2118
+ fileId,
2119
+ verify
2120
+ }) {
2121
+ return operationsByTag.files.fileAccess({
2122
+ pathParams: {
2123
+ workspace,
2124
+ region,
2125
+ fileId
2126
+ },
2127
+ queryParams: { verify },
2128
+ ...this.extraProps
2129
+ });
2130
+ }
2131
+ }
1530
2132
  class SearchAndFilterApi {
1531
2133
  constructor(extraProps) {
1532
2134
  this.extraProps = extraProps;
@@ -1610,17 +2212,26 @@ class SearchAndFilterApi {
1610
2212
  database,
1611
2213
  branch,
1612
2214
  table,
1613
- question,
1614
- fuzziness,
1615
- target,
1616
- prefix,
1617
- filter,
1618
- boosters,
1619
- rules
2215
+ options
1620
2216
  }) {
1621
2217
  return operationsByTag.searchAndFilter.askTable({
1622
2218
  pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1623
- body: { question, fuzziness, target, prefix, filter, boosters, rules },
2219
+ body: { ...options },
2220
+ ...this.extraProps
2221
+ });
2222
+ }
2223
+ askTableSession({
2224
+ workspace,
2225
+ region,
2226
+ database,
2227
+ branch,
2228
+ table,
2229
+ sessionId,
2230
+ message
2231
+ }) {
2232
+ return operationsByTag.searchAndFilter.askTableSession({
2233
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, sessionId },
2234
+ body: { message },
1624
2235
  ...this.extraProps
1625
2236
  });
1626
2237
  }
@@ -1888,6 +2499,19 @@ class MigrationsApi {
1888
2499
  ...this.extraProps
1889
2500
  });
1890
2501
  }
2502
+ pushBranchMigrations({
2503
+ workspace,
2504
+ region,
2505
+ database,
2506
+ branch,
2507
+ migrations
2508
+ }) {
2509
+ return operationsByTag.migrations.pushBranchMigrations({
2510
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2511
+ body: { migrations },
2512
+ ...this.extraProps
2513
+ });
2514
+ }
1891
2515
  }
1892
2516
  class DatabaseApi {
1893
2517
  constructor(extraProps) {
@@ -1902,11 +2526,13 @@ class DatabaseApi {
1902
2526
  createDatabase({
1903
2527
  workspace,
1904
2528
  database,
1905
- data
2529
+ data,
2530
+ headers
1906
2531
  }) {
1907
2532
  return operationsByTag.databases.createDatabase({
1908
2533
  pathParams: { workspaceId: workspace, dbName: database },
1909
2534
  body: data,
2535
+ headers,
1910
2536
  ...this.extraProps
1911
2537
  });
1912
2538
  }
@@ -1939,6 +2565,17 @@ class DatabaseApi {
1939
2565
  ...this.extraProps
1940
2566
  });
1941
2567
  }
2568
+ renameDatabase({
2569
+ workspace,
2570
+ database,
2571
+ newName
2572
+ }) {
2573
+ return operationsByTag.databases.renameDatabase({
2574
+ pathParams: { workspaceId: workspace, dbName: database },
2575
+ body: { newName },
2576
+ ...this.extraProps
2577
+ });
2578
+ }
1942
2579
  getDatabaseGithubSettings({
1943
2580
  workspace,
1944
2581
  database
@@ -1985,13 +2622,319 @@ class XataApiPlugin {
1985
2622
  class XataPlugin {
1986
2623
  }
1987
2624
 
2625
+ class FilesPlugin extends XataPlugin {
2626
+ build(pluginOptions) {
2627
+ return {
2628
+ download: async (location) => {
2629
+ const { table, record, column, fileId = "" } = location ?? {};
2630
+ return await getFileItem({
2631
+ pathParams: {
2632
+ workspace: "{workspaceId}",
2633
+ dbBranchName: "{dbBranch}",
2634
+ region: "{region}",
2635
+ tableName: table ?? "",
2636
+ recordId: record ?? "",
2637
+ columnName: column ?? "",
2638
+ fileId
2639
+ },
2640
+ ...pluginOptions,
2641
+ rawResponse: true
2642
+ });
2643
+ },
2644
+ upload: async (location, file) => {
2645
+ const { table, record, column, fileId = "" } = location ?? {};
2646
+ const contentType = getContentType(file);
2647
+ return await putFileItem({
2648
+ ...pluginOptions,
2649
+ pathParams: {
2650
+ workspace: "{workspaceId}",
2651
+ dbBranchName: "{dbBranch}",
2652
+ region: "{region}",
2653
+ tableName: table ?? "",
2654
+ recordId: record ?? "",
2655
+ columnName: column ?? "",
2656
+ fileId
2657
+ },
2658
+ body: file,
2659
+ headers: { "Content-Type": contentType }
2660
+ });
2661
+ },
2662
+ delete: async (location) => {
2663
+ const { table, record, column, fileId = "" } = location ?? {};
2664
+ return await deleteFileItem({
2665
+ pathParams: {
2666
+ workspace: "{workspaceId}",
2667
+ dbBranchName: "{dbBranch}",
2668
+ region: "{region}",
2669
+ tableName: table ?? "",
2670
+ recordId: record ?? "",
2671
+ columnName: column ?? "",
2672
+ fileId
2673
+ },
2674
+ ...pluginOptions
2675
+ });
2676
+ }
2677
+ };
2678
+ }
2679
+ }
2680
+ function getContentType(file) {
2681
+ if (typeof file === "string") {
2682
+ return "text/plain";
2683
+ }
2684
+ if (isBlob(file)) {
2685
+ return file.type;
2686
+ }
2687
+ try {
2688
+ return file.type;
2689
+ } catch (e) {
2690
+ }
2691
+ return "application/octet-stream";
2692
+ }
2693
+
2694
+ function buildTransformString(transformations) {
2695
+ return transformations.flatMap(
2696
+ (t) => Object.entries(t).map(([key, value]) => {
2697
+ if (key === "trim") {
2698
+ const { left = 0, top = 0, right = 0, bottom = 0 } = value;
2699
+ return `${key}=${[top, right, bottom, left].join(";")}`;
2700
+ }
2701
+ if (key === "gravity" && typeof value === "object") {
2702
+ const { x = 0.5, y = 0.5 } = value;
2703
+ return `${key}=${[x, y].join("x")}`;
2704
+ }
2705
+ return `${key}=${value}`;
2706
+ })
2707
+ ).join(",");
2708
+ }
2709
+ function transformImage(url, ...transformations) {
2710
+ if (!isDefined(url))
2711
+ return void 0;
2712
+ const newTransformations = buildTransformString(transformations);
2713
+ const { hostname, pathname, search } = new URL(url);
2714
+ const pathParts = pathname.split("/");
2715
+ const transformIndex = pathParts.findIndex((part) => part === "transform");
2716
+ const removedItems = transformIndex >= 0 ? pathParts.splice(transformIndex, 2) : [];
2717
+ const transform = `/transform/${[removedItems[1], newTransformations].filter(isDefined).join(",")}`;
2718
+ const path = pathParts.join("/");
2719
+ return `https://${hostname}${transform}${path}${search}`;
2720
+ }
2721
+
2722
+ var __defProp$6 = Object.defineProperty;
2723
+ var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2724
+ var __publicField$6 = (obj, key, value) => {
2725
+ __defNormalProp$6(obj, typeof key !== "symbol" ? key + "" : key, value);
2726
+ return value;
2727
+ };
2728
+ class XataFile {
2729
+ constructor(file) {
2730
+ /**
2731
+ * Identifier of the file.
2732
+ */
2733
+ __publicField$6(this, "id");
2734
+ /**
2735
+ * Name of the file.
2736
+ */
2737
+ __publicField$6(this, "name");
2738
+ /**
2739
+ * Media type of the file.
2740
+ */
2741
+ __publicField$6(this, "mediaType");
2742
+ /**
2743
+ * Base64 encoded content of the file.
2744
+ */
2745
+ __publicField$6(this, "base64Content");
2746
+ /**
2747
+ * Whether to enable public url for the file.
2748
+ */
2749
+ __publicField$6(this, "enablePublicUrl");
2750
+ /**
2751
+ * Timeout for the signed url.
2752
+ */
2753
+ __publicField$6(this, "signedUrlTimeout");
2754
+ /**
2755
+ * Size of the file.
2756
+ */
2757
+ __publicField$6(this, "size");
2758
+ /**
2759
+ * Version of the file.
2760
+ */
2761
+ __publicField$6(this, "version");
2762
+ /**
2763
+ * Url of the file.
2764
+ */
2765
+ __publicField$6(this, "url");
2766
+ /**
2767
+ * Signed url of the file.
2768
+ */
2769
+ __publicField$6(this, "signedUrl");
2770
+ /**
2771
+ * Attributes of the file.
2772
+ */
2773
+ __publicField$6(this, "attributes");
2774
+ this.id = file.id;
2775
+ this.name = file.name || "";
2776
+ this.mediaType = file.mediaType || "application/octet-stream";
2777
+ this.base64Content = file.base64Content;
2778
+ this.enablePublicUrl = file.enablePublicUrl ?? false;
2779
+ this.signedUrlTimeout = file.signedUrlTimeout ?? 300;
2780
+ this.size = file.size ?? 0;
2781
+ this.version = file.version ?? 1;
2782
+ this.url = file.url || "";
2783
+ this.signedUrl = file.signedUrl;
2784
+ this.attributes = file.attributes || {};
2785
+ }
2786
+ static fromBuffer(buffer, options = {}) {
2787
+ const base64Content = buffer.toString("base64");
2788
+ return new XataFile({ ...options, base64Content });
2789
+ }
2790
+ toBuffer() {
2791
+ if (!this.base64Content) {
2792
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2793
+ }
2794
+ return Buffer.from(this.base64Content, "base64");
2795
+ }
2796
+ static fromArrayBuffer(arrayBuffer, options = {}) {
2797
+ const uint8Array = new Uint8Array(arrayBuffer);
2798
+ return this.fromUint8Array(uint8Array, options);
2799
+ }
2800
+ toArrayBuffer() {
2801
+ if (!this.base64Content) {
2802
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2803
+ }
2804
+ const binary = atob(this.base64Content);
2805
+ return new ArrayBuffer(binary.length);
2806
+ }
2807
+ static fromUint8Array(uint8Array, options = {}) {
2808
+ let binary = "";
2809
+ for (let i = 0; i < uint8Array.byteLength; i++) {
2810
+ binary += String.fromCharCode(uint8Array[i]);
2811
+ }
2812
+ const base64Content = btoa(binary);
2813
+ return new XataFile({ ...options, base64Content });
2814
+ }
2815
+ toUint8Array() {
2816
+ if (!this.base64Content) {
2817
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2818
+ }
2819
+ const binary = atob(this.base64Content);
2820
+ const uint8Array = new Uint8Array(binary.length);
2821
+ for (let i = 0; i < binary.length; i++) {
2822
+ uint8Array[i] = binary.charCodeAt(i);
2823
+ }
2824
+ return uint8Array;
2825
+ }
2826
+ static async fromBlob(file, options = {}) {
2827
+ const name = options.name ?? file.name;
2828
+ const mediaType = file.type;
2829
+ const arrayBuffer = await file.arrayBuffer();
2830
+ return this.fromArrayBuffer(arrayBuffer, { ...options, name, mediaType });
2831
+ }
2832
+ toBlob() {
2833
+ if (!this.base64Content) {
2834
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2835
+ }
2836
+ const binary = atob(this.base64Content);
2837
+ const uint8Array = new Uint8Array(binary.length);
2838
+ for (let i = 0; i < binary.length; i++) {
2839
+ uint8Array[i] = binary.charCodeAt(i);
2840
+ }
2841
+ return new Blob([uint8Array], { type: this.mediaType });
2842
+ }
2843
+ static fromString(string, options = {}) {
2844
+ const base64Content = btoa(string);
2845
+ return new XataFile({ ...options, base64Content });
2846
+ }
2847
+ toString() {
2848
+ if (!this.base64Content) {
2849
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2850
+ }
2851
+ return atob(this.base64Content);
2852
+ }
2853
+ static fromBase64(base64Content, options = {}) {
2854
+ return new XataFile({ ...options, base64Content });
2855
+ }
2856
+ toBase64() {
2857
+ if (!this.base64Content) {
2858
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2859
+ }
2860
+ return this.base64Content;
2861
+ }
2862
+ transform(...options) {
2863
+ return {
2864
+ url: transformImage(this.url, ...options),
2865
+ signedUrl: transformImage(this.signedUrl, ...options),
2866
+ metadataUrl: transformImage(this.url, ...options, { format: "json" }),
2867
+ metadataSignedUrl: transformImage(this.signedUrl, ...options, { format: "json" })
2868
+ };
2869
+ }
2870
+ }
2871
+ const parseInputFileEntry = async (entry) => {
2872
+ if (!isDefined(entry))
2873
+ return null;
2874
+ const { id, name, mediaType, base64Content, enablePublicUrl, signedUrlTimeout } = await entry;
2875
+ return compactObject({
2876
+ id,
2877
+ // Name cannot be an empty string in our API
2878
+ name: name ? name : void 0,
2879
+ mediaType,
2880
+ base64Content,
2881
+ enablePublicUrl,
2882
+ signedUrlTimeout
2883
+ });
2884
+ };
2885
+
1988
2886
  function cleanFilter(filter) {
1989
- if (!filter)
2887
+ if (!isDefined(filter))
1990
2888
  return void 0;
1991
- const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
1992
- return values.length > 0 ? filter : void 0;
2889
+ if (!isObject(filter))
2890
+ return filter;
2891
+ const values = Object.fromEntries(
2892
+ Object.entries(filter).reduce((acc, [key, value]) => {
2893
+ if (!isDefined(value))
2894
+ return acc;
2895
+ if (Array.isArray(value)) {
2896
+ const clean = value.map((item) => cleanFilter(item)).filter((item) => isDefined(item));
2897
+ if (clean.length === 0)
2898
+ return acc;
2899
+ return [...acc, [key, clean]];
2900
+ }
2901
+ if (isObject(value)) {
2902
+ const clean = cleanFilter(value);
2903
+ if (!isDefined(clean))
2904
+ return acc;
2905
+ return [...acc, [key, clean]];
2906
+ }
2907
+ return [...acc, [key, value]];
2908
+ }, [])
2909
+ );
2910
+ return Object.keys(values).length > 0 ? values : void 0;
2911
+ }
2912
+
2913
+ function stringifyJson(value) {
2914
+ if (!isDefined(value))
2915
+ return value;
2916
+ if (isString(value))
2917
+ return value;
2918
+ try {
2919
+ return JSON.stringify(value);
2920
+ } catch (e) {
2921
+ return value;
2922
+ }
2923
+ }
2924
+ function parseJson(value) {
2925
+ try {
2926
+ return JSON.parse(value);
2927
+ } catch (e) {
2928
+ return value;
2929
+ }
1993
2930
  }
1994
2931
 
2932
+ var __defProp$5 = Object.defineProperty;
2933
+ var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2934
+ var __publicField$5 = (obj, key, value) => {
2935
+ __defNormalProp$5(obj, typeof key !== "symbol" ? key + "" : key, value);
2936
+ return value;
2937
+ };
1995
2938
  var __accessCheck$6 = (obj, member, msg) => {
1996
2939
  if (!member.has(obj))
1997
2940
  throw TypeError("Cannot " + msg);
@@ -2014,22 +2957,58 @@ var _query, _page;
2014
2957
  class Page {
2015
2958
  constructor(query, meta, records = []) {
2016
2959
  __privateAdd$6(this, _query, void 0);
2960
+ /**
2961
+ * Page metadata, required to retrieve additional records.
2962
+ */
2963
+ __publicField$5(this, "meta");
2964
+ /**
2965
+ * The set of results for this page.
2966
+ */
2967
+ __publicField$5(this, "records");
2017
2968
  __privateSet$6(this, _query, query);
2018
2969
  this.meta = meta;
2019
2970
  this.records = new RecordArray(this, records);
2020
2971
  }
2972
+ /**
2973
+ * Retrieves the next page of results.
2974
+ * @param size Maximum number of results to be retrieved.
2975
+ * @param offset Number of results to skip when retrieving the results.
2976
+ * @returns The next page or results.
2977
+ */
2021
2978
  async nextPage(size, offset) {
2022
2979
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
2023
2980
  }
2981
+ /**
2982
+ * Retrieves the previous page of results.
2983
+ * @param size Maximum number of results to be retrieved.
2984
+ * @param offset Number of results to skip when retrieving the results.
2985
+ * @returns The previous page or results.
2986
+ */
2024
2987
  async previousPage(size, offset) {
2025
2988
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
2026
2989
  }
2990
+ /**
2991
+ * Retrieves the start page of results.
2992
+ * @param size Maximum number of results to be retrieved.
2993
+ * @param offset Number of results to skip when retrieving the results.
2994
+ * @returns The start page or results.
2995
+ */
2027
2996
  async startPage(size, offset) {
2028
2997
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, start: this.meta.page.cursor } });
2029
2998
  }
2999
+ /**
3000
+ * Retrieves the end page of results.
3001
+ * @param size Maximum number of results to be retrieved.
3002
+ * @param offset Number of results to skip when retrieving the results.
3003
+ * @returns The end page or results.
3004
+ */
2030
3005
  async endPage(size, offset) {
2031
3006
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, end: this.meta.page.cursor } });
2032
3007
  }
3008
+ /**
3009
+ * Shortcut method to check if there will be additional results if the next page of results is retrieved.
3010
+ * @returns Whether or not there will be additional results in the next page of results.
3011
+ */
2033
3012
  hasNextPage() {
2034
3013
  return this.meta.page.more;
2035
3014
  }
@@ -2042,7 +3021,7 @@ const PAGINATION_DEFAULT_OFFSET = 0;
2042
3021
  function isCursorPaginationOptions(options) {
2043
3022
  return isDefined(options) && (isDefined(options.start) || isDefined(options.end) || isDefined(options.after) || isDefined(options.before));
2044
3023
  }
2045
- const _RecordArray = class extends Array {
3024
+ const _RecordArray = class _RecordArray extends Array {
2046
3025
  constructor(...args) {
2047
3026
  super(..._RecordArray.parseConstructorParams(...args));
2048
3027
  __privateAdd$6(this, _page, void 0);
@@ -2070,29 +3049,58 @@ const _RecordArray = class extends Array {
2070
3049
  map(callbackfn, thisArg) {
2071
3050
  return this.toArray().map(callbackfn, thisArg);
2072
3051
  }
3052
+ /**
3053
+ * Retrieve next page of records
3054
+ *
3055
+ * @returns A new array of objects
3056
+ */
2073
3057
  async nextPage(size, offset) {
2074
3058
  const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
2075
3059
  return new _RecordArray(newPage);
2076
3060
  }
3061
+ /**
3062
+ * Retrieve previous page of records
3063
+ *
3064
+ * @returns A new array of objects
3065
+ */
2077
3066
  async previousPage(size, offset) {
2078
3067
  const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
2079
3068
  return new _RecordArray(newPage);
2080
3069
  }
3070
+ /**
3071
+ * Retrieve start page of records
3072
+ *
3073
+ * @returns A new array of objects
3074
+ */
2081
3075
  async startPage(size, offset) {
2082
3076
  const newPage = await __privateGet$6(this, _page).startPage(size, offset);
2083
3077
  return new _RecordArray(newPage);
2084
3078
  }
3079
+ /**
3080
+ * Retrieve end page of records
3081
+ *
3082
+ * @returns A new array of objects
3083
+ */
2085
3084
  async endPage(size, offset) {
2086
3085
  const newPage = await __privateGet$6(this, _page).endPage(size, offset);
2087
3086
  return new _RecordArray(newPage);
2088
3087
  }
3088
+ /**
3089
+ * @returns Boolean indicating if there is a next page
3090
+ */
2089
3091
  hasNextPage() {
2090
3092
  return __privateGet$6(this, _page).meta.page.more;
2091
3093
  }
2092
3094
  };
2093
- let RecordArray = _RecordArray;
2094
3095
  _page = new WeakMap();
3096
+ let RecordArray = _RecordArray;
2095
3097
 
3098
+ var __defProp$4 = Object.defineProperty;
3099
+ var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3100
+ var __publicField$4 = (obj, key, value) => {
3101
+ __defNormalProp$4(obj, typeof key !== "symbol" ? key + "" : key, value);
3102
+ return value;
3103
+ };
2096
3104
  var __accessCheck$5 = (obj, member, msg) => {
2097
3105
  if (!member.has(obj))
2098
3106
  throw TypeError("Cannot " + msg);
@@ -2116,14 +3124,15 @@ var __privateMethod$3 = (obj, member, method) => {
2116
3124
  return method;
2117
3125
  };
2118
3126
  var _table$1, _repository, _data, _cleanFilterConstraint, cleanFilterConstraint_fn;
2119
- const _Query = class {
3127
+ const _Query = class _Query {
2120
3128
  constructor(repository, table, data, rawParent) {
2121
3129
  __privateAdd$5(this, _cleanFilterConstraint);
2122
3130
  __privateAdd$5(this, _table$1, void 0);
2123
3131
  __privateAdd$5(this, _repository, void 0);
2124
3132
  __privateAdd$5(this, _data, { filter: {} });
2125
- this.meta = { page: { cursor: "start", more: true } };
2126
- this.records = new RecordArray(this, []);
3133
+ // Implements pagination
3134
+ __publicField$4(this, "meta", { page: { cursor: "start", more: true, size: PAGINATION_DEFAULT_SIZE } });
3135
+ __publicField$4(this, "records", new RecordArray(this, []));
2127
3136
  __privateSet$5(this, _table$1, table);
2128
3137
  if (repository) {
2129
3138
  __privateSet$5(this, _repository, repository);
@@ -2159,18 +3168,38 @@ const _Query = class {
2159
3168
  const key = JSON.stringify({ columns, filter, sort, pagination });
2160
3169
  return toBase64(key);
2161
3170
  }
3171
+ /**
3172
+ * Builds a new query object representing a logical OR between the given subqueries.
3173
+ * @param queries An array of subqueries.
3174
+ * @returns A new Query object.
3175
+ */
2162
3176
  any(...queries) {
2163
3177
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
2164
3178
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
2165
3179
  }
3180
+ /**
3181
+ * Builds a new query object representing a logical AND between the given subqueries.
3182
+ * @param queries An array of subqueries.
3183
+ * @returns A new Query object.
3184
+ */
2166
3185
  all(...queries) {
2167
3186
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
2168
3187
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
2169
3188
  }
3189
+ /**
3190
+ * Builds a new query object representing a logical OR negating each subquery. In pseudo-code: !q1 OR !q2
3191
+ * @param queries An array of subqueries.
3192
+ * @returns A new Query object.
3193
+ */
2170
3194
  not(...queries) {
2171
3195
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
2172
3196
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
2173
3197
  }
3198
+ /**
3199
+ * Builds a new query object representing a logical AND negating each subquery. In pseudo-code: !q1 AND !q2
3200
+ * @param queries An array of subqueries.
3201
+ * @returns A new Query object.
3202
+ */
2174
3203
  none(...queries) {
2175
3204
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
2176
3205
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
@@ -2193,6 +3222,11 @@ const _Query = class {
2193
3222
  const sort = [...originalSort, { column, direction }];
2194
3223
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
2195
3224
  }
3225
+ /**
3226
+ * Builds a new query specifying the set of columns to be returned in the query response.
3227
+ * @param columns Array of column names to be returned by the query.
3228
+ * @returns A new Query object.
3229
+ */
2196
3230
  select(columns) {
2197
3231
  return new _Query(
2198
3232
  __privateGet$5(this, _repository),
@@ -2205,6 +3239,12 @@ const _Query = class {
2205
3239
  const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
2206
3240
  return __privateGet$5(this, _repository).query(query);
2207
3241
  }
3242
+ /**
3243
+ * Get results in an iterator
3244
+ *
3245
+ * @async
3246
+ * @returns Async interable of results
3247
+ */
2208
3248
  async *[Symbol.asyncIterator]() {
2209
3249
  for await (const [record] of this.getIterator({ batchSize: 1 })) {
2210
3250
  yield record;
@@ -2265,26 +3305,53 @@ const _Query = class {
2265
3305
  );
2266
3306
  return __privateGet$5(this, _repository).summarizeTable(query, summaries, summariesFilter);
2267
3307
  }
3308
+ /**
3309
+ * Builds a new query object adding a cache TTL in milliseconds.
3310
+ * @param ttl The cache TTL in milliseconds.
3311
+ * @returns A new Query object.
3312
+ */
2268
3313
  cache(ttl) {
2269
3314
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
2270
3315
  }
3316
+ /**
3317
+ * Retrieve next page of records
3318
+ *
3319
+ * @returns A new page object.
3320
+ */
2271
3321
  nextPage(size, offset) {
2272
3322
  return this.startPage(size, offset);
2273
3323
  }
3324
+ /**
3325
+ * Retrieve previous page of records
3326
+ *
3327
+ * @returns A new page object
3328
+ */
2274
3329
  previousPage(size, offset) {
2275
3330
  return this.startPage(size, offset);
2276
3331
  }
3332
+ /**
3333
+ * Retrieve start page of records
3334
+ *
3335
+ * @returns A new page object
3336
+ */
2277
3337
  startPage(size, offset) {
2278
3338
  return this.getPaginated({ pagination: { size, offset } });
2279
3339
  }
3340
+ /**
3341
+ * Retrieve last page of records
3342
+ *
3343
+ * @returns A new page object
3344
+ */
2280
3345
  endPage(size, offset) {
2281
3346
  return this.getPaginated({ pagination: { size, offset, before: "end" } });
2282
3347
  }
3348
+ /**
3349
+ * @returns Boolean indicating if there is a next page
3350
+ */
2283
3351
  hasNextPage() {
2284
3352
  return this.meta.page.more;
2285
3353
  }
2286
3354
  };
2287
- let Query = _Query;
2288
3355
  _table$1 = new WeakMap();
2289
3356
  _repository = new WeakMap();
2290
3357
  _data = new WeakMap();
@@ -2299,6 +3366,7 @@ cleanFilterConstraint_fn = function(column, value) {
2299
3366
  }
2300
3367
  return value;
2301
3368
  };
3369
+ let Query = _Query;
2302
3370
  function cleanParent(data, parent) {
2303
3371
  if (isCursorPaginationOptions(data.pagination)) {
2304
3372
  return { ...parent, sort: void 0, filter: void 0 };
@@ -2306,6 +3374,22 @@ function cleanParent(data, parent) {
2306
3374
  return parent;
2307
3375
  }
2308
3376
 
3377
+ const RecordColumnTypes = [
3378
+ "bool",
3379
+ "int",
3380
+ "float",
3381
+ "string",
3382
+ "text",
3383
+ "email",
3384
+ "multiple",
3385
+ "link",
3386
+ "object",
3387
+ "datetime",
3388
+ "vector",
3389
+ "file[]",
3390
+ "file",
3391
+ "json"
3392
+ ];
2309
3393
  function isIdentifiable(x) {
2310
3394
  return isObject(x) && isString(x?.id);
2311
3395
  }
@@ -2315,11 +3399,33 @@ function isXataRecord(x) {
2315
3399
  return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
2316
3400
  }
2317
3401
 
3402
+ function isValidExpandedColumn(column) {
3403
+ return isObject(column) && isString(column.name);
3404
+ }
3405
+ function isValidSelectableColumns(columns) {
3406
+ if (!Array.isArray(columns)) {
3407
+ return false;
3408
+ }
3409
+ return columns.every((column) => {
3410
+ if (typeof column === "string") {
3411
+ return true;
3412
+ }
3413
+ if (typeof column === "object") {
3414
+ return isValidExpandedColumn(column);
3415
+ }
3416
+ return false;
3417
+ });
3418
+ }
3419
+
2318
3420
  function isSortFilterString(value) {
2319
3421
  return isString(value);
2320
3422
  }
2321
3423
  function isSortFilterBase(filter) {
2322
- return isObject(filter) && Object.values(filter).every((value) => value === "asc" || value === "desc");
3424
+ return isObject(filter) && Object.entries(filter).every(([key, value]) => {
3425
+ if (key === "*")
3426
+ return value === "random";
3427
+ return value === "asc" || value === "desc";
3428
+ });
2323
3429
  }
2324
3430
  function isSortFilterObject(filter) {
2325
3431
  return isObject(filter) && !isSortFilterBase(filter) && filter.column !== void 0;
@@ -2360,7 +3466,7 @@ var __privateMethod$2 = (obj, member, method) => {
2360
3466
  __accessCheck$4(obj, member, "access private method");
2361
3467
  return method;
2362
3468
  };
2363
- 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;
3469
+ 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, _transformObjectToApi, transformObjectToApi_fn;
2364
3470
  const BULK_OPERATION_MAX_SIZE = 1e3;
2365
3471
  class Repository extends Query {
2366
3472
  }
@@ -2382,6 +3488,7 @@ class RestRepository extends Query {
2382
3488
  __privateAdd$4(this, _setCacheQuery);
2383
3489
  __privateAdd$4(this, _getCacheQuery);
2384
3490
  __privateAdd$4(this, _getSchemaTables$1);
3491
+ __privateAdd$4(this, _transformObjectToApi);
2385
3492
  __privateAdd$4(this, _table, void 0);
2386
3493
  __privateAdd$4(this, _getFetchProps, void 0);
2387
3494
  __privateAdd$4(this, _db, void 0);
@@ -2410,24 +3517,24 @@ class RestRepository extends Query {
2410
3517
  if (a.length === 0)
2411
3518
  return [];
2412
3519
  const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: true });
2413
- const columns = isStringArray(b) ? b : ["*"];
3520
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2414
3521
  const result = await this.read(ids, columns);
2415
3522
  return result;
2416
3523
  }
2417
3524
  if (isString(a) && isObject(b)) {
2418
3525
  if (a === "")
2419
3526
  throw new Error("The id can't be empty");
2420
- const columns = isStringArray(c) ? c : void 0;
3527
+ const columns = isValidSelectableColumns(c) ? c : void 0;
2421
3528
  return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
2422
3529
  }
2423
3530
  if (isObject(a) && isString(a.id)) {
2424
3531
  if (a.id === "")
2425
3532
  throw new Error("The id can't be empty");
2426
- const columns = isStringArray(b) ? b : void 0;
3533
+ const columns = isValidSelectableColumns(b) ? b : void 0;
2427
3534
  return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
2428
3535
  }
2429
3536
  if (isObject(a)) {
2430
- const columns = isStringArray(b) ? b : void 0;
3537
+ const columns = isValidSelectableColumns(b) ? b : void 0;
2431
3538
  return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
2432
3539
  }
2433
3540
  throw new Error("Invalid arguments for create method");
@@ -2435,7 +3542,7 @@ class RestRepository extends Query {
2435
3542
  }
2436
3543
  async read(a, b) {
2437
3544
  return __privateGet$4(this, _trace).call(this, "read", async () => {
2438
- const columns = isStringArray(b) ? b : ["*"];
3545
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2439
3546
  if (Array.isArray(a)) {
2440
3547
  if (a.length === 0)
2441
3548
  return [];
@@ -2462,7 +3569,13 @@ class RestRepository extends Query {
2462
3569
  ...__privateGet$4(this, _getFetchProps).call(this)
2463
3570
  });
2464
3571
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2465
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
3572
+ return initObject(
3573
+ __privateGet$4(this, _db),
3574
+ schemaTables,
3575
+ __privateGet$4(this, _table),
3576
+ response,
3577
+ columns
3578
+ );
2466
3579
  } catch (e) {
2467
3580
  if (isObject(e) && e.status === 404) {
2468
3581
  return null;
@@ -2504,17 +3617,17 @@ class RestRepository extends Query {
2504
3617
  ifVersion,
2505
3618
  upsert: false
2506
3619
  });
2507
- const columns = isStringArray(b) ? b : ["*"];
3620
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2508
3621
  const result = await this.read(a, columns);
2509
3622
  return result;
2510
3623
  }
2511
3624
  try {
2512
3625
  if (isString(a) && isObject(b)) {
2513
- const columns = isStringArray(c) ? c : void 0;
3626
+ const columns = isValidSelectableColumns(c) ? c : void 0;
2514
3627
  return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2515
3628
  }
2516
3629
  if (isObject(a) && isString(a.id)) {
2517
- const columns = isStringArray(b) ? b : void 0;
3630
+ const columns = isValidSelectableColumns(b) ? b : void 0;
2518
3631
  return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
2519
3632
  }
2520
3633
  } catch (error) {
@@ -2554,17 +3667,27 @@ class RestRepository extends Query {
2554
3667
  ifVersion,
2555
3668
  upsert: true
2556
3669
  });
2557
- const columns = isStringArray(b) ? b : ["*"];
3670
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2558
3671
  const result = await this.read(a, columns);
2559
3672
  return result;
2560
3673
  }
2561
3674
  if (isString(a) && isObject(b)) {
2562
- const columns = isStringArray(c) ? c : void 0;
2563
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3675
+ if (a === "")
3676
+ throw new Error("The id can't be empty");
3677
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3678
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2564
3679
  }
2565
3680
  if (isObject(a) && isString(a.id)) {
2566
- const columns = isStringArray(c) ? c : void 0;
2567
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3681
+ if (a.id === "")
3682
+ throw new Error("The id can't be empty");
3683
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3684
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3685
+ }
3686
+ if (!isDefined(a) && isObject(b)) {
3687
+ return await this.create(b, c);
3688
+ }
3689
+ if (isObject(a) && !isDefined(a.id)) {
3690
+ return await this.create(a, b);
2568
3691
  }
2569
3692
  throw new Error("Invalid arguments for createOrUpdate method");
2570
3693
  });
@@ -2576,17 +3699,27 @@ class RestRepository extends Query {
2576
3699
  if (a.length === 0)
2577
3700
  return [];
2578
3701
  const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: false });
2579
- const columns = isStringArray(b) ? b : ["*"];
3702
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2580
3703
  const result = await this.read(ids, columns);
2581
3704
  return result;
2582
3705
  }
2583
3706
  if (isString(a) && isObject(b)) {
2584
- const columns = isStringArray(c) ? c : void 0;
2585
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
3707
+ if (a === "")
3708
+ throw new Error("The id can't be empty");
3709
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3710
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
2586
3711
  }
2587
3712
  if (isObject(a) && isString(a.id)) {
2588
- const columns = isStringArray(c) ? c : void 0;
2589
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3713
+ if (a.id === "")
3714
+ throw new Error("The id can't be empty");
3715
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3716
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3717
+ }
3718
+ if (!isDefined(a) && isObject(b)) {
3719
+ return await this.create(b, c);
3720
+ }
3721
+ if (isObject(a) && !isDefined(a.id)) {
3722
+ return await this.create(a, b);
2590
3723
  }
2591
3724
  throw new Error("Invalid arguments for createOrReplace method");
2592
3725
  });
@@ -2603,7 +3736,7 @@ class RestRepository extends Query {
2603
3736
  return o.id;
2604
3737
  throw new Error("Invalid arguments for delete method");
2605
3738
  });
2606
- const columns = isStringArray(b) ? b : ["*"];
3739
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2607
3740
  const result = await this.read(a, columns);
2608
3741
  await __privateMethod$2(this, _deleteRecords, deleteRecords_fn).call(this, ids);
2609
3742
  return result;
@@ -2722,7 +3855,13 @@ class RestRepository extends Query {
2722
3855
  });
2723
3856
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2724
3857
  const records = objects.map(
2725
- (record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record, data.columns ?? ["*"])
3858
+ (record) => initObject(
3859
+ __privateGet$4(this, _db),
3860
+ schemaTables,
3861
+ __privateGet$4(this, _table),
3862
+ record,
3863
+ data.columns ?? ["*"]
3864
+ )
2726
3865
  );
2727
3866
  await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
2728
3867
  return new Page(query, meta, records);
@@ -2752,6 +3891,39 @@ class RestRepository extends Query {
2752
3891
  return result;
2753
3892
  });
2754
3893
  }
3894
+ ask(question, options) {
3895
+ const questionParam = options?.sessionId ? { message: question } : { question };
3896
+ const params = {
3897
+ pathParams: {
3898
+ workspace: "{workspaceId}",
3899
+ dbBranchName: "{dbBranch}",
3900
+ region: "{region}",
3901
+ tableName: __privateGet$4(this, _table),
3902
+ sessionId: options?.sessionId
3903
+ },
3904
+ body: {
3905
+ ...questionParam,
3906
+ rules: options?.rules,
3907
+ searchType: options?.searchType,
3908
+ search: options?.searchType === "keyword" ? options?.search : void 0,
3909
+ vectorSearch: options?.searchType === "vector" ? options?.vectorSearch : void 0
3910
+ },
3911
+ ...__privateGet$4(this, _getFetchProps).call(this)
3912
+ };
3913
+ if (options?.onMessage) {
3914
+ fetchSSERequest({
3915
+ endpoint: "dataPlane",
3916
+ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}",
3917
+ method: "POST",
3918
+ onMessage: (message) => {
3919
+ options.onMessage?.({ answer: message.text, records: message.records });
3920
+ },
3921
+ ...params
3922
+ });
3923
+ } else {
3924
+ return askTableSession(params);
3925
+ }
3926
+ }
2755
3927
  }
2756
3928
  _table = new WeakMap();
2757
3929
  _getFetchProps = new WeakMap();
@@ -2761,7 +3933,7 @@ _schemaTables$2 = new WeakMap();
2761
3933
  _trace = new WeakMap();
2762
3934
  _insertRecordWithoutId = new WeakSet();
2763
3935
  insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
2764
- const record = transformObjectLinks(object);
3936
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2765
3937
  const response = await insertRecord({
2766
3938
  pathParams: {
2767
3939
  workspace: "{workspaceId}",
@@ -2778,7 +3950,9 @@ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
2778
3950
  };
2779
3951
  _insertRecordWithId = new WeakSet();
2780
3952
  insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { createOnly, ifVersion }) {
2781
- const record = transformObjectLinks(object);
3953
+ if (!recordId)
3954
+ return null;
3955
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2782
3956
  const response = await insertRecordWithID({
2783
3957
  pathParams: {
2784
3958
  workspace: "{workspaceId}",
@@ -2796,21 +3970,20 @@ insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { crea
2796
3970
  };
2797
3971
  _insertRecords = new WeakSet();
2798
3972
  insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2799
- const chunkedOperations = chunk(
2800
- objects.map((object) => ({
2801
- insert: { table: __privateGet$4(this, _table), record: transformObjectLinks(object), createOnly, ifVersion }
2802
- })),
2803
- BULK_OPERATION_MAX_SIZE
2804
- );
3973
+ const operations = await promiseMap(objects, async (object) => {
3974
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3975
+ return { insert: { table: __privateGet$4(this, _table), record, createOnly, ifVersion } };
3976
+ });
3977
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
2805
3978
  const ids = [];
2806
- for (const operations of chunkedOperations) {
3979
+ for (const operations2 of chunkedOperations) {
2807
3980
  const { results } = await branchTransaction({
2808
3981
  pathParams: {
2809
3982
  workspace: "{workspaceId}",
2810
3983
  dbBranchName: "{dbBranch}",
2811
3984
  region: "{region}"
2812
3985
  },
2813
- body: { operations },
3986
+ body: { operations: operations2 },
2814
3987
  ...__privateGet$4(this, _getFetchProps).call(this)
2815
3988
  });
2816
3989
  for (const result of results) {
@@ -2825,7 +3998,9 @@ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2825
3998
  };
2826
3999
  _updateRecordWithID = new WeakSet();
2827
4000
  updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2828
- const { id: _id, ...record } = transformObjectLinks(object);
4001
+ if (!recordId)
4002
+ return null;
4003
+ const { id: _id, ...record } = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2829
4004
  try {
2830
4005
  const response = await updateRecordWithID({
2831
4006
  pathParams: {
@@ -2850,21 +4025,20 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2850
4025
  };
2851
4026
  _updateRecords = new WeakSet();
2852
4027
  updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2853
- const chunkedOperations = chunk(
2854
- objects.map(({ id, ...object }) => ({
2855
- update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields: transformObjectLinks(object) }
2856
- })),
2857
- BULK_OPERATION_MAX_SIZE
2858
- );
4028
+ const operations = await promiseMap(objects, async ({ id, ...object }) => {
4029
+ const fields = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
4030
+ return { update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields } };
4031
+ });
4032
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
2859
4033
  const ids = [];
2860
- for (const operations of chunkedOperations) {
4034
+ for (const operations2 of chunkedOperations) {
2861
4035
  const { results } = await branchTransaction({
2862
4036
  pathParams: {
2863
4037
  workspace: "{workspaceId}",
2864
4038
  dbBranchName: "{dbBranch}",
2865
4039
  region: "{region}"
2866
4040
  },
2867
- body: { operations },
4041
+ body: { operations: operations2 },
2868
4042
  ...__privateGet$4(this, _getFetchProps).call(this)
2869
4043
  });
2870
4044
  for (const result of results) {
@@ -2879,6 +4053,8 @@ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2879
4053
  };
2880
4054
  _upsertRecordWithID = new WeakSet();
2881
4055
  upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
4056
+ if (!recordId)
4057
+ return null;
2882
4058
  const response = await upsertRecordWithID({
2883
4059
  pathParams: {
2884
4060
  workspace: "{workspaceId}",
@@ -2896,6 +4072,8 @@ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2896
4072
  };
2897
4073
  _deleteRecord = new WeakSet();
2898
4074
  deleteRecord_fn = async function(recordId, columns = ["*"]) {
4075
+ if (!recordId)
4076
+ return null;
2899
4077
  try {
2900
4078
  const response = await deleteRecord({
2901
4079
  pathParams: {
@@ -2920,7 +4098,7 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2920
4098
  _deleteRecords = new WeakSet();
2921
4099
  deleteRecords_fn = async function(recordIds) {
2922
4100
  const chunkedOperations = chunk(
2923
- recordIds.map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
4101
+ compact(recordIds).map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
2924
4102
  BULK_OPERATION_MAX_SIZE
2925
4103
  );
2926
4104
  for (const operations of chunkedOperations) {
@@ -2937,15 +4115,16 @@ deleteRecords_fn = async function(recordIds) {
2937
4115
  };
2938
4116
  _setCacheQuery = new WeakSet();
2939
4117
  setCacheQuery_fn = async function(query, meta, records) {
2940
- await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
4118
+ await __privateGet$4(this, _cache)?.set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: /* @__PURE__ */ new Date(), meta, records });
2941
4119
  };
2942
4120
  _getCacheQuery = new WeakSet();
2943
4121
  getCacheQuery_fn = async function(query) {
2944
4122
  const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
2945
- const result = await __privateGet$4(this, _cache).get(key);
4123
+ const result = await __privateGet$4(this, _cache)?.get(key);
2946
4124
  if (!result)
2947
4125
  return null;
2948
- const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
4126
+ const defaultTTL = __privateGet$4(this, _cache)?.defaultQueryTTL ?? -1;
4127
+ const { cache: ttl = defaultTTL } = query.getQueryOptions();
2949
4128
  if (ttl < 0)
2950
4129
  return null;
2951
4130
  const hasExpired = result.date.getTime() + ttl < Date.now();
@@ -2962,7 +4141,42 @@ getSchemaTables_fn$1 = async function() {
2962
4141
  __privateSet$4(this, _schemaTables$2, schema.tables);
2963
4142
  return schema.tables;
2964
4143
  };
2965
- const transformObjectLinks = (object) => {
4144
+ _transformObjectToApi = new WeakSet();
4145
+ transformObjectToApi_fn = async function(object) {
4146
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
4147
+ const schema = schemaTables.find((table) => table.name === __privateGet$4(this, _table));
4148
+ if (!schema)
4149
+ throw new Error(`Table ${__privateGet$4(this, _table)} not found in schema`);
4150
+ const result = {};
4151
+ for (const [key, value] of Object.entries(object)) {
4152
+ if (key === "xata")
4153
+ continue;
4154
+ const type = schema.columns.find((column) => column.name === key)?.type;
4155
+ switch (type) {
4156
+ case "link": {
4157
+ result[key] = isIdentifiable(value) ? value.id : value;
4158
+ break;
4159
+ }
4160
+ case "datetime": {
4161
+ result[key] = value instanceof Date ? value.toISOString() : value;
4162
+ break;
4163
+ }
4164
+ case `file`:
4165
+ result[key] = await parseInputFileEntry(value);
4166
+ break;
4167
+ case "file[]":
4168
+ result[key] = await promiseMap(value, (item) => parseInputFileEntry(item));
4169
+ break;
4170
+ case "json":
4171
+ result[key] = stringifyJson(value);
4172
+ break;
4173
+ default:
4174
+ result[key] = value;
4175
+ }
4176
+ }
4177
+ return result;
4178
+ };
4179
+ const removeLinksFromObject = (object) => {
2966
4180
  return Object.entries(object).reduce((acc, [key, value]) => {
2967
4181
  if (key === "xata")
2968
4182
  return acc;
@@ -2999,18 +4213,33 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
2999
4213
  if (item === column.name) {
3000
4214
  return [...acc, "*"];
3001
4215
  }
3002
- if (item.startsWith(`${column.name}.`)) {
4216
+ if (isString(item) && item.startsWith(`${column.name}.`)) {
3003
4217
  const [, ...path] = item.split(".");
3004
4218
  return [...acc, path.join(".")];
3005
4219
  }
3006
4220
  return acc;
3007
4221
  }, []);
3008
- data[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
4222
+ data[column.name] = initObject(
4223
+ db,
4224
+ schemaTables,
4225
+ linkTable,
4226
+ value,
4227
+ selectedLinkColumns
4228
+ );
3009
4229
  } else {
3010
4230
  data[column.name] = null;
3011
4231
  }
3012
4232
  break;
3013
4233
  }
4234
+ case "file":
4235
+ data[column.name] = isDefined(value) ? new XataFile(value) : null;
4236
+ break;
4237
+ case "file[]":
4238
+ data[column.name] = value?.map((item) => new XataFile(item)) ?? null;
4239
+ break;
4240
+ case "json":
4241
+ data[column.name] = parseJson(value);
4242
+ break;
3014
4243
  default:
3015
4244
  data[column.name] = value ?? null;
3016
4245
  if (column.notNull === true && value === null) {
@@ -3020,30 +4249,33 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
3020
4249
  }
3021
4250
  }
3022
4251
  const record = { ...data };
4252
+ const serializable = { xata, ...removeLinksFromObject(data) };
4253
+ const metadata = xata !== void 0 ? { ...xata, createdAt: new Date(xata.createdAt), updatedAt: new Date(xata.updatedAt) } : void 0;
3023
4254
  record.read = function(columns2) {
3024
4255
  return db[table].read(record["id"], columns2);
3025
4256
  };
3026
4257
  record.update = function(data2, b, c) {
3027
- const columns2 = isStringArray(b) ? b : ["*"];
4258
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
3028
4259
  const ifVersion = parseIfVersion(b, c);
3029
4260
  return db[table].update(record["id"], data2, columns2, { ifVersion });
3030
4261
  };
3031
4262
  record.replace = function(data2, b, c) {
3032
- const columns2 = isStringArray(b) ? b : ["*"];
4263
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
3033
4264
  const ifVersion = parseIfVersion(b, c);
3034
4265
  return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
3035
4266
  };
3036
4267
  record.delete = function() {
3037
4268
  return db[table].delete(record["id"]);
3038
4269
  };
4270
+ record.xata = Object.freeze(metadata);
3039
4271
  record.getMetadata = function() {
3040
- return xata;
4272
+ return record.xata;
3041
4273
  };
3042
4274
  record.toSerializable = function() {
3043
- return JSON.parse(JSON.stringify(transformObjectLinks(data)));
4275
+ return JSON.parse(JSON.stringify(serializable));
3044
4276
  };
3045
4277
  record.toString = function() {
3046
- return JSON.stringify(transformObjectLinks(data));
4278
+ return JSON.stringify(serializable);
3047
4279
  };
3048
4280
  for (const prop of ["read", "update", "replace", "delete", "getMetadata", "toSerializable", "toString"]) {
3049
4281
  Object.defineProperty(record, prop, { enumerable: false });
@@ -3061,11 +4293,7 @@ function extractId(value) {
3061
4293
  function isValidColumn(columns, column) {
3062
4294
  if (columns.includes("*"))
3063
4295
  return true;
3064
- if (column.type === "link") {
3065
- const linkColumns = columns.filter((item) => item.startsWith(column.name));
3066
- return linkColumns.length > 0;
3067
- }
3068
- return columns.includes(column.name);
4296
+ return columns.filter((item) => isString(item) && item.startsWith(column.name)).length > 0;
3069
4297
  }
3070
4298
  function parseIfVersion(...args) {
3071
4299
  for (const arg of args) {
@@ -3076,6 +4304,12 @@ function parseIfVersion(...args) {
3076
4304
  return void 0;
3077
4305
  }
3078
4306
 
4307
+ var __defProp$3 = Object.defineProperty;
4308
+ var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4309
+ var __publicField$3 = (obj, key, value) => {
4310
+ __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
4311
+ return value;
4312
+ };
3079
4313
  var __accessCheck$3 = (obj, member, msg) => {
3080
4314
  if (!member.has(obj))
3081
4315
  throw TypeError("Cannot " + msg);
@@ -3098,6 +4332,8 @@ var _map;
3098
4332
  class SimpleCache {
3099
4333
  constructor(options = {}) {
3100
4334
  __privateAdd$3(this, _map, void 0);
4335
+ __publicField$3(this, "capacity");
4336
+ __publicField$3(this, "defaultQueryTTL");
3101
4337
  __privateSet$3(this, _map, /* @__PURE__ */ new Map());
3102
4338
  this.capacity = options.max ?? 500;
3103
4339
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
@@ -3262,6 +4498,7 @@ search_fn = async function(query, options, pluginOptions) {
3262
4498
  const { tables, fuzziness, highlight, prefix, page } = options ?? {};
3263
4499
  const { records } = await searchBranch({
3264
4500
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4501
+ // @ts-ignore https://github.com/xataio/client-ts/issues/313
3265
4502
  body: { tables, query, fuzziness, prefix, highlight, page },
3266
4503
  ...pluginOptions
3267
4504
  });
@@ -3279,6 +4516,78 @@ getSchemaTables_fn = async function(pluginOptions) {
3279
4516
  return schema.tables;
3280
4517
  };
3281
4518
 
4519
+ function escapeElement(elementRepresentation) {
4520
+ const escaped = elementRepresentation.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
4521
+ return '"' + escaped + '"';
4522
+ }
4523
+ function arrayString(val) {
4524
+ let result = "{";
4525
+ for (let i = 0; i < val.length; i++) {
4526
+ if (i > 0) {
4527
+ result = result + ",";
4528
+ }
4529
+ if (val[i] === null || typeof val[i] === "undefined") {
4530
+ result = result + "NULL";
4531
+ } else if (Array.isArray(val[i])) {
4532
+ result = result + arrayString(val[i]);
4533
+ } else if (val[i] instanceof Buffer) {
4534
+ result += "\\\\x" + val[i].toString("hex");
4535
+ } else {
4536
+ result += escapeElement(prepareValue(val[i]));
4537
+ }
4538
+ }
4539
+ result = result + "}";
4540
+ return result;
4541
+ }
4542
+ function prepareValue(value) {
4543
+ if (!isDefined(value))
4544
+ return null;
4545
+ if (value instanceof Date) {
4546
+ return value.toISOString();
4547
+ }
4548
+ if (Array.isArray(value)) {
4549
+ return arrayString(value);
4550
+ }
4551
+ if (isObject(value)) {
4552
+ return JSON.stringify(value);
4553
+ }
4554
+ try {
4555
+ return value.toString();
4556
+ } catch (e) {
4557
+ return value;
4558
+ }
4559
+ }
4560
+ function prepareParams(param1, param2) {
4561
+ if (isString(param1)) {
4562
+ return { statement: param1, params: param2?.map((value) => prepareValue(value)) };
4563
+ }
4564
+ if (isStringArray(param1)) {
4565
+ const statement = param1.reduce((acc, curr, index) => {
4566
+ return acc + curr + (index < (param2?.length ?? 0) ? "$" + (index + 1) : "");
4567
+ }, "");
4568
+ return { statement, params: param2?.map((value) => prepareValue(value)) };
4569
+ }
4570
+ if (isObject(param1)) {
4571
+ const { statement, params, consistency } = param1;
4572
+ return { statement, params: params?.map((value) => prepareValue(value)), consistency };
4573
+ }
4574
+ throw new Error("Invalid query");
4575
+ }
4576
+
4577
+ class SQLPlugin extends XataPlugin {
4578
+ build(pluginOptions) {
4579
+ return async (param1, ...param2) => {
4580
+ const { statement, params, consistency } = prepareParams(param1, param2);
4581
+ const { records, warning } = await sqlQuery({
4582
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4583
+ body: { statement, params, consistency },
4584
+ ...pluginOptions
4585
+ });
4586
+ return { records, warning };
4587
+ };
4588
+ }
4589
+ }
4590
+
3282
4591
  class TransactionPlugin extends XataPlugin {
3283
4592
  build(pluginOptions) {
3284
4593
  return {
@@ -3294,6 +4603,12 @@ class TransactionPlugin extends XataPlugin {
3294
4603
  }
3295
4604
  }
3296
4605
 
4606
+ var __defProp$2 = Object.defineProperty;
4607
+ var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4608
+ var __publicField$2 = (obj, key, value) => {
4609
+ __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
4610
+ return value;
4611
+ };
3297
4612
  var __accessCheck = (obj, member, msg) => {
3298
4613
  if (!member.has(obj))
3299
4614
  throw TypeError("Cannot " + msg);
@@ -3323,29 +4638,32 @@ const buildClient = (plugins) => {
3323
4638
  __privateAdd(this, _parseOptions);
3324
4639
  __privateAdd(this, _getFetchProps);
3325
4640
  __privateAdd(this, _options, void 0);
4641
+ __publicField$2(this, "db");
4642
+ __publicField$2(this, "search");
4643
+ __publicField$2(this, "transactions");
4644
+ __publicField$2(this, "sql");
4645
+ __publicField$2(this, "files");
3326
4646
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
3327
4647
  __privateSet(this, _options, safeOptions);
3328
4648
  const pluginOptions = {
3329
4649
  ...__privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
3330
- cache: safeOptions.cache
4650
+ cache: safeOptions.cache,
4651
+ host: safeOptions.host
3331
4652
  };
3332
4653
  const db = new SchemaPlugin(schemaTables).build(pluginOptions);
3333
4654
  const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
3334
4655
  const transactions = new TransactionPlugin().build(pluginOptions);
4656
+ const sql = new SQLPlugin().build(pluginOptions);
4657
+ const files = new FilesPlugin().build(pluginOptions);
3335
4658
  this.db = db;
3336
4659
  this.search = search;
3337
4660
  this.transactions = transactions;
4661
+ this.sql = sql;
4662
+ this.files = files;
3338
4663
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
3339
4664
  if (namespace === void 0)
3340
4665
  continue;
3341
- const result = namespace.build(pluginOptions);
3342
- if (result instanceof Promise) {
3343
- void result.then((namespace2) => {
3344
- this[key] = namespace2;
3345
- });
3346
- } else {
3347
- this[key] = result;
3348
- }
4666
+ this[key] = namespace.build(pluginOptions);
3349
4667
  }
3350
4668
  }
3351
4669
  async getConfig() {
@@ -3363,7 +4681,6 @@ const buildClient = (plugins) => {
3363
4681
  }
3364
4682
  const fetch = getFetchImplementation(options?.fetch);
3365
4683
  const databaseURL = options?.databaseURL || getDatabaseURL();
3366
- const branch = options?.branch || getBranch() || "main";
3367
4684
  const apiKey = options?.apiKey || getAPIKey();
3368
4685
  const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
3369
4686
  const trace = options?.trace ?? defaultTrace;
@@ -3376,6 +4693,26 @@ const buildClient = (plugins) => {
3376
4693
  if (!databaseURL) {
3377
4694
  throw new Error("Option databaseURL is required");
3378
4695
  }
4696
+ const envBranch = getBranch();
4697
+ const previewBranch = getPreviewBranch();
4698
+ const branch = options?.branch || previewBranch || envBranch || "main";
4699
+ if (!!previewBranch && branch !== previewBranch) {
4700
+ console.warn(
4701
+ `Ignoring preview branch ${previewBranch} because branch option was passed to the client constructor with value ${branch}`
4702
+ );
4703
+ } else if (!!envBranch && branch !== envBranch) {
4704
+ console.warn(
4705
+ `Ignoring branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
4706
+ );
4707
+ } else if (!!previewBranch && !!envBranch && previewBranch !== envBranch) {
4708
+ console.warn(
4709
+ `Ignoring preview branch ${previewBranch} and branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
4710
+ );
4711
+ } else if (!previewBranch && !envBranch && options?.branch === void 0) {
4712
+ console.warn(
4713
+ `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.`
4714
+ );
4715
+ }
3379
4716
  return {
3380
4717
  fetch,
3381
4718
  databaseURL,
@@ -3403,6 +4740,7 @@ const buildClient = (plugins) => {
3403
4740
  fetch,
3404
4741
  apiKey,
3405
4742
  apiUrl: "",
4743
+ // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
3406
4744
  workspacesApiUrl: (path, params) => {
3407
4745
  const hasBranch = params.dbBranchName ?? params.branch;
3408
4746
  const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branch}` : "");
@@ -3418,11 +4756,17 @@ const buildClient = (plugins) => {
3418
4756
  class BaseClient extends buildClient() {
3419
4757
  }
3420
4758
 
4759
+ var __defProp$1 = Object.defineProperty;
4760
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4761
+ var __publicField$1 = (obj, key, value) => {
4762
+ __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
4763
+ return value;
4764
+ };
3421
4765
  const META = "__";
3422
4766
  const VALUE = "___";
3423
4767
  class Serializer {
3424
4768
  constructor() {
3425
- this.classes = {};
4769
+ __publicField$1(this, "classes", {});
3426
4770
  }
3427
4771
  add(clazz) {
3428
4772
  this.classes[clazz.name] = clazz;
@@ -3500,15 +4844,23 @@ function buildWorkerRunner(config) {
3500
4844
  };
3501
4845
  }
3502
4846
 
4847
+ var __defProp = Object.defineProperty;
4848
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4849
+ var __publicField = (obj, key, value) => {
4850
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4851
+ return value;
4852
+ };
3503
4853
  class XataError extends Error {
3504
4854
  constructor(message, status) {
3505
4855
  super(message);
4856
+ __publicField(this, "status");
3506
4857
  this.status = status;
3507
4858
  }
3508
4859
  }
3509
4860
 
3510
4861
  exports.BaseClient = BaseClient;
3511
4862
  exports.FetcherError = FetcherError;
4863
+ exports.FilesPlugin = FilesPlugin;
3512
4864
  exports.Operations = operationsByTag;
3513
4865
  exports.PAGINATION_DEFAULT_OFFSET = PAGINATION_DEFAULT_OFFSET;
3514
4866
  exports.PAGINATION_DEFAULT_SIZE = PAGINATION_DEFAULT_SIZE;
@@ -3517,8 +4869,10 @@ exports.PAGINATION_MAX_SIZE = PAGINATION_MAX_SIZE;
3517
4869
  exports.Page = Page;
3518
4870
  exports.Query = Query;
3519
4871
  exports.RecordArray = RecordArray;
4872
+ exports.RecordColumnTypes = RecordColumnTypes;
3520
4873
  exports.Repository = Repository;
3521
4874
  exports.RestRepository = RestRepository;
4875
+ exports.SQLPlugin = SQLPlugin;
3522
4876
  exports.SchemaPlugin = SchemaPlugin;
3523
4877
  exports.SearchPlugin = SearchPlugin;
3524
4878
  exports.Serializer = Serializer;
@@ -3526,6 +4880,7 @@ exports.SimpleCache = SimpleCache;
3526
4880
  exports.XataApiClient = XataApiClient;
3527
4881
  exports.XataApiPlugin = XataApiPlugin;
3528
4882
  exports.XataError = XataError;
4883
+ exports.XataFile = XataFile;
3529
4884
  exports.XataPlugin = XataPlugin;
3530
4885
  exports.acceptWorkspaceMemberInvite = acceptWorkspaceMemberInvite;
3531
4886
  exports.addGitBranchesEntry = addGitBranchesEntry;
@@ -3533,8 +4888,11 @@ exports.addTableColumn = addTableColumn;
3533
4888
  exports.aggregateTable = aggregateTable;
3534
4889
  exports.applyBranchSchemaEdit = applyBranchSchemaEdit;
3535
4890
  exports.askTable = askTable;
4891
+ exports.askTableSession = askTableSession;
3536
4892
  exports.branchTransaction = branchTransaction;
3537
4893
  exports.buildClient = buildClient;
4894
+ exports.buildPreviewBranchName = buildPreviewBranchName;
4895
+ exports.buildProviderString = buildProviderString;
3538
4896
  exports.buildWorkerRunner = buildWorkerRunner;
3539
4897
  exports.bulkInsertTableRecords = bulkInsertTableRecords;
3540
4898
  exports.cancelWorkspaceMemberInvite = cancelWorkspaceMemberInvite;
@@ -3542,6 +4900,7 @@ exports.compareBranchSchemas = compareBranchSchemas;
3542
4900
  exports.compareBranchWithUserSchema = compareBranchWithUserSchema;
3543
4901
  exports.compareMigrationRequest = compareMigrationRequest;
3544
4902
  exports.contains = contains;
4903
+ exports.copyBranch = copyBranch;
3545
4904
  exports.createBranch = createBranch;
3546
4905
  exports.createDatabase = createDatabase;
3547
4906
  exports.createMigrationRequest = createMigrationRequest;
@@ -3552,18 +4911,24 @@ exports.deleteBranch = deleteBranch;
3552
4911
  exports.deleteColumn = deleteColumn;
3553
4912
  exports.deleteDatabase = deleteDatabase;
3554
4913
  exports.deleteDatabaseGithubSettings = deleteDatabaseGithubSettings;
4914
+ exports.deleteFile = deleteFile;
4915
+ exports.deleteFileItem = deleteFileItem;
4916
+ exports.deleteOAuthAccessToken = deleteOAuthAccessToken;
3555
4917
  exports.deleteRecord = deleteRecord;
3556
4918
  exports.deleteTable = deleteTable;
3557
4919
  exports.deleteUser = deleteUser;
3558
4920
  exports.deleteUserAPIKey = deleteUserAPIKey;
4921
+ exports.deleteUserOAuthClient = deleteUserOAuthClient;
3559
4922
  exports.deleteWorkspace = deleteWorkspace;
3560
4923
  exports.deserialize = deserialize;
3561
4924
  exports.endsWith = endsWith;
3562
4925
  exports.equals = equals;
3563
4926
  exports.executeBranchMigrationPlan = executeBranchMigrationPlan;
3564
4927
  exports.exists = exists;
4928
+ exports.fileAccess = fileAccess;
3565
4929
  exports.ge = ge;
3566
4930
  exports.getAPIKey = getAPIKey;
4931
+ exports.getAuthorizationCode = getAuthorizationCode;
3567
4932
  exports.getBranch = getBranch;
3568
4933
  exports.getBranchDetails = getBranchDetails;
3569
4934
  exports.getBranchList = getBranchList;
@@ -3577,18 +4942,24 @@ exports.getDatabaseGithubSettings = getDatabaseGithubSettings;
3577
4942
  exports.getDatabaseList = getDatabaseList;
3578
4943
  exports.getDatabaseMetadata = getDatabaseMetadata;
3579
4944
  exports.getDatabaseURL = getDatabaseURL;
4945
+ exports.getFile = getFile;
4946
+ exports.getFileItem = getFileItem;
3580
4947
  exports.getGitBranchesMapping = getGitBranchesMapping;
3581
4948
  exports.getHostUrl = getHostUrl;
3582
4949
  exports.getMigrationRequest = getMigrationRequest;
3583
4950
  exports.getMigrationRequestIsMerged = getMigrationRequestIsMerged;
4951
+ exports.getPreviewBranch = getPreviewBranch;
3584
4952
  exports.getRecord = getRecord;
3585
4953
  exports.getTableColumns = getTableColumns;
3586
4954
  exports.getTableSchema = getTableSchema;
3587
4955
  exports.getUser = getUser;
3588
4956
  exports.getUserAPIKeys = getUserAPIKeys;
4957
+ exports.getUserOAuthAccessTokens = getUserOAuthAccessTokens;
4958
+ exports.getUserOAuthClients = getUserOAuthClients;
3589
4959
  exports.getWorkspace = getWorkspace;
3590
4960
  exports.getWorkspaceMembersList = getWorkspaceMembersList;
3591
4961
  exports.getWorkspacesList = getWorkspacesList;
4962
+ exports.grantAuthorizationCode = grantAuthorizationCode;
3592
4963
  exports.greaterEquals = greaterEquals;
3593
4964
  exports.greaterThan = greaterThan;
3594
4965
  exports.greaterThanEquals = greaterThanEquals;
@@ -3607,6 +4978,8 @@ exports.isHostProviderAlias = isHostProviderAlias;
3607
4978
  exports.isHostProviderBuilder = isHostProviderBuilder;
3608
4979
  exports.isIdentifiable = isIdentifiable;
3609
4980
  exports.isNot = isNot;
4981
+ exports.isValidExpandedColumn = isValidExpandedColumn;
4982
+ exports.isValidSelectableColumns = isValidSelectableColumns;
3610
4983
  exports.isXataRecord = isXataRecord;
3611
4984
  exports.le = le;
3612
4985
  exports.lessEquals = lessEquals;
@@ -3623,24 +4996,31 @@ exports.parseProviderString = parseProviderString;
3623
4996
  exports.parseWorkspacesUrlParts = parseWorkspacesUrlParts;
3624
4997
  exports.pattern = pattern;
3625
4998
  exports.previewBranchSchemaEdit = previewBranchSchemaEdit;
4999
+ exports.pushBranchMigrations = pushBranchMigrations;
5000
+ exports.putFile = putFile;
5001
+ exports.putFileItem = putFileItem;
3626
5002
  exports.queryMigrationRequests = queryMigrationRequests;
3627
5003
  exports.queryTable = queryTable;
3628
5004
  exports.removeGitBranchesEntry = removeGitBranchesEntry;
3629
5005
  exports.removeWorkspaceMember = removeWorkspaceMember;
5006
+ exports.renameDatabase = renameDatabase;
3630
5007
  exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite;
3631
5008
  exports.resolveBranch = resolveBranch;
3632
5009
  exports.searchBranch = searchBranch;
3633
5010
  exports.searchTable = searchTable;
3634
5011
  exports.serialize = serialize;
3635
5012
  exports.setTableSchema = setTableSchema;
5013
+ exports.sqlQuery = sqlQuery;
3636
5014
  exports.startsWith = startsWith;
3637
5015
  exports.summarizeTable = summarizeTable;
5016
+ exports.transformImage = transformImage;
3638
5017
  exports.updateBranchMetadata = updateBranchMetadata;
3639
5018
  exports.updateBranchSchema = updateBranchSchema;
3640
5019
  exports.updateColumn = updateColumn;
3641
5020
  exports.updateDatabaseGithubSettings = updateDatabaseGithubSettings;
3642
5021
  exports.updateDatabaseMetadata = updateDatabaseMetadata;
3643
5022
  exports.updateMigrationRequest = updateMigrationRequest;
5023
+ exports.updateOAuthAccessToken = updateOAuthAccessToken;
3644
5024
  exports.updateRecordWithID = updateRecordWithID;
3645
5025
  exports.updateTable = updateTable;
3646
5026
  exports.updateUser = updateUser;