@xata.io/client 0.0.0-alpha.vfd68f4d → 0.0.0-alpha.vfd6ce53

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -18,7 +18,8 @@ const TraceAttributes = {
18
18
  HTTP_METHOD: "http.method",
19
19
  HTTP_URL: "http.url",
20
20
  HTTP_ROUTE: "http.route",
21
- HTTP_TARGET: "http.target"
21
+ HTTP_TARGET: "http.target",
22
+ CLOUDFLARE_RAY_ID: "cf.ray"
22
23
  };
23
24
 
24
25
  function notEmpty(value) {
@@ -27,8 +28,18 @@ function notEmpty(value) {
27
28
  function compact(arr) {
28
29
  return arr.filter(notEmpty);
29
30
  }
31
+ function compactObject(obj) {
32
+ return Object.fromEntries(Object.entries(obj).filter(([, value]) => notEmpty(value)));
33
+ }
34
+ function isBlob(value) {
35
+ try {
36
+ return value instanceof Blob;
37
+ } catch (error) {
38
+ return false;
39
+ }
40
+ }
30
41
  function isObject(value) {
31
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
42
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date) && !isBlob(value);
32
43
  }
33
44
  function isDefined(value) {
34
45
  return value !== null && value !== void 0;
@@ -83,6 +94,27 @@ function chunk(array, chunkSize) {
83
94
  async function timeout(ms) {
84
95
  return new Promise((resolve) => setTimeout(resolve, ms));
85
96
  }
97
+ function timeoutWithCancel(ms) {
98
+ let timeoutId;
99
+ const promise = new Promise((resolve) => {
100
+ timeoutId = setTimeout(() => {
101
+ resolve();
102
+ }, ms);
103
+ });
104
+ return {
105
+ cancel: () => clearTimeout(timeoutId),
106
+ promise
107
+ };
108
+ }
109
+ function promiseMap(inputValues, mapper) {
110
+ const reducer = (acc$, inputValue) => acc$.then(
111
+ (acc) => mapper(inputValue).then((result) => {
112
+ acc.push(result);
113
+ return acc;
114
+ })
115
+ );
116
+ return inputValues.reduce(reducer, Promise.resolve([]));
117
+ }
86
118
 
87
119
  function getEnvironment() {
88
120
  try {
@@ -91,8 +123,10 @@ function getEnvironment() {
91
123
  apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
92
124
  databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
93
125
  branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
94
- envBranch: process.env.VERCEL_GIT_COMMIT_REF ?? process.env.CF_PAGES_BRANCH ?? process.env.BRANCH,
95
- fallbackBranch: process.env.XATA_FALLBACK_BRANCH ?? getGlobalFallbackBranch()
126
+ deployPreview: process.env.XATA_PREVIEW,
127
+ deployPreviewBranch: process.env.XATA_PREVIEW_BRANCH,
128
+ vercelGitCommitRef: process.env.VERCEL_GIT_COMMIT_REF,
129
+ vercelGitRepoOwner: process.env.VERCEL_GIT_REPO_OWNER
96
130
  };
97
131
  }
98
132
  } catch (err) {
@@ -103,8 +137,10 @@ function getEnvironment() {
103
137
  apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
104
138
  databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
105
139
  branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
106
- envBranch: Deno.env.get("VERCEL_GIT_COMMIT_REF") ?? Deno.env.get("CF_PAGES_BRANCH") ?? Deno.env.get("BRANCH"),
107
- fallbackBranch: Deno.env.get("XATA_FALLBACK_BRANCH") ?? getGlobalFallbackBranch()
140
+ deployPreview: Deno.env.get("XATA_PREVIEW"),
141
+ deployPreviewBranch: Deno.env.get("XATA_PREVIEW_BRANCH"),
142
+ vercelGitCommitRef: Deno.env.get("VERCEL_GIT_COMMIT_REF"),
143
+ vercelGitRepoOwner: Deno.env.get("VERCEL_GIT_REPO_OWNER")
108
144
  };
109
145
  }
110
146
  } catch (err) {
@@ -113,8 +149,10 @@ function getEnvironment() {
113
149
  apiKey: getGlobalApiKey(),
114
150
  databaseURL: getGlobalDatabaseURL(),
115
151
  branch: getGlobalBranch(),
116
- envBranch: void 0,
117
- fallbackBranch: getGlobalFallbackBranch()
152
+ deployPreview: void 0,
153
+ deployPreviewBranch: void 0,
154
+ vercelGitCommitRef: void 0,
155
+ vercelGitRepoOwner: void 0
118
156
  };
119
157
  }
120
158
  function getEnableBrowserVariable() {
@@ -157,36 +195,48 @@ function getGlobalBranch() {
157
195
  return void 0;
158
196
  }
159
197
  }
160
- function getGlobalFallbackBranch() {
198
+ function getDatabaseURL() {
161
199
  try {
162
- return XATA_FALLBACK_BRANCH;
200
+ const { databaseURL } = getEnvironment();
201
+ return databaseURL;
163
202
  } catch (err) {
164
203
  return void 0;
165
204
  }
166
205
  }
167
- async function getGitBranch() {
168
- const cmd = ["git", "branch", "--show-current"];
169
- const fullCmd = cmd.join(" ");
170
- const nodeModule = ["child", "process"].join("_");
171
- const execOptions = { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] };
206
+ function getAPIKey() {
172
207
  try {
173
- const { execSync } = await import(nodeModule);
174
- return execSync(fullCmd, execOptions).toString().trim();
208
+ const { apiKey } = getEnvironment();
209
+ return apiKey;
175
210
  } catch (err) {
211
+ return void 0;
176
212
  }
213
+ }
214
+ function getBranch() {
177
215
  try {
178
- if (isObject(Deno)) {
179
- const process2 = Deno.run({ cmd, stdout: "piped", stderr: "null" });
180
- return new TextDecoder().decode(await process2.output()).trim();
181
- }
216
+ const { branch } = getEnvironment();
217
+ return branch;
182
218
  } catch (err) {
219
+ return void 0;
183
220
  }
184
221
  }
185
-
186
- function getAPIKey() {
222
+ function buildPreviewBranchName({ org, branch }) {
223
+ return `preview-${org}-${branch}`;
224
+ }
225
+ function getPreviewBranch() {
187
226
  try {
188
- const { apiKey } = getEnvironment();
189
- return apiKey;
227
+ const { deployPreview, deployPreviewBranch, vercelGitCommitRef, vercelGitRepoOwner } = getEnvironment();
228
+ if (deployPreviewBranch)
229
+ return deployPreviewBranch;
230
+ switch (deployPreview) {
231
+ case "vercel": {
232
+ if (!vercelGitCommitRef || !vercelGitRepoOwner) {
233
+ console.warn("XATA_PREVIEW=vercel but VERCEL_GIT_COMMIT_REF or VERCEL_GIT_REPO_OWNER is not valid");
234
+ return void 0;
235
+ }
236
+ return buildPreviewBranchName({ org: vercelGitRepoOwner, branch: vercelGitCommitRef });
237
+ }
238
+ }
239
+ return void 0;
190
240
  } catch (err) {
191
241
  return void 0;
192
242
  }
@@ -215,13 +265,13 @@ var __privateMethod$4 = (obj, member, method) => {
215
265
  return method;
216
266
  };
217
267
  var _fetch, _queue, _concurrency, _enqueue, enqueue_fn;
268
+ const REQUEST_TIMEOUT = 5 * 60 * 1e3;
218
269
  function getFetchImplementation(userFetch) {
219
270
  const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
220
- const fetchImpl = userFetch ?? globalFetch;
271
+ const globalThisFetch = typeof globalThis !== "undefined" ? globalThis.fetch : void 0;
272
+ const fetchImpl = userFetch ?? globalFetch ?? globalThisFetch;
221
273
  if (!fetchImpl) {
222
- throw new Error(
223
- `Couldn't find \`fetch\`. Install a fetch implementation such as \`node-fetch\` and pass it explicitly.`
224
- );
274
+ throw new Error(`Couldn't find a global \`fetch\`. Pass a fetch implementation explicitly.`);
225
275
  }
226
276
  return fetchImpl;
227
277
  }
@@ -246,18 +296,22 @@ class ApiRequestPool {
246
296
  return __privateGet$8(this, _fetch);
247
297
  }
248
298
  request(url, options) {
249
- const start = new Date();
250
- const fetch2 = this.getFetch();
299
+ const start = /* @__PURE__ */ new Date();
300
+ const fetchImpl = this.getFetch();
251
301
  const runRequest = async (stalled = false) => {
252
- const response = await fetch2(url, options);
302
+ const { promise, cancel } = timeoutWithCancel(REQUEST_TIMEOUT);
303
+ const response = await Promise.race([fetchImpl(url, options), promise.then(() => null)]).finally(cancel);
304
+ if (!response) {
305
+ throw new Error("Request timed out");
306
+ }
253
307
  if (response.status === 429) {
254
308
  const rateLimitReset = parseNumber(response.headers?.get("x-ratelimit-reset")) ?? 1;
255
309
  await timeout(rateLimitReset * 1e3);
256
310
  return await runRequest(true);
257
311
  }
258
312
  if (stalled) {
259
- const stalledTime = new Date().getTime() - start.getTime();
260
- console.warn(`A request to Xata hit your workspace limits, was retried and stalled for ${stalledTime}ms`);
313
+ const stalledTime = (/* @__PURE__ */ new Date()).getTime() - start.getTime();
314
+ console.warn(`A request to Xata hit branch rate limits, was retried and stalled for ${stalledTime}ms`);
261
315
  }
262
316
  return response;
263
317
  };
@@ -299,7 +353,180 @@ function generateUUID() {
299
353
  });
300
354
  }
301
355
 
302
- const VERSION = "0.22.0";
356
+ async function getBytes(stream, onChunk) {
357
+ const reader = stream.getReader();
358
+ let result;
359
+ while (!(result = await reader.read()).done) {
360
+ onChunk(result.value);
361
+ }
362
+ }
363
+ function getLines(onLine) {
364
+ let buffer;
365
+ let position;
366
+ let fieldLength;
367
+ let discardTrailingNewline = false;
368
+ return function onChunk(arr) {
369
+ if (buffer === void 0) {
370
+ buffer = arr;
371
+ position = 0;
372
+ fieldLength = -1;
373
+ } else {
374
+ buffer = concat(buffer, arr);
375
+ }
376
+ const bufLength = buffer.length;
377
+ let lineStart = 0;
378
+ while (position < bufLength) {
379
+ if (discardTrailingNewline) {
380
+ if (buffer[position] === 10 /* NewLine */) {
381
+ lineStart = ++position;
382
+ }
383
+ discardTrailingNewline = false;
384
+ }
385
+ let lineEnd = -1;
386
+ for (; position < bufLength && lineEnd === -1; ++position) {
387
+ switch (buffer[position]) {
388
+ case 58 /* Colon */:
389
+ if (fieldLength === -1) {
390
+ fieldLength = position - lineStart;
391
+ }
392
+ break;
393
+ case 13 /* CarriageReturn */:
394
+ discardTrailingNewline = true;
395
+ case 10 /* NewLine */:
396
+ lineEnd = position;
397
+ break;
398
+ }
399
+ }
400
+ if (lineEnd === -1) {
401
+ break;
402
+ }
403
+ onLine(buffer.subarray(lineStart, lineEnd), fieldLength);
404
+ lineStart = position;
405
+ fieldLength = -1;
406
+ }
407
+ if (lineStart === bufLength) {
408
+ buffer = void 0;
409
+ } else if (lineStart !== 0) {
410
+ buffer = buffer.subarray(lineStart);
411
+ position -= lineStart;
412
+ }
413
+ };
414
+ }
415
+ function getMessages(onId, onRetry, onMessage) {
416
+ let message = newMessage();
417
+ const decoder = new TextDecoder();
418
+ return function onLine(line, fieldLength) {
419
+ if (line.length === 0) {
420
+ onMessage?.(message);
421
+ message = newMessage();
422
+ } else if (fieldLength > 0) {
423
+ const field = decoder.decode(line.subarray(0, fieldLength));
424
+ const valueOffset = fieldLength + (line[fieldLength + 1] === 32 /* Space */ ? 2 : 1);
425
+ const value = decoder.decode(line.subarray(valueOffset));
426
+ switch (field) {
427
+ case "data":
428
+ message.data = message.data ? message.data + "\n" + value : value;
429
+ break;
430
+ case "event":
431
+ message.event = value;
432
+ break;
433
+ case "id":
434
+ onId(message.id = value);
435
+ break;
436
+ case "retry":
437
+ const retry = parseInt(value, 10);
438
+ if (!isNaN(retry)) {
439
+ onRetry(message.retry = retry);
440
+ }
441
+ break;
442
+ }
443
+ }
444
+ };
445
+ }
446
+ function concat(a, b) {
447
+ const res = new Uint8Array(a.length + b.length);
448
+ res.set(a);
449
+ res.set(b, a.length);
450
+ return res;
451
+ }
452
+ function newMessage() {
453
+ return {
454
+ data: "",
455
+ event: "",
456
+ id: "",
457
+ retry: void 0
458
+ };
459
+ }
460
+ const EventStreamContentType = "text/event-stream";
461
+ const LastEventId = "last-event-id";
462
+ function fetchEventSource(input, {
463
+ signal: inputSignal,
464
+ headers: inputHeaders,
465
+ onopen: inputOnOpen,
466
+ onmessage,
467
+ onclose,
468
+ onerror,
469
+ fetch: inputFetch,
470
+ ...rest
471
+ }) {
472
+ return new Promise((resolve, reject) => {
473
+ const headers = { ...inputHeaders };
474
+ if (!headers.accept) {
475
+ headers.accept = EventStreamContentType;
476
+ }
477
+ let curRequestController;
478
+ function dispose() {
479
+ curRequestController.abort();
480
+ }
481
+ inputSignal?.addEventListener("abort", () => {
482
+ dispose();
483
+ resolve();
484
+ });
485
+ const fetchImpl = inputFetch ?? fetch;
486
+ const onopen = inputOnOpen ?? defaultOnOpen;
487
+ async function create() {
488
+ curRequestController = new AbortController();
489
+ try {
490
+ const response = await fetchImpl(input, {
491
+ ...rest,
492
+ headers,
493
+ signal: curRequestController.signal
494
+ });
495
+ await onopen(response);
496
+ await getBytes(
497
+ response.body,
498
+ getLines(
499
+ getMessages(
500
+ (id) => {
501
+ if (id) {
502
+ headers[LastEventId] = id;
503
+ } else {
504
+ delete headers[LastEventId];
505
+ }
506
+ },
507
+ (_retry) => {
508
+ },
509
+ onmessage
510
+ )
511
+ )
512
+ );
513
+ onclose?.();
514
+ dispose();
515
+ resolve();
516
+ } catch (err) {
517
+ }
518
+ }
519
+ create();
520
+ });
521
+ }
522
+ function defaultOnOpen(response) {
523
+ const contentType = response.headers?.get("content-type");
524
+ if (!contentType?.startsWith(EventStreamContentType)) {
525
+ throw new Error(`Expected content-type to be ${EventStreamContentType}, Actual: ${contentType}`);
526
+ }
527
+ }
528
+
529
+ const VERSION = "0.28.0";
303
530
 
304
531
  class ErrorWithCause extends Error {
305
532
  constructor(message, options) {
@@ -375,6 +602,18 @@ function hostHeader(url) {
375
602
  const { groups } = pattern.exec(url) ?? {};
376
603
  return groups?.host ? { Host: groups.host } : {};
377
604
  }
605
+ async function parseBody(body, headers) {
606
+ if (!isDefined(body))
607
+ return void 0;
608
+ if (isBlob(body) || typeof body.text === "function") {
609
+ return body;
610
+ }
611
+ const { "Content-Type": contentType } = headers ?? {};
612
+ if (String(contentType).toLowerCase() === "application/json" && isObject(body)) {
613
+ return JSON.stringify(body);
614
+ }
615
+ return body;
616
+ }
378
617
  const defaultClientID = generateUUID();
379
618
  async function fetch$1({
380
619
  url: path,
@@ -383,7 +622,7 @@ async function fetch$1({
383
622
  headers: customHeaders,
384
623
  pathParams,
385
624
  queryParams,
386
- fetchImpl,
625
+ fetch: fetch2,
387
626
  apiKey,
388
627
  endpoint,
389
628
  apiUrl,
@@ -394,9 +633,10 @@ async function fetch$1({
394
633
  sessionID,
395
634
  clientName,
396
635
  xataAgentExtra,
397
- fetchOptions = {}
636
+ fetchOptions = {},
637
+ rawResponse = false
398
638
  }) {
399
- pool.setFetch(fetchImpl);
639
+ pool.setFetch(fetch2);
400
640
  return await trace(
401
641
  `${method.toUpperCase()} ${path}`,
402
642
  async ({ setAttributes }) => {
@@ -413,7 +653,7 @@ async function fetch$1({
413
653
  isDefined(clientName) ? ["service", clientName] : void 0,
414
654
  ...Object.entries(xataAgentExtra ?? {})
415
655
  ]).map(([key, value]) => `${key}=${value}`).join("; ");
416
- const headers = {
656
+ const headers = compactObject({
417
657
  "Accept-Encoding": "identity",
418
658
  "Content-Type": "application/json",
419
659
  "X-Xata-Client-ID": clientID ?? defaultClientID,
@@ -422,11 +662,11 @@ async function fetch$1({
422
662
  ...customHeaders,
423
663
  ...hostHeader(fullUrl),
424
664
  Authorization: `Bearer ${apiKey}`
425
- };
665
+ });
426
666
  const response = await pool.request(url, {
427
667
  ...fetchOptions,
428
668
  method: method.toUpperCase(),
429
- body: body ? JSON.stringify(body) : void 0,
669
+ body: await parseBody(body, headers),
430
670
  headers,
431
671
  signal
432
672
  });
@@ -437,8 +677,12 @@ async function fetch$1({
437
677
  [TraceAttributes.HTTP_REQUEST_ID]: requestId,
438
678
  [TraceAttributes.HTTP_STATUS_CODE]: response.status,
439
679
  [TraceAttributes.HTTP_HOST]: host,
440
- [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", "")
680
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", ""),
681
+ [TraceAttributes.CLOUDFLARE_RAY_ID]: response.headers?.get("cf-ray") ?? void 0
441
682
  });
683
+ const message = response.headers?.get("x-xata-message");
684
+ if (message)
685
+ console.warn(message);
442
686
  if (response.status === 204) {
443
687
  return {};
444
688
  }
@@ -446,7 +690,7 @@ async function fetch$1({
446
690
  throw new FetcherError(response.status, "Rate limit exceeded", requestId);
447
691
  }
448
692
  try {
449
- const jsonResponse = await response.json();
693
+ const jsonResponse = rawResponse ? await response.blob() : await response.json();
450
694
  if (response.ok) {
451
695
  return jsonResponse;
452
696
  }
@@ -458,6 +702,59 @@ async function fetch$1({
458
702
  { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
459
703
  );
460
704
  }
705
+ function fetchSSERequest({
706
+ url: path,
707
+ method,
708
+ body,
709
+ headers: customHeaders,
710
+ pathParams,
711
+ queryParams,
712
+ fetch: fetch2,
713
+ apiKey,
714
+ endpoint,
715
+ apiUrl,
716
+ workspacesApiUrl,
717
+ onMessage,
718
+ onError,
719
+ onClose,
720
+ signal,
721
+ clientID,
722
+ sessionID,
723
+ clientName,
724
+ xataAgentExtra
725
+ }) {
726
+ const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
727
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
728
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
729
+ void fetchEventSource(url, {
730
+ method,
731
+ body: JSON.stringify(body),
732
+ fetch: fetch2,
733
+ signal,
734
+ headers: {
735
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
736
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
737
+ "X-Xata-Agent": compact([
738
+ ["client", "TS_SDK"],
739
+ ["version", VERSION],
740
+ isDefined(clientName) ? ["service", clientName] : void 0,
741
+ ...Object.entries(xataAgentExtra ?? {})
742
+ ]).map(([key, value]) => `${key}=${value}`).join("; "),
743
+ ...customHeaders,
744
+ Authorization: `Bearer ${apiKey}`,
745
+ "Content-Type": "application/json"
746
+ },
747
+ onmessage(ev) {
748
+ onMessage?.(JSON.parse(ev.data));
749
+ },
750
+ onerror(ev) {
751
+ onError?.(JSON.parse(ev.data));
752
+ },
753
+ onclose() {
754
+ onClose?.();
755
+ }
756
+ });
757
+ }
461
758
  function parseUrl(url) {
462
759
  try {
463
760
  const { host, protocol } = new URL(url);
@@ -469,6 +766,13 @@ function parseUrl(url) {
469
766
 
470
767
  const dataPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "dataPlane" });
471
768
 
769
+ const applyMigration = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/pgroll/apply", method: "post", ...variables, signal });
770
+ const pgRollStatus = (variables, signal) => dataPlaneFetch({
771
+ url: "/db/{dbBranchName}/pgroll/status",
772
+ method: "get",
773
+ ...variables,
774
+ signal
775
+ });
472
776
  const getBranchList = (variables, signal) => dataPlaneFetch({
473
777
  url: "/dbs/{dbName}",
474
778
  method: "get",
@@ -488,6 +792,18 @@ const deleteBranch = (variables, signal) => dataPlaneFetch({
488
792
  ...variables,
489
793
  signal
490
794
  });
795
+ const getSchema = (variables, signal) => dataPlaneFetch({
796
+ url: "/db/{dbBranchName}/schema",
797
+ method: "get",
798
+ ...variables,
799
+ signal
800
+ });
801
+ const copyBranch = (variables, signal) => dataPlaneFetch({
802
+ url: "/db/{dbBranchName}/copy",
803
+ method: "post",
804
+ ...variables,
805
+ signal
806
+ });
491
807
  const updateBranchMetadata = (variables, signal) => dataPlaneFetch({
492
808
  url: "/db/{dbBranchName}/metadata",
493
809
  method: "put",
@@ -537,6 +853,7 @@ const compareBranchSchemas = (variables, signal) => dataPlaneFetch({ url: "/db/{
537
853
  const updateBranchSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/update", method: "post", ...variables, signal });
538
854
  const previewBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables, signal });
539
855
  const applyBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables, signal });
856
+ const pushBranchMigrations = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/push", method: "post", ...variables, signal });
540
857
  const createTable = (variables, signal) => dataPlaneFetch({
541
858
  url: "/db/{dbBranchName}/tables/{tableName}",
542
859
  method: "put",
@@ -581,6 +898,42 @@ const deleteColumn = (variables, signal) => dataPlaneFetch({
581
898
  });
582
899
  const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
583
900
  const insertRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
901
+ const getFileItem = (variables, signal) => dataPlaneFetch({
902
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
903
+ method: "get",
904
+ ...variables,
905
+ signal
906
+ });
907
+ const putFileItem = (variables, signal) => dataPlaneFetch({
908
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
909
+ method: "put",
910
+ ...variables,
911
+ signal
912
+ });
913
+ const deleteFileItem = (variables, signal) => dataPlaneFetch({
914
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
915
+ method: "delete",
916
+ ...variables,
917
+ signal
918
+ });
919
+ const getFile = (variables, signal) => dataPlaneFetch({
920
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
921
+ method: "get",
922
+ ...variables,
923
+ signal
924
+ });
925
+ const putFile = (variables, signal) => dataPlaneFetch({
926
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
927
+ method: "put",
928
+ ...variables,
929
+ signal
930
+ });
931
+ const deleteFile = (variables, signal) => dataPlaneFetch({
932
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
933
+ method: "delete",
934
+ ...variables,
935
+ signal
936
+ });
584
937
  const getRecord = (variables, signal) => dataPlaneFetch({
585
938
  url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
586
939
  method: "get",
@@ -610,14 +963,37 @@ const searchTable = (variables, signal) => dataPlaneFetch({
610
963
  ...variables,
611
964
  signal
612
965
  });
966
+ const vectorSearchTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/vectorSearch", method: "post", ...variables, signal });
967
+ const askTable = (variables, signal) => dataPlaneFetch({
968
+ url: "/db/{dbBranchName}/tables/{tableName}/ask",
969
+ method: "post",
970
+ ...variables,
971
+ signal
972
+ });
973
+ const askTableSession = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}", method: "post", ...variables, signal });
613
974
  const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
614
975
  const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
976
+ const fileAccess = (variables, signal) => dataPlaneFetch({
977
+ url: "/file/{fileId}",
978
+ method: "get",
979
+ ...variables,
980
+ signal
981
+ });
982
+ const sqlQuery = (variables, signal) => dataPlaneFetch({
983
+ url: "/db/{dbBranchName}/sql",
984
+ method: "post",
985
+ ...variables,
986
+ signal
987
+ });
615
988
  const operationsByTag$2 = {
616
989
  branch: {
990
+ applyMigration,
991
+ pgRollStatus,
617
992
  getBranchList,
618
993
  getBranchDetails,
619
994
  createBranch,
620
995
  deleteBranch,
996
+ copyBranch,
621
997
  updateBranchMetadata,
622
998
  getBranchMetadata,
623
999
  getBranchStats,
@@ -627,6 +1003,7 @@ const operationsByTag$2 = {
627
1003
  resolveBranch
628
1004
  },
629
1005
  migrations: {
1006
+ getSchema,
630
1007
  getBranchMigrationHistory,
631
1008
  getBranchMigrationPlan,
632
1009
  executeBranchMigrationPlan,
@@ -635,7 +1012,8 @@ const operationsByTag$2 = {
635
1012
  compareBranchSchemas,
636
1013
  updateBranchSchema,
637
1014
  previewBranchSchemaEdit,
638
- applyBranchSchemaEdit
1015
+ applyBranchSchemaEdit,
1016
+ pushBranchMigrations
639
1017
  },
640
1018
  migrationRequests: {
641
1019
  queryMigrationRequests,
@@ -669,11 +1047,24 @@ const operationsByTag$2 = {
669
1047
  deleteRecord,
670
1048
  bulkInsertTableRecords
671
1049
  },
672
- searchAndFilter: { queryTable, searchBranch, searchTable, summarizeTable, aggregateTable }
1050
+ files: { getFileItem, putFileItem, deleteFileItem, getFile, putFile, deleteFile, fileAccess },
1051
+ searchAndFilter: {
1052
+ queryTable,
1053
+ searchBranch,
1054
+ searchTable,
1055
+ vectorSearchTable,
1056
+ askTable,
1057
+ askTableSession,
1058
+ summarizeTable,
1059
+ aggregateTable
1060
+ },
1061
+ sql: { sqlQuery }
673
1062
  };
674
1063
 
675
1064
  const controlPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "controlPlane" });
676
1065
 
1066
+ const getAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "get", ...variables, signal });
1067
+ const grantAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "post", ...variables, signal });
677
1068
  const getUser = (variables, signal) => controlPlaneFetch({
678
1069
  url: "/user",
679
1070
  method: "get",
@@ -710,6 +1101,31 @@ const deleteUserAPIKey = (variables, signal) => controlPlaneFetch({
710
1101
  ...variables,
711
1102
  signal
712
1103
  });
1104
+ const getUserOAuthClients = (variables, signal) => controlPlaneFetch({
1105
+ url: "/user/oauth/clients",
1106
+ method: "get",
1107
+ ...variables,
1108
+ signal
1109
+ });
1110
+ const deleteUserOAuthClient = (variables, signal) => controlPlaneFetch({
1111
+ url: "/user/oauth/clients/{clientId}",
1112
+ method: "delete",
1113
+ ...variables,
1114
+ signal
1115
+ });
1116
+ const getUserOAuthAccessTokens = (variables, signal) => controlPlaneFetch({
1117
+ url: "/user/oauth/tokens",
1118
+ method: "get",
1119
+ ...variables,
1120
+ signal
1121
+ });
1122
+ const deleteOAuthAccessToken = (variables, signal) => controlPlaneFetch({
1123
+ url: "/user/oauth/tokens/{token}",
1124
+ method: "delete",
1125
+ ...variables,
1126
+ signal
1127
+ });
1128
+ const updateOAuthAccessToken = (variables, signal) => controlPlaneFetch({ url: "/user/oauth/tokens/{token}", method: "patch", ...variables, signal });
713
1129
  const getWorkspacesList = (variables, signal) => controlPlaneFetch({
714
1130
  url: "/workspaces",
715
1131
  method: "get",
@@ -753,6 +1169,20 @@ const updateWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ u
753
1169
  const cancelWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "delete", ...variables, signal });
754
1170
  const acceptWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept", method: "post", ...variables, signal });
755
1171
  const resendWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}/resend", method: "post", ...variables, signal });
1172
+ const listClusters = (variables, signal) => controlPlaneFetch({
1173
+ url: "/workspaces/{workspaceId}/clusters",
1174
+ method: "get",
1175
+ ...variables,
1176
+ signal
1177
+ });
1178
+ const createCluster = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/clusters", method: "post", ...variables, signal });
1179
+ const getCluster = (variables, signal) => controlPlaneFetch({
1180
+ url: "/workspaces/{workspaceId}/clusters/{clusterId}",
1181
+ method: "get",
1182
+ ...variables,
1183
+ signal
1184
+ });
1185
+ const updateCluster = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/clusters/{clusterId}", method: "patch", ...variables, signal });
756
1186
  const getDatabaseList = (variables, signal) => controlPlaneFetch({
757
1187
  url: "/workspaces/{workspaceId}/dbs",
758
1188
  method: "get",
@@ -768,6 +1198,7 @@ const deleteDatabase = (variables, signal) => controlPlaneFetch({
768
1198
  });
769
1199
  const getDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "get", ...variables, signal });
770
1200
  const updateDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "patch", ...variables, signal });
1201
+ const renameDatabase = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/rename", method: "post", ...variables, signal });
771
1202
  const getDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "get", ...variables, signal });
772
1203
  const updateDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "put", ...variables, signal });
773
1204
  const deleteDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "delete", ...variables, signal });
@@ -778,6 +1209,15 @@ const listRegions = (variables, signal) => controlPlaneFetch({
778
1209
  signal
779
1210
  });
780
1211
  const operationsByTag$1 = {
1212
+ oAuth: {
1213
+ getAuthorizationCode,
1214
+ grantAuthorizationCode,
1215
+ getUserOAuthClients,
1216
+ deleteUserOAuthClient,
1217
+ getUserOAuthAccessTokens,
1218
+ deleteOAuthAccessToken,
1219
+ updateOAuthAccessToken
1220
+ },
781
1221
  users: { getUser, updateUser, deleteUser },
782
1222
  authentication: { getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
783
1223
  workspaces: {
@@ -797,12 +1237,14 @@ const operationsByTag$1 = {
797
1237
  acceptWorkspaceMemberInvite,
798
1238
  resendWorkspaceMemberInvite
799
1239
  },
1240
+ xbcontrolOther: { listClusters, createCluster, getCluster, updateCluster },
800
1241
  databases: {
801
1242
  getDatabaseList,
802
1243
  createDatabase,
803
1244
  deleteDatabase,
804
1245
  getDatabaseMetadata,
805
1246
  updateDatabaseMetadata,
1247
+ renameDatabase,
806
1248
  getDatabaseGithubSettings,
807
1249
  updateDatabaseGithubSettings,
808
1250
  deleteDatabaseGithubSettings,
@@ -826,8 +1268,12 @@ const providers = {
826
1268
  workspaces: "https://{workspaceId}.{region}.xata.sh"
827
1269
  },
828
1270
  staging: {
829
- main: "https://staging.xatabase.co",
830
- workspaces: "https://{workspaceId}.staging.{region}.xatabase.co"
1271
+ main: "https://api.staging-xata.dev",
1272
+ workspaces: "https://{workspaceId}.{region}.staging-xata.dev"
1273
+ },
1274
+ dev: {
1275
+ main: "https://api.dev-xata.dev",
1276
+ workspaces: "https://{workspaceId}.{region}.dev-xata.dev"
831
1277
  }
832
1278
  };
833
1279
  function isHostProviderAlias(alias) {
@@ -845,13 +1291,19 @@ function parseProviderString(provider = "production") {
845
1291
  return null;
846
1292
  return { main, workspaces };
847
1293
  }
1294
+ function buildProviderString(provider) {
1295
+ if (isHostProviderAlias(provider))
1296
+ return provider;
1297
+ return `${provider.main},${provider.workspaces}`;
1298
+ }
848
1299
  function parseWorkspacesUrlParts(url) {
849
1300
  if (!isString(url))
850
1301
  return null;
851
1302
  const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/;
852
- const regexStaging = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))\.xatabase\.co.*/;
853
- const regexDev = /(?:https:\/\/)?([^.]+)\.staging(?:\.([^.]+))\.xata\.tech.*/;
854
- const match = url.match(regex) || url.match(regexStaging) || url.match(regexDev);
1303
+ const regexDev = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.dev-xata\.dev.*/;
1304
+ const regexStaging = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.staging-xata\.dev.*/;
1305
+ const regexProdTesting = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.tech.*/;
1306
+ const match = url.match(regex) || url.match(regexDev) || url.match(regexStaging) || url.match(regexProdTesting);
855
1307
  if (!match)
856
1308
  return null;
857
1309
  return { workspace: match[1], region: match[2] };
@@ -890,7 +1342,7 @@ class XataApiClient {
890
1342
  __privateSet$7(this, _extraProps, {
891
1343
  apiUrl: getHostUrl(provider, "main"),
892
1344
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
893
- fetchImpl: getFetchImplementation(options.fetch),
1345
+ fetch: getFetchImplementation(options.fetch),
894
1346
  apiKey,
895
1347
  trace,
896
1348
  clientName: options.clientName,
@@ -948,6 +1400,11 @@ class XataApiClient {
948
1400
  __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
949
1401
  return __privateGet$7(this, _namespaces).records;
950
1402
  }
1403
+ get files() {
1404
+ if (!__privateGet$7(this, _namespaces).files)
1405
+ __privateGet$7(this, _namespaces).files = new FilesApi(__privateGet$7(this, _extraProps));
1406
+ return __privateGet$7(this, _namespaces).files;
1407
+ }
951
1408
  get searchAndFilter() {
952
1409
  if (!__privateGet$7(this, _namespaces).searchAndFilter)
953
1410
  __privateGet$7(this, _namespaces).searchAndFilter = new SearchAndFilterApi(__privateGet$7(this, _extraProps));
@@ -1156,6 +1613,20 @@ class BranchApi {
1156
1613
  ...this.extraProps
1157
1614
  });
1158
1615
  }
1616
+ copyBranch({
1617
+ workspace,
1618
+ region,
1619
+ database,
1620
+ branch,
1621
+ destinationBranch,
1622
+ limit
1623
+ }) {
1624
+ return operationsByTag.branch.copyBranch({
1625
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1626
+ body: { destinationBranch, limit },
1627
+ ...this.extraProps
1628
+ });
1629
+ }
1159
1630
  updateBranchMetadata({
1160
1631
  workspace,
1161
1632
  region,
@@ -1511,96 +1982,301 @@ class RecordsApi {
1511
1982
  });
1512
1983
  }
1513
1984
  }
1514
- class SearchAndFilterApi {
1985
+ class FilesApi {
1515
1986
  constructor(extraProps) {
1516
1987
  this.extraProps = extraProps;
1517
1988
  }
1518
- queryTable({
1989
+ getFileItem({
1519
1990
  workspace,
1520
1991
  region,
1521
1992
  database,
1522
1993
  branch,
1523
1994
  table,
1524
- filter,
1525
- sort,
1526
- page,
1527
- columns,
1528
- consistency
1995
+ record,
1996
+ column,
1997
+ fileId
1529
1998
  }) {
1530
- return operationsByTag.searchAndFilter.queryTable({
1531
- pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1532
- body: { filter, sort, page, columns, consistency },
1999
+ return operationsByTag.files.getFileItem({
2000
+ pathParams: {
2001
+ workspace,
2002
+ region,
2003
+ dbBranchName: `${database}:${branch}`,
2004
+ tableName: table,
2005
+ recordId: record,
2006
+ columnName: column,
2007
+ fileId
2008
+ },
1533
2009
  ...this.extraProps
1534
2010
  });
1535
2011
  }
1536
- searchTable({
2012
+ putFileItem({
1537
2013
  workspace,
1538
2014
  region,
1539
2015
  database,
1540
2016
  branch,
1541
2017
  table,
1542
- query,
1543
- fuzziness,
1544
- target,
1545
- prefix,
1546
- filter,
1547
- highlight,
1548
- boosters
2018
+ record,
2019
+ column,
2020
+ fileId,
2021
+ file
1549
2022
  }) {
1550
- return operationsByTag.searchAndFilter.searchTable({
1551
- pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1552
- body: { query, fuzziness, target, prefix, filter, highlight, boosters },
2023
+ return operationsByTag.files.putFileItem({
2024
+ pathParams: {
2025
+ workspace,
2026
+ region,
2027
+ dbBranchName: `${database}:${branch}`,
2028
+ tableName: table,
2029
+ recordId: record,
2030
+ columnName: column,
2031
+ fileId
2032
+ },
2033
+ // @ts-ignore
2034
+ body: file,
1553
2035
  ...this.extraProps
1554
2036
  });
1555
2037
  }
1556
- searchBranch({
2038
+ deleteFileItem({
1557
2039
  workspace,
1558
2040
  region,
1559
2041
  database,
1560
2042
  branch,
1561
- tables,
1562
- query,
1563
- fuzziness,
1564
- prefix,
1565
- highlight
2043
+ table,
2044
+ record,
2045
+ column,
2046
+ fileId
1566
2047
  }) {
1567
- return operationsByTag.searchAndFilter.searchBranch({
1568
- pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1569
- body: { tables, query, fuzziness, prefix, highlight },
2048
+ return operationsByTag.files.deleteFileItem({
2049
+ pathParams: {
2050
+ workspace,
2051
+ region,
2052
+ dbBranchName: `${database}:${branch}`,
2053
+ tableName: table,
2054
+ recordId: record,
2055
+ columnName: column,
2056
+ fileId
2057
+ },
1570
2058
  ...this.extraProps
1571
2059
  });
1572
2060
  }
1573
- summarizeTable({
2061
+ getFile({
1574
2062
  workspace,
1575
2063
  region,
1576
2064
  database,
1577
2065
  branch,
1578
2066
  table,
1579
- filter,
1580
- columns,
1581
- summaries,
1582
- sort,
1583
- summariesFilter,
1584
- page,
1585
- consistency
2067
+ record,
2068
+ column
1586
2069
  }) {
1587
- return operationsByTag.searchAndFilter.summarizeTable({
1588
- pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1589
- body: { filter, columns, summaries, sort, summariesFilter, page, consistency },
2070
+ return operationsByTag.files.getFile({
2071
+ pathParams: {
2072
+ workspace,
2073
+ region,
2074
+ dbBranchName: `${database}:${branch}`,
2075
+ tableName: table,
2076
+ recordId: record,
2077
+ columnName: column
2078
+ },
1590
2079
  ...this.extraProps
1591
2080
  });
1592
2081
  }
1593
- aggregateTable({
2082
+ putFile({
1594
2083
  workspace,
1595
2084
  region,
1596
2085
  database,
1597
2086
  branch,
1598
2087
  table,
1599
- filter,
1600
- aggs
2088
+ record,
2089
+ column,
2090
+ file
1601
2091
  }) {
1602
- return operationsByTag.searchAndFilter.aggregateTable({
1603
- pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2092
+ return operationsByTag.files.putFile({
2093
+ pathParams: {
2094
+ workspace,
2095
+ region,
2096
+ dbBranchName: `${database}:${branch}`,
2097
+ tableName: table,
2098
+ recordId: record,
2099
+ columnName: column
2100
+ },
2101
+ body: file,
2102
+ ...this.extraProps
2103
+ });
2104
+ }
2105
+ deleteFile({
2106
+ workspace,
2107
+ region,
2108
+ database,
2109
+ branch,
2110
+ table,
2111
+ record,
2112
+ column
2113
+ }) {
2114
+ return operationsByTag.files.deleteFile({
2115
+ pathParams: {
2116
+ workspace,
2117
+ region,
2118
+ dbBranchName: `${database}:${branch}`,
2119
+ tableName: table,
2120
+ recordId: record,
2121
+ columnName: column
2122
+ },
2123
+ ...this.extraProps
2124
+ });
2125
+ }
2126
+ fileAccess({
2127
+ workspace,
2128
+ region,
2129
+ fileId,
2130
+ verify
2131
+ }) {
2132
+ return operationsByTag.files.fileAccess({
2133
+ pathParams: {
2134
+ workspace,
2135
+ region,
2136
+ fileId
2137
+ },
2138
+ queryParams: { verify },
2139
+ ...this.extraProps
2140
+ });
2141
+ }
2142
+ }
2143
+ class SearchAndFilterApi {
2144
+ constructor(extraProps) {
2145
+ this.extraProps = extraProps;
2146
+ }
2147
+ queryTable({
2148
+ workspace,
2149
+ region,
2150
+ database,
2151
+ branch,
2152
+ table,
2153
+ filter,
2154
+ sort,
2155
+ page,
2156
+ columns,
2157
+ consistency
2158
+ }) {
2159
+ return operationsByTag.searchAndFilter.queryTable({
2160
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2161
+ body: { filter, sort, page, columns, consistency },
2162
+ ...this.extraProps
2163
+ });
2164
+ }
2165
+ searchTable({
2166
+ workspace,
2167
+ region,
2168
+ database,
2169
+ branch,
2170
+ table,
2171
+ query,
2172
+ fuzziness,
2173
+ target,
2174
+ prefix,
2175
+ filter,
2176
+ highlight,
2177
+ boosters
2178
+ }) {
2179
+ return operationsByTag.searchAndFilter.searchTable({
2180
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2181
+ body: { query, fuzziness, target, prefix, filter, highlight, boosters },
2182
+ ...this.extraProps
2183
+ });
2184
+ }
2185
+ searchBranch({
2186
+ workspace,
2187
+ region,
2188
+ database,
2189
+ branch,
2190
+ tables,
2191
+ query,
2192
+ fuzziness,
2193
+ prefix,
2194
+ highlight
2195
+ }) {
2196
+ return operationsByTag.searchAndFilter.searchBranch({
2197
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2198
+ body: { tables, query, fuzziness, prefix, highlight },
2199
+ ...this.extraProps
2200
+ });
2201
+ }
2202
+ vectorSearchTable({
2203
+ workspace,
2204
+ region,
2205
+ database,
2206
+ branch,
2207
+ table,
2208
+ queryVector,
2209
+ column,
2210
+ similarityFunction,
2211
+ size,
2212
+ filter
2213
+ }) {
2214
+ return operationsByTag.searchAndFilter.vectorSearchTable({
2215
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2216
+ body: { queryVector, column, similarityFunction, size, filter },
2217
+ ...this.extraProps
2218
+ });
2219
+ }
2220
+ askTable({
2221
+ workspace,
2222
+ region,
2223
+ database,
2224
+ branch,
2225
+ table,
2226
+ options
2227
+ }) {
2228
+ return operationsByTag.searchAndFilter.askTable({
2229
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2230
+ body: { ...options },
2231
+ ...this.extraProps
2232
+ });
2233
+ }
2234
+ askTableSession({
2235
+ workspace,
2236
+ region,
2237
+ database,
2238
+ branch,
2239
+ table,
2240
+ sessionId,
2241
+ message
2242
+ }) {
2243
+ return operationsByTag.searchAndFilter.askTableSession({
2244
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, sessionId },
2245
+ body: { message },
2246
+ ...this.extraProps
2247
+ });
2248
+ }
2249
+ summarizeTable({
2250
+ workspace,
2251
+ region,
2252
+ database,
2253
+ branch,
2254
+ table,
2255
+ filter,
2256
+ columns,
2257
+ summaries,
2258
+ sort,
2259
+ summariesFilter,
2260
+ page,
2261
+ consistency
2262
+ }) {
2263
+ return operationsByTag.searchAndFilter.summarizeTable({
2264
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2265
+ body: { filter, columns, summaries, sort, summariesFilter, page, consistency },
2266
+ ...this.extraProps
2267
+ });
2268
+ }
2269
+ aggregateTable({
2270
+ workspace,
2271
+ region,
2272
+ database,
2273
+ branch,
2274
+ table,
2275
+ filter,
2276
+ aggs
2277
+ }) {
2278
+ return operationsByTag.searchAndFilter.aggregateTable({
2279
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1604
2280
  body: { filter, aggs },
1605
2281
  ...this.extraProps
1606
2282
  });
@@ -1834,6 +2510,19 @@ class MigrationsApi {
1834
2510
  ...this.extraProps
1835
2511
  });
1836
2512
  }
2513
+ pushBranchMigrations({
2514
+ workspace,
2515
+ region,
2516
+ database,
2517
+ branch,
2518
+ migrations
2519
+ }) {
2520
+ return operationsByTag.migrations.pushBranchMigrations({
2521
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2522
+ body: { migrations },
2523
+ ...this.extraProps
2524
+ });
2525
+ }
1837
2526
  }
1838
2527
  class DatabaseApi {
1839
2528
  constructor(extraProps) {
@@ -1848,11 +2537,13 @@ class DatabaseApi {
1848
2537
  createDatabase({
1849
2538
  workspace,
1850
2539
  database,
1851
- data
2540
+ data,
2541
+ headers
1852
2542
  }) {
1853
2543
  return operationsByTag.databases.createDatabase({
1854
2544
  pathParams: { workspaceId: workspace, dbName: database },
1855
2545
  body: data,
2546
+ headers,
1856
2547
  ...this.extraProps
1857
2548
  });
1858
2549
  }
@@ -1885,6 +2576,17 @@ class DatabaseApi {
1885
2576
  ...this.extraProps
1886
2577
  });
1887
2578
  }
2579
+ renameDatabase({
2580
+ workspace,
2581
+ database,
2582
+ newName
2583
+ }) {
2584
+ return operationsByTag.databases.renameDatabase({
2585
+ pathParams: { workspaceId: workspace, dbName: database },
2586
+ body: { newName },
2587
+ ...this.extraProps
2588
+ });
2589
+ }
1888
2590
  getDatabaseGithubSettings({
1889
2591
  workspace,
1890
2592
  database
@@ -1923,20 +2625,200 @@ class DatabaseApi {
1923
2625
  }
1924
2626
 
1925
2627
  class XataApiPlugin {
1926
- async build(options) {
1927
- const { fetchImpl, apiKey } = await options.getFetchProps();
1928
- return new XataApiClient({ fetch: fetchImpl, apiKey });
2628
+ build(options) {
2629
+ return new XataApiClient(options);
1929
2630
  }
1930
2631
  }
1931
2632
 
1932
2633
  class XataPlugin {
1933
2634
  }
1934
2635
 
2636
+ function buildTransformString(transformations) {
2637
+ return transformations.flatMap(
2638
+ (t) => Object.entries(t).map(([key, value]) => {
2639
+ if (key === "trim") {
2640
+ const { left = 0, top = 0, right = 0, bottom = 0 } = value;
2641
+ return `${key}=${[top, right, bottom, left].join(";")}`;
2642
+ }
2643
+ if (key === "gravity" && typeof value === "object") {
2644
+ const { x = 0.5, y = 0.5 } = value;
2645
+ return `${key}=${[x, y].join("x")}`;
2646
+ }
2647
+ return `${key}=${value}`;
2648
+ })
2649
+ ).join(",");
2650
+ }
2651
+ function transformImage(url, ...transformations) {
2652
+ if (!isDefined(url))
2653
+ return void 0;
2654
+ const newTransformations = buildTransformString(transformations);
2655
+ const { hostname, pathname, search } = new URL(url);
2656
+ const pathParts = pathname.split("/");
2657
+ const transformIndex = pathParts.findIndex((part) => part === "transform");
2658
+ const removedItems = transformIndex >= 0 ? pathParts.splice(transformIndex, 2) : [];
2659
+ const transform = `/transform/${[removedItems[1], newTransformations].filter(isDefined).join(",")}`;
2660
+ const path = pathParts.join("/");
2661
+ return `https://${hostname}${transform}${path}${search}`;
2662
+ }
2663
+
2664
+ class XataFile {
2665
+ constructor(file) {
2666
+ this.id = file.id;
2667
+ this.name = file.name || "";
2668
+ this.mediaType = file.mediaType || "application/octet-stream";
2669
+ this.base64Content = file.base64Content;
2670
+ this.enablePublicUrl = file.enablePublicUrl ?? false;
2671
+ this.signedUrlTimeout = file.signedUrlTimeout ?? 300;
2672
+ this.size = file.size ?? 0;
2673
+ this.version = file.version ?? 1;
2674
+ this.url = file.url || "";
2675
+ this.signedUrl = file.signedUrl;
2676
+ this.attributes = file.attributes || {};
2677
+ }
2678
+ static fromBuffer(buffer, options = {}) {
2679
+ const base64Content = buffer.toString("base64");
2680
+ return new XataFile({ ...options, base64Content });
2681
+ }
2682
+ toBuffer() {
2683
+ if (!this.base64Content) {
2684
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2685
+ }
2686
+ return Buffer.from(this.base64Content, "base64");
2687
+ }
2688
+ static fromArrayBuffer(arrayBuffer, options = {}) {
2689
+ const uint8Array = new Uint8Array(arrayBuffer);
2690
+ return this.fromUint8Array(uint8Array, options);
2691
+ }
2692
+ toArrayBuffer() {
2693
+ if (!this.base64Content) {
2694
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2695
+ }
2696
+ const binary = atob(this.base64Content);
2697
+ return new ArrayBuffer(binary.length);
2698
+ }
2699
+ static fromUint8Array(uint8Array, options = {}) {
2700
+ let binary = "";
2701
+ for (let i = 0; i < uint8Array.byteLength; i++) {
2702
+ binary += String.fromCharCode(uint8Array[i]);
2703
+ }
2704
+ const base64Content = btoa(binary);
2705
+ return new XataFile({ ...options, base64Content });
2706
+ }
2707
+ toUint8Array() {
2708
+ if (!this.base64Content) {
2709
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2710
+ }
2711
+ const binary = atob(this.base64Content);
2712
+ const uint8Array = new Uint8Array(binary.length);
2713
+ for (let i = 0; i < binary.length; i++) {
2714
+ uint8Array[i] = binary.charCodeAt(i);
2715
+ }
2716
+ return uint8Array;
2717
+ }
2718
+ static async fromBlob(file, options = {}) {
2719
+ const name = options.name ?? file.name;
2720
+ const mediaType = file.type;
2721
+ const arrayBuffer = await file.arrayBuffer();
2722
+ return this.fromArrayBuffer(arrayBuffer, { ...options, name, mediaType });
2723
+ }
2724
+ toBlob() {
2725
+ if (!this.base64Content) {
2726
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2727
+ }
2728
+ const binary = atob(this.base64Content);
2729
+ const uint8Array = new Uint8Array(binary.length);
2730
+ for (let i = 0; i < binary.length; i++) {
2731
+ uint8Array[i] = binary.charCodeAt(i);
2732
+ }
2733
+ return new Blob([uint8Array], { type: this.mediaType });
2734
+ }
2735
+ static fromString(string, options = {}) {
2736
+ const base64Content = btoa(string);
2737
+ return new XataFile({ ...options, base64Content });
2738
+ }
2739
+ toString() {
2740
+ if (!this.base64Content) {
2741
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2742
+ }
2743
+ return atob(this.base64Content);
2744
+ }
2745
+ static fromBase64(base64Content, options = {}) {
2746
+ return new XataFile({ ...options, base64Content });
2747
+ }
2748
+ toBase64() {
2749
+ if (!this.base64Content) {
2750
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2751
+ }
2752
+ return this.base64Content;
2753
+ }
2754
+ transform(...options) {
2755
+ return {
2756
+ url: transformImage(this.url, ...options),
2757
+ signedUrl: transformImage(this.signedUrl, ...options),
2758
+ metadataUrl: transformImage(this.url, ...options, { format: "json" }),
2759
+ metadataSignedUrl: transformImage(this.signedUrl, ...options, { format: "json" })
2760
+ };
2761
+ }
2762
+ }
2763
+ const parseInputFileEntry = async (entry) => {
2764
+ if (!isDefined(entry))
2765
+ return null;
2766
+ const { id, name, mediaType, base64Content, enablePublicUrl, signedUrlTimeout } = await entry;
2767
+ return compactObject({
2768
+ id,
2769
+ // Name cannot be an empty string in our API
2770
+ name: name ? name : void 0,
2771
+ mediaType,
2772
+ base64Content,
2773
+ enablePublicUrl,
2774
+ signedUrlTimeout
2775
+ });
2776
+ };
2777
+
1935
2778
  function cleanFilter(filter) {
1936
- if (!filter)
2779
+ if (!isDefined(filter))
1937
2780
  return void 0;
1938
- const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
1939
- return values.length > 0 ? filter : void 0;
2781
+ if (!isObject(filter))
2782
+ return filter;
2783
+ const values = Object.fromEntries(
2784
+ Object.entries(filter).reduce((acc, [key, value]) => {
2785
+ if (!isDefined(value))
2786
+ return acc;
2787
+ if (Array.isArray(value)) {
2788
+ const clean = value.map((item) => cleanFilter(item)).filter((item) => isDefined(item));
2789
+ if (clean.length === 0)
2790
+ return acc;
2791
+ return [...acc, [key, clean]];
2792
+ }
2793
+ if (isObject(value)) {
2794
+ const clean = cleanFilter(value);
2795
+ if (!isDefined(clean))
2796
+ return acc;
2797
+ return [...acc, [key, clean]];
2798
+ }
2799
+ return [...acc, [key, value]];
2800
+ }, [])
2801
+ );
2802
+ return Object.keys(values).length > 0 ? values : void 0;
2803
+ }
2804
+
2805
+ function stringifyJson(value) {
2806
+ if (!isDefined(value))
2807
+ return value;
2808
+ if (isString(value))
2809
+ return value;
2810
+ try {
2811
+ return JSON.stringify(value);
2812
+ } catch (e) {
2813
+ return value;
2814
+ }
2815
+ }
2816
+ function parseJson(value) {
2817
+ try {
2818
+ return JSON.parse(value);
2819
+ } catch (e) {
2820
+ return value;
2821
+ }
1940
2822
  }
1941
2823
 
1942
2824
  var __accessCheck$6 = (obj, member, msg) => {
@@ -1965,31 +2847,59 @@ class Page {
1965
2847
  this.meta = meta;
1966
2848
  this.records = new RecordArray(this, records);
1967
2849
  }
2850
+ /**
2851
+ * Retrieves the next page of results.
2852
+ * @param size Maximum number of results to be retrieved.
2853
+ * @param offset Number of results to skip when retrieving the results.
2854
+ * @returns The next page or results.
2855
+ */
1968
2856
  async nextPage(size, offset) {
1969
2857
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
1970
2858
  }
2859
+ /**
2860
+ * Retrieves the previous page of results.
2861
+ * @param size Maximum number of results to be retrieved.
2862
+ * @param offset Number of results to skip when retrieving the results.
2863
+ * @returns The previous page or results.
2864
+ */
1971
2865
  async previousPage(size, offset) {
1972
2866
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
1973
2867
  }
2868
+ /**
2869
+ * Retrieves the start page of results.
2870
+ * @param size Maximum number of results to be retrieved.
2871
+ * @param offset Number of results to skip when retrieving the results.
2872
+ * @returns The start page or results.
2873
+ */
1974
2874
  async startPage(size, offset) {
1975
2875
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, start: this.meta.page.cursor } });
1976
2876
  }
2877
+ /**
2878
+ * Retrieves the end page of results.
2879
+ * @param size Maximum number of results to be retrieved.
2880
+ * @param offset Number of results to skip when retrieving the results.
2881
+ * @returns The end page or results.
2882
+ */
1977
2883
  async endPage(size, offset) {
1978
2884
  return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, end: this.meta.page.cursor } });
1979
2885
  }
2886
+ /**
2887
+ * Shortcut method to check if there will be additional results if the next page of results is retrieved.
2888
+ * @returns Whether or not there will be additional results in the next page of results.
2889
+ */
1980
2890
  hasNextPage() {
1981
2891
  return this.meta.page.more;
1982
2892
  }
1983
2893
  }
1984
2894
  _query = new WeakMap();
1985
- const PAGINATION_MAX_SIZE = 200;
2895
+ const PAGINATION_MAX_SIZE = 1e3;
1986
2896
  const PAGINATION_DEFAULT_SIZE = 20;
1987
- const PAGINATION_MAX_OFFSET = 800;
2897
+ const PAGINATION_MAX_OFFSET = 49e3;
1988
2898
  const PAGINATION_DEFAULT_OFFSET = 0;
1989
2899
  function isCursorPaginationOptions(options) {
1990
2900
  return isDefined(options) && (isDefined(options.start) || isDefined(options.end) || isDefined(options.after) || isDefined(options.before));
1991
2901
  }
1992
- const _RecordArray = class extends Array {
2902
+ const _RecordArray = class _RecordArray extends Array {
1993
2903
  constructor(...args) {
1994
2904
  super(..._RecordArray.parseConstructorParams(...args));
1995
2905
  __privateAdd$6(this, _page, void 0);
@@ -2017,28 +2927,51 @@ const _RecordArray = class extends Array {
2017
2927
  map(callbackfn, thisArg) {
2018
2928
  return this.toArray().map(callbackfn, thisArg);
2019
2929
  }
2930
+ /**
2931
+ * Retrieve next page of records
2932
+ *
2933
+ * @returns A new array of objects
2934
+ */
2020
2935
  async nextPage(size, offset) {
2021
2936
  const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
2022
2937
  return new _RecordArray(newPage);
2023
2938
  }
2939
+ /**
2940
+ * Retrieve previous page of records
2941
+ *
2942
+ * @returns A new array of objects
2943
+ */
2024
2944
  async previousPage(size, offset) {
2025
2945
  const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
2026
2946
  return new _RecordArray(newPage);
2027
2947
  }
2948
+ /**
2949
+ * Retrieve start page of records
2950
+ *
2951
+ * @returns A new array of objects
2952
+ */
2028
2953
  async startPage(size, offset) {
2029
2954
  const newPage = await __privateGet$6(this, _page).startPage(size, offset);
2030
2955
  return new _RecordArray(newPage);
2031
2956
  }
2957
+ /**
2958
+ * Retrieve end page of records
2959
+ *
2960
+ * @returns A new array of objects
2961
+ */
2032
2962
  async endPage(size, offset) {
2033
2963
  const newPage = await __privateGet$6(this, _page).endPage(size, offset);
2034
2964
  return new _RecordArray(newPage);
2035
2965
  }
2966
+ /**
2967
+ * @returns Boolean indicating if there is a next page
2968
+ */
2036
2969
  hasNextPage() {
2037
2970
  return __privateGet$6(this, _page).meta.page.more;
2038
2971
  }
2039
2972
  };
2040
- let RecordArray = _RecordArray;
2041
2973
  _page = new WeakMap();
2974
+ let RecordArray = _RecordArray;
2042
2975
 
2043
2976
  var __accessCheck$5 = (obj, member, msg) => {
2044
2977
  if (!member.has(obj))
@@ -2063,13 +2996,14 @@ var __privateMethod$3 = (obj, member, method) => {
2063
2996
  return method;
2064
2997
  };
2065
2998
  var _table$1, _repository, _data, _cleanFilterConstraint, cleanFilterConstraint_fn;
2066
- const _Query = class {
2999
+ const _Query = class _Query {
2067
3000
  constructor(repository, table, data, rawParent) {
2068
3001
  __privateAdd$5(this, _cleanFilterConstraint);
2069
3002
  __privateAdd$5(this, _table$1, void 0);
2070
3003
  __privateAdd$5(this, _repository, void 0);
2071
3004
  __privateAdd$5(this, _data, { filter: {} });
2072
- this.meta = { page: { cursor: "start", more: true } };
3005
+ // Implements pagination
3006
+ this.meta = { page: { cursor: "start", more: true, size: PAGINATION_DEFAULT_SIZE } };
2073
3007
  this.records = new RecordArray(this, []);
2074
3008
  __privateSet$5(this, _table$1, table);
2075
3009
  if (repository) {
@@ -2106,18 +3040,38 @@ const _Query = class {
2106
3040
  const key = JSON.stringify({ columns, filter, sort, pagination });
2107
3041
  return toBase64(key);
2108
3042
  }
3043
+ /**
3044
+ * Builds a new query object representing a logical OR between the given subqueries.
3045
+ * @param queries An array of subqueries.
3046
+ * @returns A new Query object.
3047
+ */
2109
3048
  any(...queries) {
2110
3049
  const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
2111
3050
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
2112
3051
  }
3052
+ /**
3053
+ * Builds a new query object representing a logical AND between the given subqueries.
3054
+ * @param queries An array of subqueries.
3055
+ * @returns A new Query object.
3056
+ */
2113
3057
  all(...queries) {
2114
3058
  const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
2115
3059
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
2116
3060
  }
3061
+ /**
3062
+ * Builds a new query object representing a logical OR negating each subquery. In pseudo-code: !q1 OR !q2
3063
+ * @param queries An array of subqueries.
3064
+ * @returns A new Query object.
3065
+ */
2117
3066
  not(...queries) {
2118
3067
  const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
2119
3068
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
2120
3069
  }
3070
+ /**
3071
+ * Builds a new query object representing a logical AND negating each subquery. In pseudo-code: !q1 AND !q2
3072
+ * @param queries An array of subqueries.
3073
+ * @returns A new Query object.
3074
+ */
2121
3075
  none(...queries) {
2122
3076
  const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
2123
3077
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
@@ -2140,6 +3094,11 @@ const _Query = class {
2140
3094
  const sort = [...originalSort, { column, direction }];
2141
3095
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
2142
3096
  }
3097
+ /**
3098
+ * Builds a new query specifying the set of columns to be returned in the query response.
3099
+ * @param columns Array of column names to be returned by the query.
3100
+ * @returns A new Query object.
3101
+ */
2143
3102
  select(columns) {
2144
3103
  return new _Query(
2145
3104
  __privateGet$5(this, _repository),
@@ -2152,6 +3111,12 @@ const _Query = class {
2152
3111
  const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
2153
3112
  return __privateGet$5(this, _repository).query(query);
2154
3113
  }
3114
+ /**
3115
+ * Get results in an iterator
3116
+ *
3117
+ * @async
3118
+ * @returns Async interable of results
3119
+ */
2155
3120
  async *[Symbol.asyncIterator]() {
2156
3121
  for await (const [record] of this.getIterator({ batchSize: 1 })) {
2157
3122
  yield record;
@@ -2212,26 +3177,53 @@ const _Query = class {
2212
3177
  );
2213
3178
  return __privateGet$5(this, _repository).summarizeTable(query, summaries, summariesFilter);
2214
3179
  }
3180
+ /**
3181
+ * Builds a new query object adding a cache TTL in milliseconds.
3182
+ * @param ttl The cache TTL in milliseconds.
3183
+ * @returns A new Query object.
3184
+ */
2215
3185
  cache(ttl) {
2216
3186
  return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
2217
3187
  }
3188
+ /**
3189
+ * Retrieve next page of records
3190
+ *
3191
+ * @returns A new page object.
3192
+ */
2218
3193
  nextPage(size, offset) {
2219
3194
  return this.startPage(size, offset);
2220
3195
  }
3196
+ /**
3197
+ * Retrieve previous page of records
3198
+ *
3199
+ * @returns A new page object
3200
+ */
2221
3201
  previousPage(size, offset) {
2222
3202
  return this.startPage(size, offset);
2223
3203
  }
3204
+ /**
3205
+ * Retrieve start page of records
3206
+ *
3207
+ * @returns A new page object
3208
+ */
2224
3209
  startPage(size, offset) {
2225
3210
  return this.getPaginated({ pagination: { size, offset } });
2226
3211
  }
3212
+ /**
3213
+ * Retrieve last page of records
3214
+ *
3215
+ * @returns A new page object
3216
+ */
2227
3217
  endPage(size, offset) {
2228
3218
  return this.getPaginated({ pagination: { size, offset, before: "end" } });
2229
3219
  }
3220
+ /**
3221
+ * @returns Boolean indicating if there is a next page
3222
+ */
2230
3223
  hasNextPage() {
2231
3224
  return this.meta.page.more;
2232
3225
  }
2233
3226
  };
2234
- let Query = _Query;
2235
3227
  _table$1 = new WeakMap();
2236
3228
  _repository = new WeakMap();
2237
3229
  _data = new WeakMap();
@@ -2246,6 +3238,7 @@ cleanFilterConstraint_fn = function(column, value) {
2246
3238
  }
2247
3239
  return value;
2248
3240
  };
3241
+ let Query = _Query;
2249
3242
  function cleanParent(data, parent) {
2250
3243
  if (isCursorPaginationOptions(data.pagination)) {
2251
3244
  return { ...parent, sort: void 0, filter: void 0 };
@@ -2253,6 +3246,22 @@ function cleanParent(data, parent) {
2253
3246
  return parent;
2254
3247
  }
2255
3248
 
3249
+ const RecordColumnTypes = [
3250
+ "bool",
3251
+ "int",
3252
+ "float",
3253
+ "string",
3254
+ "text",
3255
+ "email",
3256
+ "multiple",
3257
+ "link",
3258
+ "object",
3259
+ "datetime",
3260
+ "vector",
3261
+ "file[]",
3262
+ "file",
3263
+ "json"
3264
+ ];
2256
3265
  function isIdentifiable(x) {
2257
3266
  return isObject(x) && isString(x?.id);
2258
3267
  }
@@ -2262,11 +3271,33 @@ function isXataRecord(x) {
2262
3271
  return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
2263
3272
  }
2264
3273
 
3274
+ function isValidExpandedColumn(column) {
3275
+ return isObject(column) && isString(column.name);
3276
+ }
3277
+ function isValidSelectableColumns(columns) {
3278
+ if (!Array.isArray(columns)) {
3279
+ return false;
3280
+ }
3281
+ return columns.every((column) => {
3282
+ if (typeof column === "string") {
3283
+ return true;
3284
+ }
3285
+ if (typeof column === "object") {
3286
+ return isValidExpandedColumn(column);
3287
+ }
3288
+ return false;
3289
+ });
3290
+ }
3291
+
2265
3292
  function isSortFilterString(value) {
2266
3293
  return isString(value);
2267
3294
  }
2268
3295
  function isSortFilterBase(filter) {
2269
- return isObject(filter) && Object.values(filter).every((value) => value === "asc" || value === "desc");
3296
+ return isObject(filter) && Object.entries(filter).every(([key, value]) => {
3297
+ if (key === "*")
3298
+ return value === "random";
3299
+ return value === "asc" || value === "desc";
3300
+ });
2270
3301
  }
2271
3302
  function isSortFilterObject(filter) {
2272
3303
  return isObject(filter) && !isSortFilterBase(filter) && filter.column !== void 0;
@@ -2307,7 +3338,7 @@ var __privateMethod$2 = (obj, member, method) => {
2307
3338
  __accessCheck$4(obj, member, "access private method");
2308
3339
  return method;
2309
3340
  };
2310
- var _table, _getFetchProps, _db, _cache, _schemaTables$2, _trace, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _insertRecords, insertRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _updateRecords, updateRecords_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _deleteRecords, deleteRecords_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaTables$1, getSchemaTables_fn$1;
3341
+ 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;
2311
3342
  const BULK_OPERATION_MAX_SIZE = 1e3;
2312
3343
  class Repository extends Query {
2313
3344
  }
@@ -2329,6 +3360,7 @@ class RestRepository extends Query {
2329
3360
  __privateAdd$4(this, _setCacheQuery);
2330
3361
  __privateAdd$4(this, _getCacheQuery);
2331
3362
  __privateAdd$4(this, _getSchemaTables$1);
3363
+ __privateAdd$4(this, _transformObjectToApi);
2332
3364
  __privateAdd$4(this, _table, void 0);
2333
3365
  __privateAdd$4(this, _getFetchProps, void 0);
2334
3366
  __privateAdd$4(this, _db, void 0);
@@ -2339,10 +3371,7 @@ class RestRepository extends Query {
2339
3371
  __privateSet$4(this, _db, options.db);
2340
3372
  __privateSet$4(this, _cache, options.pluginOptions.cache);
2341
3373
  __privateSet$4(this, _schemaTables$2, options.schemaTables);
2342
- __privateSet$4(this, _getFetchProps, async () => {
2343
- const props = await options.pluginOptions.getFetchProps();
2344
- return { ...props, sessionID: generateUUID() };
2345
- });
3374
+ __privateSet$4(this, _getFetchProps, () => ({ ...options.pluginOptions, sessionID: generateUUID() }));
2346
3375
  const trace = options.pluginOptions.trace ?? defaultTrace;
2347
3376
  __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
2348
3377
  return trace(name, fn, {
@@ -2360,24 +3389,24 @@ class RestRepository extends Query {
2360
3389
  if (a.length === 0)
2361
3390
  return [];
2362
3391
  const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: true });
2363
- const columns = isStringArray(b) ? b : ["*"];
3392
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2364
3393
  const result = await this.read(ids, columns);
2365
3394
  return result;
2366
3395
  }
2367
3396
  if (isString(a) && isObject(b)) {
2368
3397
  if (a === "")
2369
3398
  throw new Error("The id can't be empty");
2370
- const columns = isStringArray(c) ? c : void 0;
3399
+ const columns = isValidSelectableColumns(c) ? c : void 0;
2371
3400
  return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
2372
3401
  }
2373
3402
  if (isObject(a) && isString(a.id)) {
2374
3403
  if (a.id === "")
2375
3404
  throw new Error("The id can't be empty");
2376
- const columns = isStringArray(b) ? b : void 0;
3405
+ const columns = isValidSelectableColumns(b) ? b : void 0;
2377
3406
  return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
2378
3407
  }
2379
3408
  if (isObject(a)) {
2380
- const columns = isStringArray(b) ? b : void 0;
3409
+ const columns = isValidSelectableColumns(b) ? b : void 0;
2381
3410
  return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
2382
3411
  }
2383
3412
  throw new Error("Invalid arguments for create method");
@@ -2385,7 +3414,7 @@ class RestRepository extends Query {
2385
3414
  }
2386
3415
  async read(a, b) {
2387
3416
  return __privateGet$4(this, _trace).call(this, "read", async () => {
2388
- const columns = isStringArray(b) ? b : ["*"];
3417
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2389
3418
  if (Array.isArray(a)) {
2390
3419
  if (a.length === 0)
2391
3420
  return [];
@@ -2399,7 +3428,6 @@ class RestRepository extends Query {
2399
3428
  }
2400
3429
  const id = extractId(a);
2401
3430
  if (id) {
2402
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2403
3431
  try {
2404
3432
  const response = await getRecord({
2405
3433
  pathParams: {
@@ -2410,10 +3438,16 @@ class RestRepository extends Query {
2410
3438
  recordId: id
2411
3439
  },
2412
3440
  queryParams: { columns },
2413
- ...fetchProps
3441
+ ...__privateGet$4(this, _getFetchProps).call(this)
2414
3442
  });
2415
3443
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2416
- return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
3444
+ return initObject(
3445
+ __privateGet$4(this, _db),
3446
+ schemaTables,
3447
+ __privateGet$4(this, _table),
3448
+ response,
3449
+ columns
3450
+ );
2417
3451
  } catch (e) {
2418
3452
  if (isObject(e) && e.status === 404) {
2419
3453
  return null;
@@ -2455,17 +3489,17 @@ class RestRepository extends Query {
2455
3489
  ifVersion,
2456
3490
  upsert: false
2457
3491
  });
2458
- const columns = isStringArray(b) ? b : ["*"];
3492
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2459
3493
  const result = await this.read(a, columns);
2460
3494
  return result;
2461
3495
  }
2462
3496
  try {
2463
3497
  if (isString(a) && isObject(b)) {
2464
- const columns = isStringArray(c) ? c : void 0;
3498
+ const columns = isValidSelectableColumns(c) ? c : void 0;
2465
3499
  return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2466
3500
  }
2467
3501
  if (isObject(a) && isString(a.id)) {
2468
- const columns = isStringArray(b) ? b : void 0;
3502
+ const columns = isValidSelectableColumns(b) ? b : void 0;
2469
3503
  return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
2470
3504
  }
2471
3505
  } catch (error) {
@@ -2505,17 +3539,27 @@ class RestRepository extends Query {
2505
3539
  ifVersion,
2506
3540
  upsert: true
2507
3541
  });
2508
- const columns = isStringArray(b) ? b : ["*"];
3542
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2509
3543
  const result = await this.read(a, columns);
2510
3544
  return result;
2511
3545
  }
2512
3546
  if (isString(a) && isObject(b)) {
2513
- const columns = isStringArray(c) ? c : void 0;
2514
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3547
+ if (a === "")
3548
+ throw new Error("The id can't be empty");
3549
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3550
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
2515
3551
  }
2516
3552
  if (isObject(a) && isString(a.id)) {
2517
- const columns = isStringArray(c) ? c : void 0;
2518
- return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3553
+ if (a.id === "")
3554
+ throw new Error("The id can't be empty");
3555
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3556
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3557
+ }
3558
+ if (!isDefined(a) && isObject(b)) {
3559
+ return await this.create(b, c);
3560
+ }
3561
+ if (isObject(a) && !isDefined(a.id)) {
3562
+ return await this.create(a, b);
2519
3563
  }
2520
3564
  throw new Error("Invalid arguments for createOrUpdate method");
2521
3565
  });
@@ -2527,17 +3571,27 @@ class RestRepository extends Query {
2527
3571
  if (a.length === 0)
2528
3572
  return [];
2529
3573
  const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: false });
2530
- const columns = isStringArray(b) ? b : ["*"];
3574
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2531
3575
  const result = await this.read(ids, columns);
2532
3576
  return result;
2533
3577
  }
2534
3578
  if (isString(a) && isObject(b)) {
2535
- const columns = isStringArray(c) ? c : void 0;
2536
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
3579
+ if (a === "")
3580
+ throw new Error("The id can't be empty");
3581
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3582
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
2537
3583
  }
2538
3584
  if (isObject(a) && isString(a.id)) {
2539
- const columns = isStringArray(c) ? c : void 0;
2540
- return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3585
+ if (a.id === "")
3586
+ throw new Error("The id can't be empty");
3587
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3588
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3589
+ }
3590
+ if (!isDefined(a) && isObject(b)) {
3591
+ return await this.create(b, c);
3592
+ }
3593
+ if (isObject(a) && !isDefined(a.id)) {
3594
+ return await this.create(a, b);
2541
3595
  }
2542
3596
  throw new Error("Invalid arguments for createOrReplace method");
2543
3597
  });
@@ -2554,7 +3608,7 @@ class RestRepository extends Query {
2554
3608
  return o.id;
2555
3609
  throw new Error("Invalid arguments for delete method");
2556
3610
  });
2557
- const columns = isStringArray(b) ? b : ["*"];
3611
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
2558
3612
  const result = await this.read(a, columns);
2559
3613
  await __privateMethod$2(this, _deleteRecords, deleteRecords_fn).call(this, ids);
2560
3614
  return result;
@@ -2588,8 +3642,7 @@ class RestRepository extends Query {
2588
3642
  }
2589
3643
  async search(query, options = {}) {
2590
3644
  return __privateGet$4(this, _trace).call(this, "search", async () => {
2591
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2592
- const { records } = await searchTable({
3645
+ const { records, totalCount } = await searchTable({
2593
3646
  pathParams: {
2594
3647
  workspace: "{workspaceId}",
2595
3648
  dbBranchName: "{dbBranch}",
@@ -2606,15 +3659,42 @@ class RestRepository extends Query {
2606
3659
  page: options.page,
2607
3660
  target: options.target
2608
3661
  },
2609
- ...fetchProps
3662
+ ...__privateGet$4(this, _getFetchProps).call(this)
3663
+ });
3664
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3665
+ return {
3666
+ records: records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"])),
3667
+ totalCount
3668
+ };
3669
+ });
3670
+ }
3671
+ async vectorSearch(column, query, options) {
3672
+ return __privateGet$4(this, _trace).call(this, "vectorSearch", async () => {
3673
+ const { records, totalCount } = await vectorSearchTable({
3674
+ pathParams: {
3675
+ workspace: "{workspaceId}",
3676
+ dbBranchName: "{dbBranch}",
3677
+ region: "{region}",
3678
+ tableName: __privateGet$4(this, _table)
3679
+ },
3680
+ body: {
3681
+ column,
3682
+ queryVector: query,
3683
+ similarityFunction: options?.similarityFunction,
3684
+ size: options?.size,
3685
+ filter: options?.filter
3686
+ },
3687
+ ...__privateGet$4(this, _getFetchProps).call(this)
2610
3688
  });
2611
3689
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2612
- return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
3690
+ return {
3691
+ records: records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"])),
3692
+ totalCount
3693
+ };
2613
3694
  });
2614
3695
  }
2615
3696
  async aggregate(aggs, filter) {
2616
3697
  return __privateGet$4(this, _trace).call(this, "aggregate", async () => {
2617
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2618
3698
  const result = await aggregateTable({
2619
3699
  pathParams: {
2620
3700
  workspace: "{workspaceId}",
@@ -2623,7 +3703,7 @@ class RestRepository extends Query {
2623
3703
  tableName: __privateGet$4(this, _table)
2624
3704
  },
2625
3705
  body: { aggs, filter },
2626
- ...fetchProps
3706
+ ...__privateGet$4(this, _getFetchProps).call(this)
2627
3707
  });
2628
3708
  return result;
2629
3709
  });
@@ -2634,7 +3714,6 @@ class RestRepository extends Query {
2634
3714
  if (cacheQuery)
2635
3715
  return new Page(query, cacheQuery.meta, cacheQuery.records);
2636
3716
  const data = query.getQueryOptions();
2637
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2638
3717
  const { meta, records: objects } = await queryTable({
2639
3718
  pathParams: {
2640
3719
  workspace: "{workspaceId}",
@@ -2650,11 +3729,17 @@ class RestRepository extends Query {
2650
3729
  consistency: data.consistency
2651
3730
  },
2652
3731
  fetchOptions: data.fetchOptions,
2653
- ...fetchProps
3732
+ ...__privateGet$4(this, _getFetchProps).call(this)
2654
3733
  });
2655
3734
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2656
3735
  const records = objects.map(
2657
- (record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record, data.columns ?? ["*"])
3736
+ (record) => initObject(
3737
+ __privateGet$4(this, _db),
3738
+ schemaTables,
3739
+ __privateGet$4(this, _table),
3740
+ record,
3741
+ data.columns ?? ["*"]
3742
+ )
2658
3743
  );
2659
3744
  await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
2660
3745
  return new Page(query, meta, records);
@@ -2663,7 +3748,6 @@ class RestRepository extends Query {
2663
3748
  async summarizeTable(query, summaries, summariesFilter) {
2664
3749
  return __privateGet$4(this, _trace).call(this, "summarize", async () => {
2665
3750
  const data = query.getQueryOptions();
2666
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2667
3751
  const result = await summarizeTable({
2668
3752
  pathParams: {
2669
3753
  workspace: "{workspaceId}",
@@ -2680,11 +3764,50 @@ class RestRepository extends Query {
2680
3764
  summaries,
2681
3765
  summariesFilter
2682
3766
  },
2683
- ...fetchProps
3767
+ ...__privateGet$4(this, _getFetchProps).call(this)
2684
3768
  });
2685
- return result;
3769
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3770
+ return {
3771
+ ...result,
3772
+ summaries: result.summaries.map(
3773
+ (summary) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), summary, data.columns ?? [])
3774
+ )
3775
+ };
2686
3776
  });
2687
3777
  }
3778
+ ask(question, options) {
3779
+ const questionParam = options?.sessionId ? { message: question } : { question };
3780
+ const params = {
3781
+ pathParams: {
3782
+ workspace: "{workspaceId}",
3783
+ dbBranchName: "{dbBranch}",
3784
+ region: "{region}",
3785
+ tableName: __privateGet$4(this, _table),
3786
+ sessionId: options?.sessionId
3787
+ },
3788
+ body: {
3789
+ ...questionParam,
3790
+ rules: options?.rules,
3791
+ searchType: options?.searchType,
3792
+ search: options?.searchType === "keyword" ? options?.search : void 0,
3793
+ vectorSearch: options?.searchType === "vector" ? options?.vectorSearch : void 0
3794
+ },
3795
+ ...__privateGet$4(this, _getFetchProps).call(this)
3796
+ };
3797
+ if (options?.onMessage) {
3798
+ fetchSSERequest({
3799
+ endpoint: "dataPlane",
3800
+ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}",
3801
+ method: "POST",
3802
+ onMessage: (message) => {
3803
+ options.onMessage?.({ answer: message.text, records: message.records });
3804
+ },
3805
+ ...params
3806
+ });
3807
+ } else {
3808
+ return askTableSession(params);
3809
+ }
3810
+ }
2688
3811
  }
2689
3812
  _table = new WeakMap();
2690
3813
  _getFetchProps = new WeakMap();
@@ -2694,8 +3817,7 @@ _schemaTables$2 = new WeakMap();
2694
3817
  _trace = new WeakMap();
2695
3818
  _insertRecordWithoutId = new WeakSet();
2696
3819
  insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
2697
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2698
- const record = transformObjectLinks(object);
3820
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2699
3821
  const response = await insertRecord({
2700
3822
  pathParams: {
2701
3823
  workspace: "{workspaceId}",
@@ -2705,15 +3827,16 @@ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
2705
3827
  },
2706
3828
  queryParams: { columns },
2707
3829
  body: record,
2708
- ...fetchProps
3830
+ ...__privateGet$4(this, _getFetchProps).call(this)
2709
3831
  });
2710
3832
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2711
3833
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2712
3834
  };
2713
3835
  _insertRecordWithId = new WeakSet();
2714
3836
  insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { createOnly, ifVersion }) {
2715
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2716
- const record = transformObjectLinks(object);
3837
+ if (!recordId)
3838
+ return null;
3839
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2717
3840
  const response = await insertRecordWithID({
2718
3841
  pathParams: {
2719
3842
  workspace: "{workspaceId}",
@@ -2724,30 +3847,28 @@ insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { crea
2724
3847
  },
2725
3848
  body: record,
2726
3849
  queryParams: { createOnly, columns, ifVersion },
2727
- ...fetchProps
3850
+ ...__privateGet$4(this, _getFetchProps).call(this)
2728
3851
  });
2729
3852
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2730
3853
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2731
3854
  };
2732
3855
  _insertRecords = new WeakSet();
2733
3856
  insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2734
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2735
- const chunkedOperations = chunk(
2736
- objects.map((object) => ({
2737
- insert: { table: __privateGet$4(this, _table), record: transformObjectLinks(object), createOnly, ifVersion }
2738
- })),
2739
- BULK_OPERATION_MAX_SIZE
2740
- );
3857
+ const operations = await promiseMap(objects, async (object) => {
3858
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3859
+ return { insert: { table: __privateGet$4(this, _table), record, createOnly, ifVersion } };
3860
+ });
3861
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
2741
3862
  const ids = [];
2742
- for (const operations of chunkedOperations) {
3863
+ for (const operations2 of chunkedOperations) {
2743
3864
  const { results } = await branchTransaction({
2744
3865
  pathParams: {
2745
3866
  workspace: "{workspaceId}",
2746
3867
  dbBranchName: "{dbBranch}",
2747
3868
  region: "{region}"
2748
3869
  },
2749
- body: { operations },
2750
- ...fetchProps
3870
+ body: { operations: operations2 },
3871
+ ...__privateGet$4(this, _getFetchProps).call(this)
2751
3872
  });
2752
3873
  for (const result of results) {
2753
3874
  if (result.operation === "insert") {
@@ -2761,8 +3882,9 @@ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
2761
3882
  };
2762
3883
  _updateRecordWithID = new WeakSet();
2763
3884
  updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2764
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2765
- const { id: _id, ...record } = transformObjectLinks(object);
3885
+ if (!recordId)
3886
+ return null;
3887
+ const { id: _id, ...record } = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
2766
3888
  try {
2767
3889
  const response = await updateRecordWithID({
2768
3890
  pathParams: {
@@ -2774,7 +3896,7 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2774
3896
  },
2775
3897
  queryParams: { columns, ifVersion },
2776
3898
  body: record,
2777
- ...fetchProps
3899
+ ...__privateGet$4(this, _getFetchProps).call(this)
2778
3900
  });
2779
3901
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2780
3902
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2787,23 +3909,21 @@ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2787
3909
  };
2788
3910
  _updateRecords = new WeakSet();
2789
3911
  updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2790
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2791
- const chunkedOperations = chunk(
2792
- objects.map(({ id, ...object }) => ({
2793
- update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields: transformObjectLinks(object) }
2794
- })),
2795
- BULK_OPERATION_MAX_SIZE
2796
- );
3912
+ const operations = await promiseMap(objects, async ({ id, ...object }) => {
3913
+ const fields = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3914
+ return { update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields } };
3915
+ });
3916
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
2797
3917
  const ids = [];
2798
- for (const operations of chunkedOperations) {
3918
+ for (const operations2 of chunkedOperations) {
2799
3919
  const { results } = await branchTransaction({
2800
3920
  pathParams: {
2801
3921
  workspace: "{workspaceId}",
2802
3922
  dbBranchName: "{dbBranch}",
2803
3923
  region: "{region}"
2804
3924
  },
2805
- body: { operations },
2806
- ...fetchProps
3925
+ body: { operations: operations2 },
3926
+ ...__privateGet$4(this, _getFetchProps).call(this)
2807
3927
  });
2808
3928
  for (const result of results) {
2809
3929
  if (result.operation === "update") {
@@ -2817,7 +3937,8 @@ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
2817
3937
  };
2818
3938
  _upsertRecordWithID = new WeakSet();
2819
3939
  upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
2820
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
3940
+ if (!recordId)
3941
+ return null;
2821
3942
  const response = await upsertRecordWithID({
2822
3943
  pathParams: {
2823
3944
  workspace: "{workspaceId}",
@@ -2828,14 +3949,15 @@ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVe
2828
3949
  },
2829
3950
  queryParams: { columns, ifVersion },
2830
3951
  body: object,
2831
- ...fetchProps
3952
+ ...__privateGet$4(this, _getFetchProps).call(this)
2832
3953
  });
2833
3954
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2834
3955
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
2835
3956
  };
2836
3957
  _deleteRecord = new WeakSet();
2837
3958
  deleteRecord_fn = async function(recordId, columns = ["*"]) {
2838
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
3959
+ if (!recordId)
3960
+ return null;
2839
3961
  try {
2840
3962
  const response = await deleteRecord({
2841
3963
  pathParams: {
@@ -2846,7 +3968,7 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2846
3968
  recordId
2847
3969
  },
2848
3970
  queryParams: { columns },
2849
- ...fetchProps
3971
+ ...__privateGet$4(this, _getFetchProps).call(this)
2850
3972
  });
2851
3973
  const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
2852
3974
  return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
@@ -2859,9 +3981,8 @@ deleteRecord_fn = async function(recordId, columns = ["*"]) {
2859
3981
  };
2860
3982
  _deleteRecords = new WeakSet();
2861
3983
  deleteRecords_fn = async function(recordIds) {
2862
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2863
3984
  const chunkedOperations = chunk(
2864
- recordIds.map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
3985
+ compact(recordIds).map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
2865
3986
  BULK_OPERATION_MAX_SIZE
2866
3987
  );
2867
3988
  for (const operations of chunkedOperations) {
@@ -2872,21 +3993,22 @@ deleteRecords_fn = async function(recordIds) {
2872
3993
  region: "{region}"
2873
3994
  },
2874
3995
  body: { operations },
2875
- ...fetchProps
3996
+ ...__privateGet$4(this, _getFetchProps).call(this)
2876
3997
  });
2877
3998
  }
2878
3999
  };
2879
4000
  _setCacheQuery = new WeakSet();
2880
4001
  setCacheQuery_fn = async function(query, meta, records) {
2881
- await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
4002
+ await __privateGet$4(this, _cache)?.set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: /* @__PURE__ */ new Date(), meta, records });
2882
4003
  };
2883
4004
  _getCacheQuery = new WeakSet();
2884
4005
  getCacheQuery_fn = async function(query) {
2885
4006
  const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
2886
- const result = await __privateGet$4(this, _cache).get(key);
4007
+ const result = await __privateGet$4(this, _cache)?.get(key);
2887
4008
  if (!result)
2888
4009
  return null;
2889
- const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
4010
+ const defaultTTL = __privateGet$4(this, _cache)?.defaultQueryTTL ?? -1;
4011
+ const { cache: ttl = defaultTTL } = query.getQueryOptions();
2890
4012
  if (ttl < 0)
2891
4013
  return null;
2892
4014
  const hasExpired = result.date.getTime() + ttl < Date.now();
@@ -2896,20 +4018,47 @@ _getSchemaTables$1 = new WeakSet();
2896
4018
  getSchemaTables_fn$1 = async function() {
2897
4019
  if (__privateGet$4(this, _schemaTables$2))
2898
4020
  return __privateGet$4(this, _schemaTables$2);
2899
- const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
2900
4021
  const { schema } = await getBranchDetails({
2901
4022
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
2902
- ...fetchProps
4023
+ ...__privateGet$4(this, _getFetchProps).call(this)
2903
4024
  });
2904
4025
  __privateSet$4(this, _schemaTables$2, schema.tables);
2905
4026
  return schema.tables;
2906
4027
  };
2907
- const transformObjectLinks = (object) => {
2908
- return Object.entries(object).reduce((acc, [key, value]) => {
4028
+ _transformObjectToApi = new WeakSet();
4029
+ transformObjectToApi_fn = async function(object) {
4030
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
4031
+ const schema = schemaTables.find((table) => table.name === __privateGet$4(this, _table));
4032
+ if (!schema)
4033
+ throw new Error(`Table ${__privateGet$4(this, _table)} not found in schema`);
4034
+ const result = {};
4035
+ for (const [key, value] of Object.entries(object)) {
2909
4036
  if (key === "xata")
2910
- return acc;
2911
- return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
2912
- }, {});
4037
+ continue;
4038
+ const type = schema.columns.find((column) => column.name === key)?.type;
4039
+ switch (type) {
4040
+ case "link": {
4041
+ result[key] = isIdentifiable(value) ? value.id : value;
4042
+ break;
4043
+ }
4044
+ case "datetime": {
4045
+ result[key] = value instanceof Date ? value.toISOString() : value;
4046
+ break;
4047
+ }
4048
+ case `file`:
4049
+ result[key] = await parseInputFileEntry(value);
4050
+ break;
4051
+ case "file[]":
4052
+ result[key] = await promiseMap(value, (item) => parseInputFileEntry(item));
4053
+ break;
4054
+ case "json":
4055
+ result[key] = stringifyJson(value);
4056
+ break;
4057
+ default:
4058
+ result[key] = value;
4059
+ }
4060
+ }
4061
+ return result;
2913
4062
  };
2914
4063
  const initObject = (db, schemaTables, table, object, selectedColumns) => {
2915
4064
  const data = {};
@@ -2941,18 +4090,33 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
2941
4090
  if (item === column.name) {
2942
4091
  return [...acc, "*"];
2943
4092
  }
2944
- if (item.startsWith(`${column.name}.`)) {
4093
+ if (isString(item) && item.startsWith(`${column.name}.`)) {
2945
4094
  const [, ...path] = item.split(".");
2946
4095
  return [...acc, path.join(".")];
2947
4096
  }
2948
4097
  return acc;
2949
4098
  }, []);
2950
- data[column.name] = initObject(db, schemaTables, linkTable, value, selectedLinkColumns);
4099
+ data[column.name] = initObject(
4100
+ db,
4101
+ schemaTables,
4102
+ linkTable,
4103
+ value,
4104
+ selectedLinkColumns
4105
+ );
2951
4106
  } else {
2952
4107
  data[column.name] = null;
2953
4108
  }
2954
4109
  break;
2955
4110
  }
4111
+ case "file":
4112
+ data[column.name] = isDefined(value) ? new XataFile(value) : null;
4113
+ break;
4114
+ case "file[]":
4115
+ data[column.name] = value?.map((item) => new XataFile(item)) ?? null;
4116
+ break;
4117
+ case "json":
4118
+ data[column.name] = parseJson(value);
4119
+ break;
2956
4120
  default:
2957
4121
  data[column.name] = value ?? null;
2958
4122
  if (column.notNull === true && value === null) {
@@ -2962,30 +4126,34 @@ const initObject = (db, schemaTables, table, object, selectedColumns) => {
2962
4126
  }
2963
4127
  }
2964
4128
  const record = { ...data };
4129
+ const metadata = xata !== void 0 ? { ...xata, createdAt: new Date(xata.createdAt), updatedAt: new Date(xata.updatedAt) } : void 0;
2965
4130
  record.read = function(columns2) {
2966
4131
  return db[table].read(record["id"], columns2);
2967
4132
  };
2968
4133
  record.update = function(data2, b, c) {
2969
- const columns2 = isStringArray(b) ? b : ["*"];
4134
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
2970
4135
  const ifVersion = parseIfVersion(b, c);
2971
4136
  return db[table].update(record["id"], data2, columns2, { ifVersion });
2972
4137
  };
2973
4138
  record.replace = function(data2, b, c) {
2974
- const columns2 = isStringArray(b) ? b : ["*"];
4139
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
2975
4140
  const ifVersion = parseIfVersion(b, c);
2976
4141
  return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
2977
4142
  };
2978
4143
  record.delete = function() {
2979
4144
  return db[table].delete(record["id"]);
2980
4145
  };
4146
+ if (metadata !== void 0) {
4147
+ record.xata = Object.freeze(metadata);
4148
+ }
2981
4149
  record.getMetadata = function() {
2982
- return xata;
4150
+ return record.xata;
2983
4151
  };
2984
4152
  record.toSerializable = function() {
2985
- return JSON.parse(JSON.stringify(transformObjectLinks(data)));
4153
+ return JSON.parse(JSON.stringify(record));
2986
4154
  };
2987
4155
  record.toString = function() {
2988
- return JSON.stringify(transformObjectLinks(data));
4156
+ return JSON.stringify(record);
2989
4157
  };
2990
4158
  for (const prop of ["read", "update", "replace", "delete", "getMetadata", "toSerializable", "toString"]) {
2991
4159
  Object.defineProperty(record, prop, { enumerable: false });
@@ -3003,11 +4171,7 @@ function extractId(value) {
3003
4171
  function isValidColumn(columns, column) {
3004
4172
  if (columns.includes("*"))
3005
4173
  return true;
3006
- if (column.type === "link") {
3007
- const linkColumns = columns.filter((item) => item.startsWith(column.name));
3008
- return linkColumns.length > 0;
3009
- }
3010
- return columns.includes(column.name);
4174
+ return columns.filter((item) => isString(item) && item.startsWith(column.name)).length > 0;
3011
4175
  }
3012
4176
  function parseIfVersion(...args) {
3013
4177
  for (const arg of args) {
@@ -3084,10 +4248,12 @@ const notExists = (column) => ({ $notExists: column });
3084
4248
  const startsWith = (value) => ({ $startsWith: value });
3085
4249
  const endsWith = (value) => ({ $endsWith: value });
3086
4250
  const pattern = (value) => ({ $pattern: value });
4251
+ const iPattern = (value) => ({ $iPattern: value });
3087
4252
  const is = (value) => ({ $is: value });
3088
4253
  const equals = is;
3089
4254
  const isNot = (value) => ({ $isNot: value });
3090
4255
  const contains = (value) => ({ $contains: value });
4256
+ const iContains = (value) => ({ $iContains: value });
3091
4257
  const includes = (value) => ({ $includes: value });
3092
4258
  const includesAll = (value) => ({ $includesAll: value });
3093
4259
  const includesNone = (value) => ({ $includesNone: value });
@@ -3143,6 +4309,80 @@ class SchemaPlugin extends XataPlugin {
3143
4309
  _tables = new WeakMap();
3144
4310
  _schemaTables$1 = new WeakMap();
3145
4311
 
4312
+ class FilesPlugin extends XataPlugin {
4313
+ build(pluginOptions) {
4314
+ return {
4315
+ download: async (location) => {
4316
+ const { table, record, column, fileId = "" } = location ?? {};
4317
+ return await getFileItem({
4318
+ pathParams: {
4319
+ workspace: "{workspaceId}",
4320
+ dbBranchName: "{dbBranch}",
4321
+ region: "{region}",
4322
+ tableName: table ?? "",
4323
+ recordId: record ?? "",
4324
+ columnName: column ?? "",
4325
+ fileId
4326
+ },
4327
+ ...pluginOptions,
4328
+ rawResponse: true
4329
+ });
4330
+ },
4331
+ upload: async (location, file, options) => {
4332
+ const { table, record, column, fileId = "" } = location ?? {};
4333
+ const resolvedFile = await file;
4334
+ const contentType = options?.mediaType || getContentType(resolvedFile);
4335
+ const body = resolvedFile instanceof XataFile ? resolvedFile.toBlob() : resolvedFile;
4336
+ return await putFileItem({
4337
+ ...pluginOptions,
4338
+ pathParams: {
4339
+ workspace: "{workspaceId}",
4340
+ dbBranchName: "{dbBranch}",
4341
+ region: "{region}",
4342
+ tableName: table ?? "",
4343
+ recordId: record ?? "",
4344
+ columnName: column ?? "",
4345
+ fileId
4346
+ },
4347
+ body,
4348
+ headers: { "Content-Type": contentType }
4349
+ });
4350
+ },
4351
+ delete: async (location) => {
4352
+ const { table, record, column, fileId = "" } = location ?? {};
4353
+ return await deleteFileItem({
4354
+ pathParams: {
4355
+ workspace: "{workspaceId}",
4356
+ dbBranchName: "{dbBranch}",
4357
+ region: "{region}",
4358
+ tableName: table ?? "",
4359
+ recordId: record ?? "",
4360
+ columnName: column ?? "",
4361
+ fileId
4362
+ },
4363
+ ...pluginOptions
4364
+ });
4365
+ }
4366
+ };
4367
+ }
4368
+ }
4369
+ function getContentType(file) {
4370
+ if (typeof file === "string") {
4371
+ return "text/plain";
4372
+ }
4373
+ if ("mediaType" in file) {
4374
+ return file.mediaType;
4375
+ }
4376
+ if (isBlob(file)) {
4377
+ return file.type;
4378
+ }
4379
+ try {
4380
+ return file.type;
4381
+ } catch (e) {
4382
+ }
4383
+ return "application/octet-stream";
4384
+ }
4385
+
3146
4386
  var __accessCheck$1 = (obj, member, msg) => {
3147
4387
  if (!member.has(obj))
3148
4388
  throw TypeError("Cannot " + msg);
@@ -3175,63 +4415,137 @@ class SearchPlugin extends XataPlugin {
3175
4415
  __privateAdd$1(this, _schemaTables, void 0);
3176
4416
  __privateSet$1(this, _schemaTables, schemaTables);
3177
4417
  }
3178
- build({ getFetchProps }) {
4418
+ build(pluginOptions) {
3179
4419
  return {
3180
4420
  all: async (query, options = {}) => {
3181
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
3182
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
3183
- return records.map((record) => {
3184
- const { table = "orphan" } = record.xata;
3185
- return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
3186
- });
4421
+ const { records, totalCount } = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
4422
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
4423
+ return {
4424
+ totalCount,
4425
+ records: records.map((record) => {
4426
+ const { table = "orphan" } = record.xata;
4427
+ return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
4428
+ })
4429
+ };
3187
4430
  },
3188
4431
  byTable: async (query, options = {}) => {
3189
- const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
3190
- const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
3191
- return records.reduce((acc, record) => {
4432
+ const { records: rawRecords, totalCount } = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
4433
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
4434
+ const records = rawRecords.reduce((acc, record) => {
3192
4435
  const { table = "orphan" } = record.xata;
3193
4436
  const items = acc[table] ?? [];
3194
4437
  const item = initObject(this.db, schemaTables, table, record, ["*"]);
3195
4438
  return { ...acc, [table]: [...items, item] };
3196
4439
  }, {});
4440
+ return { totalCount, records };
3197
4441
  }
3198
4442
  };
3199
4443
  }
3200
4444
  }
3201
4445
  _schemaTables = new WeakMap();
3202
4446
  _search = new WeakSet();
3203
- search_fn = async function(query, options, getFetchProps) {
3204
- const fetchProps = await getFetchProps();
4447
+ search_fn = async function(query, options, pluginOptions) {
3205
4448
  const { tables, fuzziness, highlight, prefix, page } = options ?? {};
3206
- const { records } = await searchBranch({
4449
+ const { records, totalCount } = await searchBranch({
3207
4450
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4451
+ // @ts-ignore https://github.com/xataio/client-ts/issues/313
3208
4452
  body: { tables, query, fuzziness, prefix, highlight, page },
3209
- ...fetchProps
4453
+ ...pluginOptions
3210
4454
  });
3211
- return records;
4455
+ return { records, totalCount };
3212
4456
  };
3213
4457
  _getSchemaTables = new WeakSet();
3214
- getSchemaTables_fn = async function(getFetchProps) {
4458
+ getSchemaTables_fn = async function(pluginOptions) {
3215
4459
  if (__privateGet$1(this, _schemaTables))
3216
4460
  return __privateGet$1(this, _schemaTables);
3217
- const fetchProps = await getFetchProps();
3218
4461
  const { schema } = await getBranchDetails({
3219
4462
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3220
- ...fetchProps
4463
+ ...pluginOptions
3221
4464
  });
3222
4465
  __privateSet$1(this, _schemaTables, schema.tables);
3223
4466
  return schema.tables;
3224
4467
  };
3225
4468
 
4469
+ function escapeElement(elementRepresentation) {
4470
+ const escaped = elementRepresentation.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
4471
+ return '"' + escaped + '"';
4472
+ }
4473
+ function arrayString(val) {
4474
+ let result = "{";
4475
+ for (let i = 0; i < val.length; i++) {
4476
+ if (i > 0) {
4477
+ result = result + ",";
4478
+ }
4479
+ if (val[i] === null || typeof val[i] === "undefined") {
4480
+ result = result + "NULL";
4481
+ } else if (Array.isArray(val[i])) {
4482
+ result = result + arrayString(val[i]);
4483
+ } else if (val[i] instanceof Buffer) {
4484
+ result += "\\\\x" + val[i].toString("hex");
4485
+ } else {
4486
+ result += escapeElement(prepareValue(val[i]));
4487
+ }
4488
+ }
4489
+ result = result + "}";
4490
+ return result;
4491
+ }
4492
+ function prepareValue(value) {
4493
+ if (!isDefined(value))
4494
+ return null;
4495
+ if (value instanceof Date) {
4496
+ return value.toISOString();
4497
+ }
4498
+ if (Array.isArray(value)) {
4499
+ return arrayString(value);
4500
+ }
4501
+ if (isObject(value)) {
4502
+ return JSON.stringify(value);
4503
+ }
4504
+ try {
4505
+ return value.toString();
4506
+ } catch (e) {
4507
+ return value;
4508
+ }
4509
+ }
4510
+ function prepareParams(param1, param2) {
4511
+ if (isString(param1)) {
4512
+ return { statement: param1, params: param2?.map((value) => prepareValue(value)) };
4513
+ }
4514
+ if (isStringArray(param1)) {
4515
+ const statement = param1.reduce((acc, curr, index) => {
4516
+ return acc + curr + (index < (param2?.length ?? 0) ? "$" + (index + 1) : "");
4517
+ }, "");
4518
+ return { statement, params: param2?.map((value) => prepareValue(value)) };
4519
+ }
4520
+ if (isObject(param1)) {
4521
+ const { statement, params, consistency } = param1;
4522
+ return { statement, params: params?.map((value) => prepareValue(value)), consistency };
4523
+ }
4524
+ throw new Error("Invalid query");
4525
+ }
4526
+
4527
+ class SQLPlugin extends XataPlugin {
4528
+ build(pluginOptions) {
4529
+ return async (param1, ...param2) => {
4530
+ const { statement, params, consistency } = prepareParams(param1, param2);
4531
+ const { records, warning } = await sqlQuery({
4532
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4533
+ body: { statement, params, consistency },
4534
+ ...pluginOptions
4535
+ });
4536
+ return { records, warning };
4537
+ };
4538
+ }
4539
+ }
4540
+
3226
4541
  class TransactionPlugin extends XataPlugin {
3227
- build({ getFetchProps }) {
4542
+ build(pluginOptions) {
3228
4543
  return {
3229
4544
  run: async (operations) => {
3230
- const fetchProps = await getFetchProps();
3231
4545
  const response = await branchTransaction({
3232
4546
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
3233
4547
  body: { operations },
3234
- ...fetchProps
4548
+ ...pluginOptions
3235
4549
  });
3236
4550
  return response;
3237
4551
  }
@@ -3239,91 +4553,6 @@ class TransactionPlugin extends XataPlugin {
3239
4553
  }
3240
4554
  }
3241
4555
 
3242
- const isBranchStrategyBuilder = (strategy) => {
3243
- return typeof strategy === "function";
3244
- };
3245
-
3246
- async function getCurrentBranchName(options) {
3247
- const { branch, envBranch } = getEnvironment();
3248
- if (branch)
3249
- return branch;
3250
- const gitBranch = envBranch || await getGitBranch();
3251
- return resolveXataBranch(gitBranch, options);
3252
- }
3253
- async function getCurrentBranchDetails(options) {
3254
- const branch = await getCurrentBranchName(options);
3255
- return getDatabaseBranch(branch, options);
3256
- }
3257
- async function resolveXataBranch(gitBranch, options) {
3258
- const databaseURL = options?.databaseURL || getDatabaseURL();
3259
- const apiKey = options?.apiKey || getAPIKey();
3260
- if (!databaseURL)
3261
- throw new Error(
3262
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
3263
- );
3264
- if (!apiKey)
3265
- throw new Error(
3266
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
3267
- );
3268
- const [protocol, , host, , dbName] = databaseURL.split("/");
3269
- const urlParts = parseWorkspacesUrlParts(host);
3270
- if (!urlParts)
3271
- throw new Error(`Unable to parse workspace and region: ${databaseURL}`);
3272
- const { workspace, region } = urlParts;
3273
- const { fallbackBranch } = getEnvironment();
3274
- const { branch } = await resolveBranch({
3275
- apiKey,
3276
- apiUrl: databaseURL,
3277
- fetchImpl: getFetchImplementation(options?.fetchImpl),
3278
- workspacesApiUrl: `${protocol}//${host}`,
3279
- pathParams: { dbName, workspace, region },
3280
- queryParams: { gitBranch, fallbackBranch },
3281
- trace: defaultTrace,
3282
- clientName: options?.clientName,
3283
- xataAgentExtra: options?.xataAgentExtra
3284
- });
3285
- return branch;
3286
- }
3287
- async function getDatabaseBranch(branch, options) {
3288
- const databaseURL = options?.databaseURL || getDatabaseURL();
3289
- const apiKey = options?.apiKey || getAPIKey();
3290
- if (!databaseURL)
3291
- throw new Error(
3292
- "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
3293
- );
3294
- if (!apiKey)
3295
- throw new Error(
3296
- "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
3297
- );
3298
- const [protocol, , host, , database] = databaseURL.split("/");
3299
- const urlParts = parseWorkspacesUrlParts(host);
3300
- if (!urlParts)
3301
- throw new Error(`Unable to parse workspace and region: ${databaseURL}`);
3302
- const { workspace, region } = urlParts;
3303
- try {
3304
- return await getBranchDetails({
3305
- apiKey,
3306
- apiUrl: databaseURL,
3307
- fetchImpl: getFetchImplementation(options?.fetchImpl),
3308
- workspacesApiUrl: `${protocol}//${host}`,
3309
- pathParams: { dbBranchName: `${database}:${branch}`, workspace, region },
3310
- trace: defaultTrace
3311
- });
3312
- } catch (err) {
3313
- if (isObject(err) && err.status === 404)
3314
- return null;
3315
- throw err;
3316
- }
3317
- }
3318
- function getDatabaseURL() {
3319
- try {
3320
- const { databaseURL } = getEnvironment();
3321
- return databaseURL;
3322
- } catch (err) {
3323
- return void 0;
3324
- }
3325
- }
3326
-
3327
4556
  var __accessCheck = (obj, member, msg) => {
3328
4557
  if (!member.has(obj))
3329
4558
  throw TypeError("Cannot " + msg);
@@ -3347,46 +4576,41 @@ var __privateMethod = (obj, member, method) => {
3347
4576
  return method;
3348
4577
  };
3349
4578
  const buildClient = (plugins) => {
3350
- var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
4579
+ var _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _a;
3351
4580
  return _a = class {
3352
4581
  constructor(options = {}, schemaTables) {
3353
4582
  __privateAdd(this, _parseOptions);
3354
4583
  __privateAdd(this, _getFetchProps);
3355
- __privateAdd(this, _evaluateBranch);
3356
- __privateAdd(this, _branch, void 0);
3357
4584
  __privateAdd(this, _options, void 0);
3358
4585
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
3359
4586
  __privateSet(this, _options, safeOptions);
3360
4587
  const pluginOptions = {
3361
- getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
4588
+ ...__privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
3362
4589
  cache: safeOptions.cache,
3363
- trace: safeOptions.trace
4590
+ host: safeOptions.host
3364
4591
  };
3365
4592
  const db = new SchemaPlugin(schemaTables).build(pluginOptions);
3366
4593
  const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
3367
4594
  const transactions = new TransactionPlugin().build(pluginOptions);
4595
+ const sql = new SQLPlugin().build(pluginOptions);
4596
+ const files = new FilesPlugin().build(pluginOptions);
3368
4597
  this.db = db;
3369
4598
  this.search = search;
3370
4599
  this.transactions = transactions;
4600
+ this.sql = sql;
4601
+ this.files = files;
3371
4602
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
3372
4603
  if (namespace === void 0)
3373
4604
  continue;
3374
- const result = namespace.build(pluginOptions);
3375
- if (result instanceof Promise) {
3376
- void result.then((namespace2) => {
3377
- this[key] = namespace2;
3378
- });
3379
- } else {
3380
- this[key] = result;
3381
- }
4605
+ this[key] = namespace.build(pluginOptions);
3382
4606
  }
3383
4607
  }
3384
4608
  async getConfig() {
3385
4609
  const databaseURL = __privateGet(this, _options).databaseURL;
3386
- const branch = await __privateGet(this, _options).branch();
4610
+ const branch = __privateGet(this, _options).branch;
3387
4611
  return { databaseURL, branch };
3388
4612
  }
3389
- }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
4613
+ }, _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
3390
4614
  const enableBrowser = options?.enableBrowser ?? getEnableBrowserVariable() ?? false;
3391
4615
  const isBrowser = typeof window !== "undefined" && typeof Deno === "undefined";
3392
4616
  if (isBrowser && !enableBrowser) {
@@ -3400,20 +4624,34 @@ const buildClient = (plugins) => {
3400
4624
  const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
3401
4625
  const trace = options?.trace ?? defaultTrace;
3402
4626
  const clientName = options?.clientName;
4627
+ const host = options?.host ?? "production";
3403
4628
  const xataAgentExtra = options?.xataAgentExtra;
3404
- const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({
3405
- apiKey,
3406
- databaseURL,
3407
- fetchImpl: options?.fetch,
3408
- clientName,
3409
- xataAgentExtra
3410
- });
3411
4629
  if (!apiKey) {
3412
4630
  throw new Error("Option apiKey is required");
3413
4631
  }
3414
4632
  if (!databaseURL) {
3415
4633
  throw new Error("Option databaseURL is required");
3416
4634
  }
4635
+ const envBranch = getBranch();
4636
+ const previewBranch = getPreviewBranch();
4637
+ const branch = options?.branch || previewBranch || envBranch || "main";
4638
+ if (!!previewBranch && branch !== previewBranch) {
4639
+ console.warn(
4640
+ `Ignoring preview branch ${previewBranch} because branch option was passed to the client constructor with value ${branch}`
4641
+ );
4642
+ } else if (!!envBranch && branch !== envBranch) {
4643
+ console.warn(
4644
+ `Ignoring branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
4645
+ );
4646
+ } else if (!!previewBranch && !!envBranch && previewBranch !== envBranch) {
4647
+ console.warn(
4648
+ `Ignoring preview branch ${previewBranch} and branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
4649
+ );
4650
+ } else if (!previewBranch && !envBranch && options?.branch === void 0) {
4651
+ console.warn(
4652
+ `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.`
4653
+ );
4654
+ }
3417
4655
  return {
3418
4656
  fetch,
3419
4657
  databaseURL,
@@ -3421,12 +4659,13 @@ const buildClient = (plugins) => {
3421
4659
  branch,
3422
4660
  cache,
3423
4661
  trace,
4662
+ host,
3424
4663
  clientID: generateUUID(),
3425
4664
  enableBrowser,
3426
4665
  clientName,
3427
4666
  xataAgentExtra
3428
4667
  };
3429
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
4668
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = function({
3430
4669
  fetch,
3431
4670
  apiKey,
3432
4671
  databaseURL,
@@ -3436,16 +4675,14 @@ const buildClient = (plugins) => {
3436
4675
  clientName,
3437
4676
  xataAgentExtra
3438
4677
  }) {
3439
- const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
3440
- if (!branchValue)
3441
- throw new Error("Unable to resolve branch value");
3442
4678
  return {
3443
- fetchImpl: fetch,
4679
+ fetch,
3444
4680
  apiKey,
3445
4681
  apiUrl: "",
4682
+ // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
3446
4683
  workspacesApiUrl: (path, params) => {
3447
4684
  const hasBranch = params.dbBranchName ?? params.branch;
3448
- const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branchValue}` : "");
4685
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branch}` : "");
3449
4686
  return databaseURL + newPath;
3450
4687
  },
3451
4688
  trace,
@@ -3453,22 +4690,6 @@ const buildClient = (plugins) => {
3453
4690
  clientName,
3454
4691
  xataAgentExtra
3455
4692
  };
3456
- }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
3457
- if (__privateGet(this, _branch))
3458
- return __privateGet(this, _branch);
3459
- if (param === void 0)
3460
- return void 0;
3461
- const strategies = Array.isArray(param) ? [...param] : [param];
3462
- const evaluateBranch = async (strategy) => {
3463
- return isBranchStrategyBuilder(strategy) ? await strategy() : strategy;
3464
- };
3465
- for await (const strategy of strategies) {
3466
- const branch = await evaluateBranch(strategy);
3467
- if (branch) {
3468
- __privateSet(this, _branch, branch);
3469
- return branch;
3470
- }
3471
- }
3472
4693
  }, _a;
3473
4694
  };
3474
4695
  class BaseClient extends buildClient() {
@@ -3541,21 +4762,6 @@ const deserialize = (json) => {
3541
4762
  return defaultSerializer.fromJSON(json);
3542
4763
  };
3543
4764
 
3544
- function buildWorkerRunner(config) {
3545
- return function xataWorker(name, worker) {
3546
- return async (...args) => {
3547
- const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
3548
- const result = await fetch(url, {
3549
- method: "POST",
3550
- headers: { "Content-Type": "application/json" },
3551
- body: serialize({ args })
3552
- });
3553
- const text = await result.text();
3554
- return deserialize(text);
3555
- };
3556
- };
3557
- }
3558
-
3559
4765
  class XataError extends Error {
3560
4766
  constructor(message, status) {
3561
4767
  super(message);
@@ -3563,5 +4769,5 @@ class XataError extends Error {
3563
4769
  }
3564
4770
  }
3565
4771
 
3566
- export { BaseClient, FetcherError, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, Serializer, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, aggregateTable, applyBranchSchemaEdit, branchTransaction, buildClient, buildWorkerRunner, bulkInsertTableRecords, cancelWorkspaceMemberInvite, compareBranchSchemas, compareBranchWithUserSchema, compareMigrationRequest, contains, createBranch, createDatabase, createMigrationRequest, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteDatabaseGithubSettings, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, deserialize, endsWith, equals, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchSchemaHistory, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseGithubSettings, getDatabaseList, getDatabaseMetadata, getDatabaseURL, getGitBranchesMapping, getHostUrl, getMigrationRequest, getMigrationRequestIsMerged, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, greaterEquals, greaterThan, greaterThanEquals, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isHostProviderAlias, isHostProviderBuilder, isIdentifiable, isNot, isXataRecord, le, lessEquals, lessThan, lessThanEquals, listMigrationRequestsCommits, listRegions, lt, lte, mergeMigrationRequest, notExists, operationsByTag, parseProviderString, parseWorkspacesUrlParts, pattern, previewBranchSchemaEdit, queryMigrationRequests, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, serialize, setTableSchema, startsWith, summarizeTable, updateBranchMetadata, updateBranchSchema, updateColumn, updateDatabaseGithubSettings, updateDatabaseMetadata, updateMigrationRequest, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID };
4772
+ export { BaseClient, FetcherError, FilesPlugin, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, RecordColumnTypes, Repository, RestRepository, SQLPlugin, SchemaPlugin, SearchPlugin, Serializer, SimpleCache, TransactionPlugin, XataApiClient, XataApiPlugin, XataError, XataFile, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, aggregateTable, applyBranchSchemaEdit, applyMigration, askTable, askTableSession, branchTransaction, buildClient, buildPreviewBranchName, buildProviderString, bulkInsertTableRecords, cancelWorkspaceMemberInvite, compareBranchSchemas, compareBranchWithUserSchema, compareMigrationRequest, contains, copyBranch, createBranch, createCluster, createDatabase, createMigrationRequest, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteDatabaseGithubSettings, deleteFile, deleteFileItem, deleteOAuthAccessToken, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteUserOAuthClient, deleteWorkspace, deserialize, endsWith, equals, executeBranchMigrationPlan, exists, fileAccess, ge, getAPIKey, getAuthorizationCode, getBranch, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchSchemaHistory, getBranchStats, getCluster, getColumn, getDatabaseGithubSettings, getDatabaseList, getDatabaseMetadata, getDatabaseURL, getFile, getFileItem, getGitBranchesMapping, getHostUrl, getMigrationRequest, getMigrationRequestIsMerged, getPreviewBranch, getRecord, getSchema, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getUserOAuthAccessTokens, getUserOAuthClients, getWorkspace, getWorkspaceMembersList, getWorkspacesList, grantAuthorizationCode, greaterEquals, greaterThan, greaterThanEquals, gt, gte, iContains, iPattern, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isHostProviderAlias, isHostProviderBuilder, isIdentifiable, isNot, isValidExpandedColumn, isValidSelectableColumns, isXataRecord, le, lessEquals, lessThan, lessThanEquals, listClusters, listMigrationRequestsCommits, listRegions, lt, lte, mergeMigrationRequest, notExists, operationsByTag, parseProviderString, parseWorkspacesUrlParts, pattern, pgRollStatus, previewBranchSchemaEdit, pushBranchMigrations, putFile, putFileItem, queryMigrationRequests, queryTable, removeGitBranchesEntry, removeWorkspaceMember, renameDatabase, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, serialize, setTableSchema, sqlQuery, startsWith, summarizeTable, transformImage, updateBranchMetadata, updateBranchSchema, updateCluster, updateColumn, updateDatabaseGithubSettings, updateDatabaseMetadata, updateMigrationRequest, updateOAuthAccessToken, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID, vectorSearchTable };
3567
4773
  //# sourceMappingURL=index.mjs.map