@xata.io/client 0.0.0-alpha.vf166c7e → 0.0.0-alpha.vf181bf6b5770b15d42125b2728f3bf80a87e6333

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