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