@xata.io/client 0.0.0-alpha.ve276c32 → 0.0.0-alpha.ve2d4e87

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.
Files changed (71) hide show
  1. package/.turbo/turbo-add-version.log +4 -0
  2. package/.turbo/turbo-build.log +13 -0
  3. package/CHANGELOG.md +648 -0
  4. package/README.md +7 -1
  5. package/dist/index.cjs +5032 -0
  6. package/dist/index.cjs.map +1 -0
  7. package/dist/index.d.ts +9471 -6
  8. package/dist/index.mjs +4860 -0
  9. package/dist/index.mjs.map +1 -0
  10. package/package.json +20 -10
  11. package/.eslintrc.cjs +0 -13
  12. package/dist/api/client.d.ts +0 -95
  13. package/dist/api/client.js +0 -251
  14. package/dist/api/components.d.ts +0 -1437
  15. package/dist/api/components.js +0 -998
  16. package/dist/api/fetcher.d.ts +0 -40
  17. package/dist/api/fetcher.js +0 -79
  18. package/dist/api/index.d.ts +0 -7
  19. package/dist/api/index.js +0 -21
  20. package/dist/api/parameters.d.ts +0 -16
  21. package/dist/api/parameters.js +0 -2
  22. package/dist/api/providers.d.ts +0 -8
  23. package/dist/api/providers.js +0 -30
  24. package/dist/api/responses.d.ts +0 -50
  25. package/dist/api/responses.js +0 -2
  26. package/dist/api/schemas.d.ts +0 -311
  27. package/dist/api/schemas.js +0 -2
  28. package/dist/client.d.ts +0 -39
  29. package/dist/client.js +0 -124
  30. package/dist/index.js +0 -29
  31. package/dist/namespace.d.ts +0 -7
  32. package/dist/namespace.js +0 -6
  33. package/dist/schema/filters.d.ts +0 -96
  34. package/dist/schema/filters.js +0 -2
  35. package/dist/schema/filters.spec.d.ts +0 -1
  36. package/dist/schema/filters.spec.js +0 -177
  37. package/dist/schema/index.d.ts +0 -21
  38. package/dist/schema/index.js +0 -49
  39. package/dist/schema/operators.d.ts +0 -74
  40. package/dist/schema/operators.js +0 -93
  41. package/dist/schema/pagination.d.ts +0 -83
  42. package/dist/schema/pagination.js +0 -93
  43. package/dist/schema/query.d.ts +0 -118
  44. package/dist/schema/query.js +0 -242
  45. package/dist/schema/record.d.ts +0 -66
  46. package/dist/schema/record.js +0 -13
  47. package/dist/schema/repository.d.ts +0 -134
  48. package/dist/schema/repository.js +0 -284
  49. package/dist/schema/selection.d.ts +0 -25
  50. package/dist/schema/selection.js +0 -2
  51. package/dist/schema/selection.spec.d.ts +0 -1
  52. package/dist/schema/selection.spec.js +0 -204
  53. package/dist/schema/sorting.d.ts +0 -22
  54. package/dist/schema/sorting.js +0 -35
  55. package/dist/schema/sorting.spec.d.ts +0 -1
  56. package/dist/schema/sorting.spec.js +0 -11
  57. package/dist/search/index.d.ts +0 -34
  58. package/dist/search/index.js +0 -55
  59. package/dist/util/branches.d.ts +0 -5
  60. package/dist/util/branches.js +0 -7
  61. package/dist/util/config.d.ts +0 -11
  62. package/dist/util/config.js +0 -121
  63. package/dist/util/environment.d.ts +0 -5
  64. package/dist/util/environment.js +0 -68
  65. package/dist/util/fetch.d.ts +0 -2
  66. package/dist/util/fetch.js +0 -13
  67. package/dist/util/lang.d.ts +0 -5
  68. package/dist/util/lang.js +0 -22
  69. package/dist/util/types.d.ts +0 -25
  70. package/dist/util/types.js +0 -2
  71. package/tsconfig.json +0 -21
package/dist/index.cjs ADDED
@@ -0,0 +1,5032 @@
1
+ 'use strict';
2
+
3
+ const defaultTrace = async (name, fn, _options) => {
4
+ return await fn({
5
+ name,
6
+ setAttributes: () => {
7
+ return;
8
+ }
9
+ });
10
+ };
11
+ const TraceAttributes = {
12
+ KIND: "xata.trace.kind",
13
+ VERSION: "xata.sdk.version",
14
+ TABLE: "xata.table",
15
+ HTTP_REQUEST_ID: "http.request_id",
16
+ HTTP_STATUS_CODE: "http.status_code",
17
+ HTTP_HOST: "http.host",
18
+ HTTP_SCHEME: "http.scheme",
19
+ HTTP_USER_AGENT: "http.user_agent",
20
+ HTTP_METHOD: "http.method",
21
+ HTTP_URL: "http.url",
22
+ HTTP_ROUTE: "http.route",
23
+ HTTP_TARGET: "http.target",
24
+ CLOUDFLARE_RAY_ID: "cf.ray"
25
+ };
26
+
27
+ function notEmpty(value) {
28
+ return value !== null && value !== void 0;
29
+ }
30
+ function compact(arr) {
31
+ return arr.filter(notEmpty);
32
+ }
33
+ function compactObject(obj) {
34
+ return Object.fromEntries(Object.entries(obj).filter(([, value]) => notEmpty(value)));
35
+ }
36
+ function isBlob(value) {
37
+ try {
38
+ return value instanceof Blob;
39
+ } catch (error) {
40
+ return false;
41
+ }
42
+ }
43
+ function isObject(value) {
44
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date) && !isBlob(value);
45
+ }
46
+ function isDefined(value) {
47
+ return value !== null && value !== void 0;
48
+ }
49
+ function isString(value) {
50
+ return isDefined(value) && typeof value === "string";
51
+ }
52
+ function isStringArray(value) {
53
+ return isDefined(value) && Array.isArray(value) && value.every(isString);
54
+ }
55
+ function isNumber(value) {
56
+ return isDefined(value) && typeof value === "number";
57
+ }
58
+ function parseNumber(value) {
59
+ if (isNumber(value)) {
60
+ return value;
61
+ }
62
+ if (isString(value)) {
63
+ const parsed = Number(value);
64
+ if (!Number.isNaN(parsed)) {
65
+ return parsed;
66
+ }
67
+ }
68
+ return void 0;
69
+ }
70
+ function toBase64(value) {
71
+ try {
72
+ return btoa(value);
73
+ } catch (err) {
74
+ const buf = Buffer;
75
+ return buf.from(value).toString("base64");
76
+ }
77
+ }
78
+ function deepMerge(a, b) {
79
+ const result = { ...a };
80
+ for (const [key, value] of Object.entries(b)) {
81
+ if (isObject(value) && isObject(result[key])) {
82
+ result[key] = deepMerge(result[key], value);
83
+ } else {
84
+ result[key] = value;
85
+ }
86
+ }
87
+ return result;
88
+ }
89
+ function chunk(array, chunkSize) {
90
+ const result = [];
91
+ for (let i = 0; i < array.length; i += chunkSize) {
92
+ result.push(array.slice(i, i + chunkSize));
93
+ }
94
+ return result;
95
+ }
96
+ async function timeout(ms) {
97
+ return new Promise((resolve) => setTimeout(resolve, ms));
98
+ }
99
+ function timeoutWithCancel(ms) {
100
+ let timeoutId;
101
+ const promise = new Promise((resolve) => {
102
+ timeoutId = setTimeout(() => {
103
+ resolve();
104
+ }, ms);
105
+ });
106
+ return {
107
+ cancel: () => clearTimeout(timeoutId),
108
+ promise
109
+ };
110
+ }
111
+ function promiseMap(inputValues, mapper) {
112
+ const reducer = (acc$, inputValue) => acc$.then(
113
+ (acc) => mapper(inputValue).then((result) => {
114
+ acc.push(result);
115
+ return acc;
116
+ })
117
+ );
118
+ return inputValues.reduce(reducer, Promise.resolve([]));
119
+ }
120
+
121
+ function getEnvironment() {
122
+ try {
123
+ if (isDefined(process) && isDefined(process.env)) {
124
+ return {
125
+ apiKey: process.env.XATA_API_KEY ?? getGlobalApiKey(),
126
+ databaseURL: process.env.XATA_DATABASE_URL ?? getGlobalDatabaseURL(),
127
+ branch: process.env.XATA_BRANCH ?? getGlobalBranch(),
128
+ deployPreview: process.env.XATA_PREVIEW,
129
+ deployPreviewBranch: process.env.XATA_PREVIEW_BRANCH,
130
+ vercelGitCommitRef: process.env.VERCEL_GIT_COMMIT_REF,
131
+ vercelGitRepoOwner: process.env.VERCEL_GIT_REPO_OWNER
132
+ };
133
+ }
134
+ } catch (err) {
135
+ }
136
+ try {
137
+ if (isObject(Deno) && isObject(Deno.env)) {
138
+ return {
139
+ apiKey: Deno.env.get("XATA_API_KEY") ?? getGlobalApiKey(),
140
+ databaseURL: Deno.env.get("XATA_DATABASE_URL") ?? getGlobalDatabaseURL(),
141
+ branch: Deno.env.get("XATA_BRANCH") ?? getGlobalBranch(),
142
+ deployPreview: Deno.env.get("XATA_PREVIEW"),
143
+ deployPreviewBranch: Deno.env.get("XATA_PREVIEW_BRANCH"),
144
+ vercelGitCommitRef: Deno.env.get("VERCEL_GIT_COMMIT_REF"),
145
+ vercelGitRepoOwner: Deno.env.get("VERCEL_GIT_REPO_OWNER")
146
+ };
147
+ }
148
+ } catch (err) {
149
+ }
150
+ return {
151
+ apiKey: getGlobalApiKey(),
152
+ databaseURL: getGlobalDatabaseURL(),
153
+ branch: getGlobalBranch(),
154
+ deployPreview: void 0,
155
+ deployPreviewBranch: void 0,
156
+ vercelGitCommitRef: void 0,
157
+ vercelGitRepoOwner: void 0
158
+ };
159
+ }
160
+ function getEnableBrowserVariable() {
161
+ try {
162
+ if (isObject(process) && isObject(process.env) && process.env.XATA_ENABLE_BROWSER !== void 0) {
163
+ return process.env.XATA_ENABLE_BROWSER === "true";
164
+ }
165
+ } catch (err) {
166
+ }
167
+ try {
168
+ if (isObject(Deno) && isObject(Deno.env) && Deno.env.get("XATA_ENABLE_BROWSER") !== void 0) {
169
+ return Deno.env.get("XATA_ENABLE_BROWSER") === "true";
170
+ }
171
+ } catch (err) {
172
+ }
173
+ try {
174
+ return XATA_ENABLE_BROWSER === true || XATA_ENABLE_BROWSER === "true";
175
+ } catch (err) {
176
+ return void 0;
177
+ }
178
+ }
179
+ function getGlobalApiKey() {
180
+ try {
181
+ return XATA_API_KEY;
182
+ } catch (err) {
183
+ return void 0;
184
+ }
185
+ }
186
+ function getGlobalDatabaseURL() {
187
+ try {
188
+ return XATA_DATABASE_URL;
189
+ } catch (err) {
190
+ return void 0;
191
+ }
192
+ }
193
+ function getGlobalBranch() {
194
+ try {
195
+ return XATA_BRANCH;
196
+ } catch (err) {
197
+ return void 0;
198
+ }
199
+ }
200
+ function getDatabaseURL() {
201
+ try {
202
+ const { databaseURL } = getEnvironment();
203
+ return databaseURL;
204
+ } catch (err) {
205
+ return void 0;
206
+ }
207
+ }
208
+ function getAPIKey() {
209
+ try {
210
+ const { apiKey } = getEnvironment();
211
+ return apiKey;
212
+ } catch (err) {
213
+ return void 0;
214
+ }
215
+ }
216
+ function getBranch() {
217
+ try {
218
+ const { branch } = getEnvironment();
219
+ return branch;
220
+ } catch (err) {
221
+ return void 0;
222
+ }
223
+ }
224
+ function buildPreviewBranchName({ org, branch }) {
225
+ return `preview-${org}-${branch}`;
226
+ }
227
+ function getPreviewBranch() {
228
+ try {
229
+ const { deployPreview, deployPreviewBranch, vercelGitCommitRef, vercelGitRepoOwner } = getEnvironment();
230
+ if (deployPreviewBranch)
231
+ return deployPreviewBranch;
232
+ switch (deployPreview) {
233
+ case "vercel": {
234
+ if (!vercelGitCommitRef || !vercelGitRepoOwner) {
235
+ console.warn("XATA_PREVIEW=vercel but VERCEL_GIT_COMMIT_REF or VERCEL_GIT_REPO_OWNER is not valid");
236
+ return void 0;
237
+ }
238
+ return buildPreviewBranchName({ org: vercelGitRepoOwner, branch: vercelGitCommitRef });
239
+ }
240
+ }
241
+ return void 0;
242
+ } catch (err) {
243
+ return void 0;
244
+ }
245
+ }
246
+
247
+ var __defProp$8 = Object.defineProperty;
248
+ var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
249
+ var __publicField$8 = (obj, key, value) => {
250
+ __defNormalProp$8(obj, typeof key !== "symbol" ? key + "" : key, value);
251
+ return value;
252
+ };
253
+ var __accessCheck$8 = (obj, member, msg) => {
254
+ if (!member.has(obj))
255
+ throw TypeError("Cannot " + msg);
256
+ };
257
+ var __privateGet$8 = (obj, member, getter) => {
258
+ __accessCheck$8(obj, member, "read from private field");
259
+ return getter ? getter.call(obj) : member.get(obj);
260
+ };
261
+ var __privateAdd$8 = (obj, member, value) => {
262
+ if (member.has(obj))
263
+ throw TypeError("Cannot add the same private member more than once");
264
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
265
+ };
266
+ var __privateSet$8 = (obj, member, value, setter) => {
267
+ __accessCheck$8(obj, member, "write to private field");
268
+ setter ? setter.call(obj, value) : member.set(obj, value);
269
+ return value;
270
+ };
271
+ var __privateMethod$4 = (obj, member, method) => {
272
+ __accessCheck$8(obj, member, "access private method");
273
+ return method;
274
+ };
275
+ var _fetch, _queue, _concurrency, _enqueue, enqueue_fn;
276
+ const REQUEST_TIMEOUT = 5 * 60 * 1e3;
277
+ function getFetchImplementation(userFetch) {
278
+ const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
279
+ const globalThisFetch = typeof globalThis !== "undefined" ? globalThis.fetch : void 0;
280
+ const fetchImpl = userFetch ?? globalFetch ?? globalThisFetch;
281
+ if (!fetchImpl) {
282
+ throw new Error(`Couldn't find a global \`fetch\`. Pass a fetch implementation explicitly.`);
283
+ }
284
+ return fetchImpl;
285
+ }
286
+ class ApiRequestPool {
287
+ constructor(concurrency = 10) {
288
+ __privateAdd$8(this, _enqueue);
289
+ __privateAdd$8(this, _fetch, void 0);
290
+ __privateAdd$8(this, _queue, void 0);
291
+ __privateAdd$8(this, _concurrency, void 0);
292
+ __publicField$8(this, "running");
293
+ __publicField$8(this, "started");
294
+ __privateSet$8(this, _queue, []);
295
+ __privateSet$8(this, _concurrency, concurrency);
296
+ this.running = 0;
297
+ this.started = 0;
298
+ }
299
+ setFetch(fetch2) {
300
+ __privateSet$8(this, _fetch, fetch2);
301
+ }
302
+ getFetch() {
303
+ if (!__privateGet$8(this, _fetch)) {
304
+ throw new Error("Fetch not set");
305
+ }
306
+ return __privateGet$8(this, _fetch);
307
+ }
308
+ request(url, options) {
309
+ const start = /* @__PURE__ */ new Date();
310
+ const fetchImpl = this.getFetch();
311
+ const runRequest = async (stalled = false) => {
312
+ const { promise, cancel } = timeoutWithCancel(REQUEST_TIMEOUT);
313
+ const response = await Promise.race([fetchImpl(url, options), promise.then(() => null)]).finally(cancel);
314
+ if (!response) {
315
+ throw new Error("Request timed out");
316
+ }
317
+ if (response.status === 429) {
318
+ const rateLimitReset = parseNumber(response.headers?.get("x-ratelimit-reset")) ?? 1;
319
+ await timeout(rateLimitReset * 1e3);
320
+ return await runRequest(true);
321
+ }
322
+ if (stalled) {
323
+ const stalledTime = (/* @__PURE__ */ new Date()).getTime() - start.getTime();
324
+ console.warn(`A request to Xata hit branch rate limits, was retried and stalled for ${stalledTime}ms`);
325
+ }
326
+ return response;
327
+ };
328
+ return __privateMethod$4(this, _enqueue, enqueue_fn).call(this, async () => {
329
+ return await runRequest();
330
+ });
331
+ }
332
+ }
333
+ _fetch = new WeakMap();
334
+ _queue = new WeakMap();
335
+ _concurrency = new WeakMap();
336
+ _enqueue = new WeakSet();
337
+ enqueue_fn = function(task) {
338
+ const promise = new Promise((resolve) => __privateGet$8(this, _queue).push(resolve)).finally(() => {
339
+ this.started--;
340
+ this.running++;
341
+ }).then(() => task()).finally(() => {
342
+ this.running--;
343
+ const next = __privateGet$8(this, _queue).shift();
344
+ if (next !== void 0) {
345
+ this.started++;
346
+ next();
347
+ }
348
+ });
349
+ if (this.running + this.started < __privateGet$8(this, _concurrency)) {
350
+ const next = __privateGet$8(this, _queue).shift();
351
+ if (next !== void 0) {
352
+ this.started++;
353
+ next();
354
+ }
355
+ }
356
+ return promise;
357
+ };
358
+
359
+ function generateUUID() {
360
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
361
+ const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
362
+ return v.toString(16);
363
+ });
364
+ }
365
+
366
+ async function getBytes(stream, onChunk) {
367
+ const reader = stream.getReader();
368
+ let result;
369
+ while (!(result = await reader.read()).done) {
370
+ onChunk(result.value);
371
+ }
372
+ }
373
+ function getLines(onLine) {
374
+ let buffer;
375
+ let position;
376
+ let fieldLength;
377
+ let discardTrailingNewline = false;
378
+ return function onChunk(arr) {
379
+ if (buffer === void 0) {
380
+ buffer = arr;
381
+ position = 0;
382
+ fieldLength = -1;
383
+ } else {
384
+ buffer = concat(buffer, arr);
385
+ }
386
+ const bufLength = buffer.length;
387
+ let lineStart = 0;
388
+ while (position < bufLength) {
389
+ if (discardTrailingNewline) {
390
+ if (buffer[position] === 10 /* NewLine */) {
391
+ lineStart = ++position;
392
+ }
393
+ discardTrailingNewline = false;
394
+ }
395
+ let lineEnd = -1;
396
+ for (; position < bufLength && lineEnd === -1; ++position) {
397
+ switch (buffer[position]) {
398
+ case 58 /* Colon */:
399
+ if (fieldLength === -1) {
400
+ fieldLength = position - lineStart;
401
+ }
402
+ break;
403
+ case 13 /* CarriageReturn */:
404
+ discardTrailingNewline = true;
405
+ case 10 /* NewLine */:
406
+ lineEnd = position;
407
+ break;
408
+ }
409
+ }
410
+ if (lineEnd === -1) {
411
+ break;
412
+ }
413
+ onLine(buffer.subarray(lineStart, lineEnd), fieldLength);
414
+ lineStart = position;
415
+ fieldLength = -1;
416
+ }
417
+ if (lineStart === bufLength) {
418
+ buffer = void 0;
419
+ } else if (lineStart !== 0) {
420
+ buffer = buffer.subarray(lineStart);
421
+ position -= lineStart;
422
+ }
423
+ };
424
+ }
425
+ function getMessages(onId, onRetry, onMessage) {
426
+ let message = newMessage();
427
+ const decoder = new TextDecoder();
428
+ return function onLine(line, fieldLength) {
429
+ if (line.length === 0) {
430
+ onMessage?.(message);
431
+ message = newMessage();
432
+ } else if (fieldLength > 0) {
433
+ const field = decoder.decode(line.subarray(0, fieldLength));
434
+ const valueOffset = fieldLength + (line[fieldLength + 1] === 32 /* Space */ ? 2 : 1);
435
+ const value = decoder.decode(line.subarray(valueOffset));
436
+ switch (field) {
437
+ case "data":
438
+ message.data = message.data ? message.data + "\n" + value : value;
439
+ break;
440
+ case "event":
441
+ message.event = value;
442
+ break;
443
+ case "id":
444
+ onId(message.id = value);
445
+ break;
446
+ case "retry":
447
+ const retry = parseInt(value, 10);
448
+ if (!isNaN(retry)) {
449
+ onRetry(message.retry = retry);
450
+ }
451
+ break;
452
+ }
453
+ }
454
+ };
455
+ }
456
+ function concat(a, b) {
457
+ const res = new Uint8Array(a.length + b.length);
458
+ res.set(a);
459
+ res.set(b, a.length);
460
+ return res;
461
+ }
462
+ function newMessage() {
463
+ return {
464
+ data: "",
465
+ event: "",
466
+ id: "",
467
+ retry: void 0
468
+ };
469
+ }
470
+ const EventStreamContentType = "text/event-stream";
471
+ const LastEventId = "last-event-id";
472
+ function fetchEventSource(input, {
473
+ signal: inputSignal,
474
+ headers: inputHeaders,
475
+ onopen: inputOnOpen,
476
+ onmessage,
477
+ onclose,
478
+ onerror,
479
+ fetch: inputFetch,
480
+ ...rest
481
+ }) {
482
+ return new Promise((resolve, reject) => {
483
+ const headers = { ...inputHeaders };
484
+ if (!headers.accept) {
485
+ headers.accept = EventStreamContentType;
486
+ }
487
+ let curRequestController;
488
+ function dispose() {
489
+ curRequestController.abort();
490
+ }
491
+ inputSignal?.addEventListener("abort", () => {
492
+ dispose();
493
+ resolve();
494
+ });
495
+ const fetchImpl = inputFetch ?? fetch;
496
+ const onopen = inputOnOpen ?? defaultOnOpen;
497
+ async function create() {
498
+ curRequestController = new AbortController();
499
+ try {
500
+ const response = await fetchImpl(input, {
501
+ ...rest,
502
+ headers,
503
+ signal: curRequestController.signal
504
+ });
505
+ await onopen(response);
506
+ await getBytes(
507
+ response.body,
508
+ getLines(
509
+ getMessages(
510
+ (id) => {
511
+ if (id) {
512
+ headers[LastEventId] = id;
513
+ } else {
514
+ delete headers[LastEventId];
515
+ }
516
+ },
517
+ (_retry) => {
518
+ },
519
+ onmessage
520
+ )
521
+ )
522
+ );
523
+ onclose?.();
524
+ dispose();
525
+ resolve();
526
+ } catch (err) {
527
+ }
528
+ }
529
+ create();
530
+ });
531
+ }
532
+ function defaultOnOpen(response) {
533
+ const contentType = response.headers?.get("content-type");
534
+ if (!contentType?.startsWith(EventStreamContentType)) {
535
+ throw new Error(`Expected content-type to be ${EventStreamContentType}, Actual: ${contentType}`);
536
+ }
537
+ }
538
+
539
+ const VERSION = "0.26.5";
540
+
541
+ var __defProp$7 = Object.defineProperty;
542
+ var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
543
+ var __publicField$7 = (obj, key, value) => {
544
+ __defNormalProp$7(obj, typeof key !== "symbol" ? key + "" : key, value);
545
+ return value;
546
+ };
547
+ class ErrorWithCause extends Error {
548
+ constructor(message, options) {
549
+ super(message, options);
550
+ __publicField$7(this, "cause");
551
+ }
552
+ }
553
+ class FetcherError extends ErrorWithCause {
554
+ constructor(status, data, requestId) {
555
+ super(getMessage(data));
556
+ __publicField$7(this, "status");
557
+ __publicField$7(this, "requestId");
558
+ __publicField$7(this, "errors");
559
+ this.status = status;
560
+ this.errors = isBulkError(data) ? data.errors : [{ message: getMessage(data), status }];
561
+ this.requestId = requestId;
562
+ if (data instanceof Error) {
563
+ this.stack = data.stack;
564
+ this.cause = data.cause;
565
+ }
566
+ }
567
+ toString() {
568
+ const error = super.toString();
569
+ return `[${this.status}] (${this.requestId ?? "Unknown"}): ${error}`;
570
+ }
571
+ }
572
+ function isBulkError(error) {
573
+ return isObject(error) && Array.isArray(error.errors);
574
+ }
575
+ function isErrorWithMessage(error) {
576
+ return isObject(error) && isString(error.message);
577
+ }
578
+ function getMessage(data) {
579
+ if (data instanceof Error) {
580
+ return data.message;
581
+ } else if (isString(data)) {
582
+ return data;
583
+ } else if (isErrorWithMessage(data)) {
584
+ return data.message;
585
+ } else if (isBulkError(data)) {
586
+ return "Bulk operation failed";
587
+ } else {
588
+ return "Unexpected error";
589
+ }
590
+ }
591
+
592
+ const pool = new ApiRequestPool();
593
+ const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
594
+ const cleanQueryParams = Object.entries(queryParams).reduce((acc, [key, value]) => {
595
+ if (value === void 0 || value === null)
596
+ return acc;
597
+ return { ...acc, [key]: value };
598
+ }, {});
599
+ const query = new URLSearchParams(cleanQueryParams).toString();
600
+ const queryString = query.length > 0 ? `?${query}` : "";
601
+ const cleanPathParams = Object.entries(pathParams).reduce((acc, [key, value]) => {
602
+ return { ...acc, [key]: encodeURIComponent(String(value ?? "")).replace("%3A", ":") };
603
+ }, {});
604
+ return url.replace(/\{\w*\}/g, (key) => cleanPathParams[key.slice(1, -1)]) + queryString;
605
+ };
606
+ function buildBaseUrl({
607
+ endpoint,
608
+ path,
609
+ workspacesApiUrl,
610
+ apiUrl,
611
+ pathParams = {}
612
+ }) {
613
+ if (endpoint === "dataPlane") {
614
+ const url = isString(workspacesApiUrl) ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
615
+ const urlWithWorkspace = isString(pathParams.workspace) ? url.replace("{workspaceId}", String(pathParams.workspace)) : url;
616
+ return isString(pathParams.region) ? urlWithWorkspace.replace("{region}", String(pathParams.region)) : urlWithWorkspace;
617
+ }
618
+ return `${apiUrl}${path}`;
619
+ }
620
+ function hostHeader(url) {
621
+ const pattern = /.*:\/\/(?<host>[^/]+).*/;
622
+ const { groups } = pattern.exec(url) ?? {};
623
+ return groups?.host ? { Host: groups.host } : {};
624
+ }
625
+ async function parseBody(body, headers) {
626
+ if (!isDefined(body))
627
+ return void 0;
628
+ if (isBlob(body) || typeof body.text === "function") {
629
+ return body;
630
+ }
631
+ const { "Content-Type": contentType } = headers ?? {};
632
+ if (String(contentType).toLowerCase() === "application/json" && isObject(body)) {
633
+ return JSON.stringify(body);
634
+ }
635
+ return body;
636
+ }
637
+ const defaultClientID = generateUUID();
638
+ async function fetch$1({
639
+ url: path,
640
+ method,
641
+ body,
642
+ headers: customHeaders,
643
+ pathParams,
644
+ queryParams,
645
+ fetch: fetch2,
646
+ apiKey,
647
+ endpoint,
648
+ apiUrl,
649
+ workspacesApiUrl,
650
+ trace,
651
+ signal,
652
+ clientID,
653
+ sessionID,
654
+ clientName,
655
+ xataAgentExtra,
656
+ fetchOptions = {},
657
+ rawResponse = false
658
+ }) {
659
+ pool.setFetch(fetch2);
660
+ return await trace(
661
+ `${method.toUpperCase()} ${path}`,
662
+ async ({ setAttributes }) => {
663
+ const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
664
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
665
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
666
+ setAttributes({
667
+ [TraceAttributes.HTTP_URL]: url,
668
+ [TraceAttributes.HTTP_TARGET]: resolveUrl(path, queryParams, pathParams)
669
+ });
670
+ const xataAgent = compact([
671
+ ["client", "TS_SDK"],
672
+ ["version", VERSION],
673
+ isDefined(clientName) ? ["service", clientName] : void 0,
674
+ ...Object.entries(xataAgentExtra ?? {})
675
+ ]).map(([key, value]) => `${key}=${value}`).join("; ");
676
+ const headers = compactObject({
677
+ "Accept-Encoding": "identity",
678
+ "Content-Type": "application/json",
679
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
680
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
681
+ "X-Xata-Agent": xataAgent,
682
+ ...customHeaders,
683
+ ...hostHeader(fullUrl),
684
+ Authorization: `Bearer ${apiKey}`
685
+ });
686
+ const response = await pool.request(url, {
687
+ ...fetchOptions,
688
+ method: method.toUpperCase(),
689
+ body: await parseBody(body, headers),
690
+ headers,
691
+ signal
692
+ });
693
+ const { host, protocol } = parseUrl(response.url);
694
+ const requestId = response.headers?.get("x-request-id") ?? void 0;
695
+ setAttributes({
696
+ [TraceAttributes.KIND]: "http",
697
+ [TraceAttributes.HTTP_REQUEST_ID]: requestId,
698
+ [TraceAttributes.HTTP_STATUS_CODE]: response.status,
699
+ [TraceAttributes.HTTP_HOST]: host,
700
+ [TraceAttributes.HTTP_SCHEME]: protocol?.replace(":", ""),
701
+ [TraceAttributes.CLOUDFLARE_RAY_ID]: response.headers?.get("cf-ray") ?? void 0
702
+ });
703
+ const message = response.headers?.get("x-xata-message");
704
+ if (message)
705
+ console.warn(message);
706
+ if (response.status === 204) {
707
+ return {};
708
+ }
709
+ if (response.status === 429) {
710
+ throw new FetcherError(response.status, "Rate limit exceeded", requestId);
711
+ }
712
+ try {
713
+ const jsonResponse = rawResponse ? await response.blob() : await response.json();
714
+ if (response.ok) {
715
+ return jsonResponse;
716
+ }
717
+ throw new FetcherError(response.status, jsonResponse, requestId);
718
+ } catch (error) {
719
+ throw new FetcherError(response.status, error, requestId);
720
+ }
721
+ },
722
+ { [TraceAttributes.HTTP_METHOD]: method.toUpperCase(), [TraceAttributes.HTTP_ROUTE]: path }
723
+ );
724
+ }
725
+ function fetchSSERequest({
726
+ url: path,
727
+ method,
728
+ body,
729
+ headers: customHeaders,
730
+ pathParams,
731
+ queryParams,
732
+ fetch: fetch2,
733
+ apiKey,
734
+ endpoint,
735
+ apiUrl,
736
+ workspacesApiUrl,
737
+ onMessage,
738
+ onError,
739
+ onClose,
740
+ signal,
741
+ clientID,
742
+ sessionID,
743
+ clientName,
744
+ xataAgentExtra
745
+ }) {
746
+ const baseUrl = buildBaseUrl({ endpoint, path, workspacesApiUrl, pathParams, apiUrl });
747
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
748
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
749
+ void fetchEventSource(url, {
750
+ method,
751
+ body: JSON.stringify(body),
752
+ fetch: fetch2,
753
+ signal,
754
+ headers: {
755
+ "X-Xata-Client-ID": clientID ?? defaultClientID,
756
+ "X-Xata-Session-ID": sessionID ?? generateUUID(),
757
+ "X-Xata-Agent": compact([
758
+ ["client", "TS_SDK"],
759
+ ["version", VERSION],
760
+ isDefined(clientName) ? ["service", clientName] : void 0,
761
+ ...Object.entries(xataAgentExtra ?? {})
762
+ ]).map(([key, value]) => `${key}=${value}`).join("; "),
763
+ ...customHeaders,
764
+ Authorization: `Bearer ${apiKey}`,
765
+ "Content-Type": "application/json"
766
+ },
767
+ onmessage(ev) {
768
+ onMessage?.(JSON.parse(ev.data));
769
+ },
770
+ onerror(ev) {
771
+ onError?.(JSON.parse(ev.data));
772
+ },
773
+ onclose() {
774
+ onClose?.();
775
+ }
776
+ });
777
+ }
778
+ function parseUrl(url) {
779
+ try {
780
+ const { host, protocol } = new URL(url);
781
+ return { host, protocol };
782
+ } catch (error) {
783
+ return {};
784
+ }
785
+ }
786
+
787
+ const dataPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "dataPlane" });
788
+
789
+ const getBranchList = (variables, signal) => dataPlaneFetch({
790
+ url: "/dbs/{dbName}",
791
+ method: "get",
792
+ ...variables,
793
+ signal
794
+ });
795
+ const getBranchDetails = (variables, signal) => dataPlaneFetch({
796
+ url: "/db/{dbBranchName}",
797
+ method: "get",
798
+ ...variables,
799
+ signal
800
+ });
801
+ const createBranch = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}", method: "put", ...variables, signal });
802
+ const deleteBranch = (variables, signal) => dataPlaneFetch({
803
+ url: "/db/{dbBranchName}",
804
+ method: "delete",
805
+ ...variables,
806
+ signal
807
+ });
808
+ const copyBranch = (variables, signal) => dataPlaneFetch({
809
+ url: "/db/{dbBranchName}/copy",
810
+ method: "post",
811
+ ...variables,
812
+ signal
813
+ });
814
+ const updateBranchMetadata = (variables, signal) => dataPlaneFetch({
815
+ url: "/db/{dbBranchName}/metadata",
816
+ method: "put",
817
+ ...variables,
818
+ signal
819
+ });
820
+ const getBranchMetadata = (variables, signal) => dataPlaneFetch({
821
+ url: "/db/{dbBranchName}/metadata",
822
+ method: "get",
823
+ ...variables,
824
+ signal
825
+ });
826
+ const getBranchStats = (variables, signal) => dataPlaneFetch({
827
+ url: "/db/{dbBranchName}/stats",
828
+ method: "get",
829
+ ...variables,
830
+ signal
831
+ });
832
+ const getGitBranchesMapping = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables, signal });
833
+ const addGitBranchesEntry = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables, signal });
834
+ const removeGitBranchesEntry = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables, signal });
835
+ const resolveBranch = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/resolveBranch", method: "get", ...variables, signal });
836
+ const getBranchMigrationHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables, signal });
837
+ const getBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables, signal });
838
+ const executeBranchMigrationPlan = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables, signal });
839
+ const queryMigrationRequests = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/query", method: "post", ...variables, signal });
840
+ const createMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations", method: "post", ...variables, signal });
841
+ const getMigrationRequest = (variables, signal) => dataPlaneFetch({
842
+ url: "/dbs/{dbName}/migrations/{mrNumber}",
843
+ method: "get",
844
+ ...variables,
845
+ signal
846
+ });
847
+ const updateMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/{mrNumber}", method: "patch", ...variables, signal });
848
+ const listMigrationRequestsCommits = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/{mrNumber}/commits", method: "post", ...variables, signal });
849
+ const compareMigrationRequest = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/{mrNumber}/compare", method: "post", ...variables, signal });
850
+ const getMigrationRequestIsMerged = (variables, signal) => dataPlaneFetch({ url: "/dbs/{dbName}/migrations/{mrNumber}/merge", method: "get", ...variables, signal });
851
+ const mergeMigrationRequest = (variables, signal) => dataPlaneFetch({
852
+ url: "/dbs/{dbName}/migrations/{mrNumber}/merge",
853
+ method: "post",
854
+ ...variables,
855
+ signal
856
+ });
857
+ const getBranchSchemaHistory = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/history", method: "post", ...variables, signal });
858
+ const compareBranchWithUserSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/compare", method: "post", ...variables, signal });
859
+ const compareBranchSchemas = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/compare/{branchName}", method: "post", ...variables, signal });
860
+ const updateBranchSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/update", method: "post", ...variables, signal });
861
+ const previewBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/preview", method: "post", ...variables, signal });
862
+ const applyBranchSchemaEdit = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/apply", method: "post", ...variables, signal });
863
+ const pushBranchMigrations = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/schema/push", method: "post", ...variables, signal });
864
+ const createTable = (variables, signal) => dataPlaneFetch({
865
+ url: "/db/{dbBranchName}/tables/{tableName}",
866
+ method: "put",
867
+ ...variables,
868
+ signal
869
+ });
870
+ const deleteTable = (variables, signal) => dataPlaneFetch({
871
+ url: "/db/{dbBranchName}/tables/{tableName}",
872
+ method: "delete",
873
+ ...variables,
874
+ signal
875
+ });
876
+ const updateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}", method: "patch", ...variables, signal });
877
+ const getTableSchema = (variables, signal) => dataPlaneFetch({
878
+ url: "/db/{dbBranchName}/tables/{tableName}/schema",
879
+ method: "get",
880
+ ...variables,
881
+ signal
882
+ });
883
+ const setTableSchema = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/schema", method: "put", ...variables, signal });
884
+ const getTableColumns = (variables, signal) => dataPlaneFetch({
885
+ url: "/db/{dbBranchName}/tables/{tableName}/columns",
886
+ method: "get",
887
+ ...variables,
888
+ signal
889
+ });
890
+ const addTableColumn = (variables, signal) => dataPlaneFetch(
891
+ { url: "/db/{dbBranchName}/tables/{tableName}/columns", method: "post", ...variables, signal }
892
+ );
893
+ const getColumn = (variables, signal) => dataPlaneFetch({
894
+ url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
895
+ method: "get",
896
+ ...variables,
897
+ signal
898
+ });
899
+ const updateColumn = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}", method: "patch", ...variables, signal });
900
+ const deleteColumn = (variables, signal) => dataPlaneFetch({
901
+ url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
902
+ method: "delete",
903
+ ...variables,
904
+ signal
905
+ });
906
+ const branchTransaction = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/transaction", method: "post", ...variables, signal });
907
+ const insertRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables, signal });
908
+ const getFileItem = (variables, signal) => dataPlaneFetch({
909
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
910
+ method: "get",
911
+ ...variables,
912
+ signal
913
+ });
914
+ const putFileItem = (variables, signal) => dataPlaneFetch({
915
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
916
+ method: "put",
917
+ ...variables,
918
+ signal
919
+ });
920
+ const deleteFileItem = (variables, signal) => dataPlaneFetch({
921
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file/{fileId}",
922
+ method: "delete",
923
+ ...variables,
924
+ signal
925
+ });
926
+ const getFile = (variables, signal) => dataPlaneFetch({
927
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
928
+ method: "get",
929
+ ...variables,
930
+ signal
931
+ });
932
+ const putFile = (variables, signal) => dataPlaneFetch({
933
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
934
+ method: "put",
935
+ ...variables,
936
+ signal
937
+ });
938
+ const deleteFile = (variables, signal) => dataPlaneFetch({
939
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}/column/{columnName}/file",
940
+ method: "delete",
941
+ ...variables,
942
+ signal
943
+ });
944
+ const getRecord = (variables, signal) => dataPlaneFetch({
945
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
946
+ method: "get",
947
+ ...variables,
948
+ signal
949
+ });
950
+ const insertRecordWithID = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables, signal });
951
+ const updateRecordWithID = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables, signal });
952
+ const upsertRecordWithID = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables, signal });
953
+ const deleteRecord = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "delete", ...variables, signal });
954
+ const bulkInsertTableRecords = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/bulk", method: "post", ...variables, signal });
955
+ const queryTable = (variables, signal) => dataPlaneFetch({
956
+ url: "/db/{dbBranchName}/tables/{tableName}/query",
957
+ method: "post",
958
+ ...variables,
959
+ signal
960
+ });
961
+ const searchBranch = (variables, signal) => dataPlaneFetch({
962
+ url: "/db/{dbBranchName}/search",
963
+ method: "post",
964
+ ...variables,
965
+ signal
966
+ });
967
+ const searchTable = (variables, signal) => dataPlaneFetch({
968
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
969
+ method: "post",
970
+ ...variables,
971
+ signal
972
+ });
973
+ const vectorSearchTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/vectorSearch", method: "post", ...variables, signal });
974
+ const askTable = (variables, signal) => dataPlaneFetch({
975
+ url: "/db/{dbBranchName}/tables/{tableName}/ask",
976
+ method: "post",
977
+ ...variables,
978
+ signal
979
+ });
980
+ const askTableSession = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}", method: "post", ...variables, signal });
981
+ const summarizeTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/summarize", method: "post", ...variables, signal });
982
+ const aggregateTable = (variables, signal) => dataPlaneFetch({ url: "/db/{dbBranchName}/tables/{tableName}/aggregate", method: "post", ...variables, signal });
983
+ const fileAccess = (variables, signal) => dataPlaneFetch({
984
+ url: "/file/{fileId}",
985
+ method: "get",
986
+ ...variables,
987
+ signal
988
+ });
989
+ const sqlQuery = (variables, signal) => dataPlaneFetch({
990
+ url: "/db/{dbBranchName}/sql",
991
+ method: "post",
992
+ ...variables,
993
+ signal
994
+ });
995
+ const operationsByTag$2 = {
996
+ branch: {
997
+ getBranchList,
998
+ getBranchDetails,
999
+ createBranch,
1000
+ deleteBranch,
1001
+ copyBranch,
1002
+ updateBranchMetadata,
1003
+ getBranchMetadata,
1004
+ getBranchStats,
1005
+ getGitBranchesMapping,
1006
+ addGitBranchesEntry,
1007
+ removeGitBranchesEntry,
1008
+ resolveBranch
1009
+ },
1010
+ migrations: {
1011
+ getBranchMigrationHistory,
1012
+ getBranchMigrationPlan,
1013
+ executeBranchMigrationPlan,
1014
+ getBranchSchemaHistory,
1015
+ compareBranchWithUserSchema,
1016
+ compareBranchSchemas,
1017
+ updateBranchSchema,
1018
+ previewBranchSchemaEdit,
1019
+ applyBranchSchemaEdit,
1020
+ pushBranchMigrations
1021
+ },
1022
+ migrationRequests: {
1023
+ queryMigrationRequests,
1024
+ createMigrationRequest,
1025
+ getMigrationRequest,
1026
+ updateMigrationRequest,
1027
+ listMigrationRequestsCommits,
1028
+ compareMigrationRequest,
1029
+ getMigrationRequestIsMerged,
1030
+ mergeMigrationRequest
1031
+ },
1032
+ table: {
1033
+ createTable,
1034
+ deleteTable,
1035
+ updateTable,
1036
+ getTableSchema,
1037
+ setTableSchema,
1038
+ getTableColumns,
1039
+ addTableColumn,
1040
+ getColumn,
1041
+ updateColumn,
1042
+ deleteColumn
1043
+ },
1044
+ records: {
1045
+ branchTransaction,
1046
+ insertRecord,
1047
+ getRecord,
1048
+ insertRecordWithID,
1049
+ updateRecordWithID,
1050
+ upsertRecordWithID,
1051
+ deleteRecord,
1052
+ bulkInsertTableRecords
1053
+ },
1054
+ files: { getFileItem, putFileItem, deleteFileItem, getFile, putFile, deleteFile, fileAccess },
1055
+ searchAndFilter: {
1056
+ queryTable,
1057
+ searchBranch,
1058
+ searchTable,
1059
+ vectorSearchTable,
1060
+ askTable,
1061
+ askTableSession,
1062
+ summarizeTable,
1063
+ aggregateTable
1064
+ },
1065
+ sql: { sqlQuery }
1066
+ };
1067
+
1068
+ const controlPlaneFetch = async (options) => fetch$1({ ...options, endpoint: "controlPlane" });
1069
+
1070
+ const getAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "get", ...variables, signal });
1071
+ const grantAuthorizationCode = (variables, signal) => controlPlaneFetch({ url: "/oauth/authorize", method: "post", ...variables, signal });
1072
+ const getUser = (variables, signal) => controlPlaneFetch({
1073
+ url: "/user",
1074
+ method: "get",
1075
+ ...variables,
1076
+ signal
1077
+ });
1078
+ const updateUser = (variables, signal) => controlPlaneFetch({
1079
+ url: "/user",
1080
+ method: "put",
1081
+ ...variables,
1082
+ signal
1083
+ });
1084
+ const deleteUser = (variables, signal) => controlPlaneFetch({
1085
+ url: "/user",
1086
+ method: "delete",
1087
+ ...variables,
1088
+ signal
1089
+ });
1090
+ const getUserAPIKeys = (variables, signal) => controlPlaneFetch({
1091
+ url: "/user/keys",
1092
+ method: "get",
1093
+ ...variables,
1094
+ signal
1095
+ });
1096
+ const createUserAPIKey = (variables, signal) => controlPlaneFetch({
1097
+ url: "/user/keys/{keyName}",
1098
+ method: "post",
1099
+ ...variables,
1100
+ signal
1101
+ });
1102
+ const deleteUserAPIKey = (variables, signal) => controlPlaneFetch({
1103
+ url: "/user/keys/{keyName}",
1104
+ method: "delete",
1105
+ ...variables,
1106
+ signal
1107
+ });
1108
+ const getUserOAuthClients = (variables, signal) => controlPlaneFetch({
1109
+ url: "/user/oauth/clients",
1110
+ method: "get",
1111
+ ...variables,
1112
+ signal
1113
+ });
1114
+ const deleteUserOAuthClient = (variables, signal) => controlPlaneFetch({
1115
+ url: "/user/oauth/clients/{clientId}",
1116
+ method: "delete",
1117
+ ...variables,
1118
+ signal
1119
+ });
1120
+ const getUserOAuthAccessTokens = (variables, signal) => controlPlaneFetch({
1121
+ url: "/user/oauth/tokens",
1122
+ method: "get",
1123
+ ...variables,
1124
+ signal
1125
+ });
1126
+ const deleteOAuthAccessToken = (variables, signal) => controlPlaneFetch({
1127
+ url: "/user/oauth/tokens/{token}",
1128
+ method: "delete",
1129
+ ...variables,
1130
+ signal
1131
+ });
1132
+ const updateOAuthAccessToken = (variables, signal) => controlPlaneFetch({ url: "/user/oauth/tokens/{token}", method: "patch", ...variables, signal });
1133
+ const getWorkspacesList = (variables, signal) => controlPlaneFetch({
1134
+ url: "/workspaces",
1135
+ method: "get",
1136
+ ...variables,
1137
+ signal
1138
+ });
1139
+ const createWorkspace = (variables, signal) => controlPlaneFetch({
1140
+ url: "/workspaces",
1141
+ method: "post",
1142
+ ...variables,
1143
+ signal
1144
+ });
1145
+ const getWorkspace = (variables, signal) => controlPlaneFetch({
1146
+ url: "/workspaces/{workspaceId}",
1147
+ method: "get",
1148
+ ...variables,
1149
+ signal
1150
+ });
1151
+ const updateWorkspace = (variables, signal) => controlPlaneFetch({
1152
+ url: "/workspaces/{workspaceId}",
1153
+ method: "put",
1154
+ ...variables,
1155
+ signal
1156
+ });
1157
+ const deleteWorkspace = (variables, signal) => controlPlaneFetch({
1158
+ url: "/workspaces/{workspaceId}",
1159
+ method: "delete",
1160
+ ...variables,
1161
+ signal
1162
+ });
1163
+ const getWorkspaceMembersList = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/members", method: "get", ...variables, signal });
1164
+ const updateWorkspaceMemberRole = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/members/{userId}", method: "put", ...variables, signal });
1165
+ const removeWorkspaceMember = (variables, signal) => controlPlaneFetch({
1166
+ url: "/workspaces/{workspaceId}/members/{userId}",
1167
+ method: "delete",
1168
+ ...variables,
1169
+ signal
1170
+ });
1171
+ const inviteWorkspaceMember = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables, signal });
1172
+ const updateWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "patch", ...variables, signal });
1173
+ const cancelWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}", method: "delete", ...variables, signal });
1174
+ const acceptWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept", method: "post", ...variables, signal });
1175
+ const resendWorkspaceMemberInvite = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/invites/{inviteId}/resend", method: "post", ...variables, signal });
1176
+ const getDatabaseList = (variables, signal) => controlPlaneFetch({
1177
+ url: "/workspaces/{workspaceId}/dbs",
1178
+ method: "get",
1179
+ ...variables,
1180
+ signal
1181
+ });
1182
+ const createDatabase = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "put", ...variables, signal });
1183
+ const deleteDatabase = (variables, signal) => controlPlaneFetch({
1184
+ url: "/workspaces/{workspaceId}/dbs/{dbName}",
1185
+ method: "delete",
1186
+ ...variables,
1187
+ signal
1188
+ });
1189
+ const getDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "get", ...variables, signal });
1190
+ const updateDatabaseMetadata = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}", method: "patch", ...variables, signal });
1191
+ const renameDatabase = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/rename", method: "post", ...variables, signal });
1192
+ const getDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "get", ...variables, signal });
1193
+ const updateDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "put", ...variables, signal });
1194
+ const deleteDatabaseGithubSettings = (variables, signal) => controlPlaneFetch({ url: "/workspaces/{workspaceId}/dbs/{dbName}/github", method: "delete", ...variables, signal });
1195
+ const listRegions = (variables, signal) => controlPlaneFetch({
1196
+ url: "/workspaces/{workspaceId}/regions",
1197
+ method: "get",
1198
+ ...variables,
1199
+ signal
1200
+ });
1201
+ const operationsByTag$1 = {
1202
+ oAuth: {
1203
+ getAuthorizationCode,
1204
+ grantAuthorizationCode,
1205
+ getUserOAuthClients,
1206
+ deleteUserOAuthClient,
1207
+ getUserOAuthAccessTokens,
1208
+ deleteOAuthAccessToken,
1209
+ updateOAuthAccessToken
1210
+ },
1211
+ users: { getUser, updateUser, deleteUser },
1212
+ authentication: { getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
1213
+ workspaces: {
1214
+ getWorkspacesList,
1215
+ createWorkspace,
1216
+ getWorkspace,
1217
+ updateWorkspace,
1218
+ deleteWorkspace,
1219
+ getWorkspaceMembersList,
1220
+ updateWorkspaceMemberRole,
1221
+ removeWorkspaceMember
1222
+ },
1223
+ invites: {
1224
+ inviteWorkspaceMember,
1225
+ updateWorkspaceMemberInvite,
1226
+ cancelWorkspaceMemberInvite,
1227
+ acceptWorkspaceMemberInvite,
1228
+ resendWorkspaceMemberInvite
1229
+ },
1230
+ databases: {
1231
+ getDatabaseList,
1232
+ createDatabase,
1233
+ deleteDatabase,
1234
+ getDatabaseMetadata,
1235
+ updateDatabaseMetadata,
1236
+ renameDatabase,
1237
+ getDatabaseGithubSettings,
1238
+ updateDatabaseGithubSettings,
1239
+ deleteDatabaseGithubSettings,
1240
+ listRegions
1241
+ }
1242
+ };
1243
+
1244
+ const operationsByTag = deepMerge(operationsByTag$2, operationsByTag$1);
1245
+
1246
+ function getHostUrl(provider, type) {
1247
+ if (isHostProviderAlias(provider)) {
1248
+ return providers[provider][type];
1249
+ } else if (isHostProviderBuilder(provider)) {
1250
+ return provider[type];
1251
+ }
1252
+ throw new Error("Invalid API provider");
1253
+ }
1254
+ const providers = {
1255
+ production: {
1256
+ main: "https://api.xata.io",
1257
+ workspaces: "https://{workspaceId}.{region}.xata.sh"
1258
+ },
1259
+ staging: {
1260
+ main: "https://api.staging-xata.dev",
1261
+ workspaces: "https://{workspaceId}.{region}.staging-xata.dev"
1262
+ },
1263
+ dev: {
1264
+ main: "https://api.dev-xata.dev",
1265
+ workspaces: "https://{workspaceId}.{region}.dev-xata.dev"
1266
+ }
1267
+ };
1268
+ function isHostProviderAlias(alias) {
1269
+ return isString(alias) && Object.keys(providers).includes(alias);
1270
+ }
1271
+ function isHostProviderBuilder(builder) {
1272
+ return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
1273
+ }
1274
+ function parseProviderString(provider = "production") {
1275
+ if (isHostProviderAlias(provider)) {
1276
+ return provider;
1277
+ }
1278
+ const [main, workspaces] = provider.split(",");
1279
+ if (!main || !workspaces)
1280
+ return null;
1281
+ return { main, workspaces };
1282
+ }
1283
+ function buildProviderString(provider) {
1284
+ if (isHostProviderAlias(provider))
1285
+ return provider;
1286
+ return `${provider.main},${provider.workspaces}`;
1287
+ }
1288
+ function parseWorkspacesUrlParts(url) {
1289
+ if (!isString(url))
1290
+ return null;
1291
+ const regex = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.sh.*/;
1292
+ const regexDev = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.dev-xata\.dev.*/;
1293
+ const regexStaging = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.staging-xata\.dev.*/;
1294
+ const regexProdTesting = /(?:https:\/\/)?([^.]+)(?:\.([^.]+))\.xata\.tech.*/;
1295
+ const match = url.match(regex) || url.match(regexDev) || url.match(regexStaging) || url.match(regexProdTesting);
1296
+ if (!match)
1297
+ return null;
1298
+ return { workspace: match[1], region: match[2] };
1299
+ }
1300
+
1301
+ var __accessCheck$7 = (obj, member, msg) => {
1302
+ if (!member.has(obj))
1303
+ throw TypeError("Cannot " + msg);
1304
+ };
1305
+ var __privateGet$7 = (obj, member, getter) => {
1306
+ __accessCheck$7(obj, member, "read from private field");
1307
+ return getter ? getter.call(obj) : member.get(obj);
1308
+ };
1309
+ var __privateAdd$7 = (obj, member, value) => {
1310
+ if (member.has(obj))
1311
+ throw TypeError("Cannot add the same private member more than once");
1312
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1313
+ };
1314
+ var __privateSet$7 = (obj, member, value, setter) => {
1315
+ __accessCheck$7(obj, member, "write to private field");
1316
+ setter ? setter.call(obj, value) : member.set(obj, value);
1317
+ return value;
1318
+ };
1319
+ var _extraProps, _namespaces;
1320
+ class XataApiClient {
1321
+ constructor(options = {}) {
1322
+ __privateAdd$7(this, _extraProps, void 0);
1323
+ __privateAdd$7(this, _namespaces, {});
1324
+ const provider = options.host ?? "production";
1325
+ const apiKey = options.apiKey ?? getAPIKey();
1326
+ const trace = options.trace ?? defaultTrace;
1327
+ const clientID = generateUUID();
1328
+ if (!apiKey) {
1329
+ throw new Error("Could not resolve a valid apiKey");
1330
+ }
1331
+ __privateSet$7(this, _extraProps, {
1332
+ apiUrl: getHostUrl(provider, "main"),
1333
+ workspacesApiUrl: getHostUrl(provider, "workspaces"),
1334
+ fetch: getFetchImplementation(options.fetch),
1335
+ apiKey,
1336
+ trace,
1337
+ clientName: options.clientName,
1338
+ xataAgentExtra: options.xataAgentExtra,
1339
+ clientID
1340
+ });
1341
+ }
1342
+ get user() {
1343
+ if (!__privateGet$7(this, _namespaces).user)
1344
+ __privateGet$7(this, _namespaces).user = new UserApi(__privateGet$7(this, _extraProps));
1345
+ return __privateGet$7(this, _namespaces).user;
1346
+ }
1347
+ get authentication() {
1348
+ if (!__privateGet$7(this, _namespaces).authentication)
1349
+ __privateGet$7(this, _namespaces).authentication = new AuthenticationApi(__privateGet$7(this, _extraProps));
1350
+ return __privateGet$7(this, _namespaces).authentication;
1351
+ }
1352
+ get workspaces() {
1353
+ if (!__privateGet$7(this, _namespaces).workspaces)
1354
+ __privateGet$7(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$7(this, _extraProps));
1355
+ return __privateGet$7(this, _namespaces).workspaces;
1356
+ }
1357
+ get invites() {
1358
+ if (!__privateGet$7(this, _namespaces).invites)
1359
+ __privateGet$7(this, _namespaces).invites = new InvitesApi(__privateGet$7(this, _extraProps));
1360
+ return __privateGet$7(this, _namespaces).invites;
1361
+ }
1362
+ get database() {
1363
+ if (!__privateGet$7(this, _namespaces).database)
1364
+ __privateGet$7(this, _namespaces).database = new DatabaseApi(__privateGet$7(this, _extraProps));
1365
+ return __privateGet$7(this, _namespaces).database;
1366
+ }
1367
+ get branches() {
1368
+ if (!__privateGet$7(this, _namespaces).branches)
1369
+ __privateGet$7(this, _namespaces).branches = new BranchApi(__privateGet$7(this, _extraProps));
1370
+ return __privateGet$7(this, _namespaces).branches;
1371
+ }
1372
+ get migrations() {
1373
+ if (!__privateGet$7(this, _namespaces).migrations)
1374
+ __privateGet$7(this, _namespaces).migrations = new MigrationsApi(__privateGet$7(this, _extraProps));
1375
+ return __privateGet$7(this, _namespaces).migrations;
1376
+ }
1377
+ get migrationRequests() {
1378
+ if (!__privateGet$7(this, _namespaces).migrationRequests)
1379
+ __privateGet$7(this, _namespaces).migrationRequests = new MigrationRequestsApi(__privateGet$7(this, _extraProps));
1380
+ return __privateGet$7(this, _namespaces).migrationRequests;
1381
+ }
1382
+ get tables() {
1383
+ if (!__privateGet$7(this, _namespaces).tables)
1384
+ __privateGet$7(this, _namespaces).tables = new TableApi(__privateGet$7(this, _extraProps));
1385
+ return __privateGet$7(this, _namespaces).tables;
1386
+ }
1387
+ get records() {
1388
+ if (!__privateGet$7(this, _namespaces).records)
1389
+ __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
1390
+ return __privateGet$7(this, _namespaces).records;
1391
+ }
1392
+ get files() {
1393
+ if (!__privateGet$7(this, _namespaces).files)
1394
+ __privateGet$7(this, _namespaces).files = new FilesApi(__privateGet$7(this, _extraProps));
1395
+ return __privateGet$7(this, _namespaces).files;
1396
+ }
1397
+ get searchAndFilter() {
1398
+ if (!__privateGet$7(this, _namespaces).searchAndFilter)
1399
+ __privateGet$7(this, _namespaces).searchAndFilter = new SearchAndFilterApi(__privateGet$7(this, _extraProps));
1400
+ return __privateGet$7(this, _namespaces).searchAndFilter;
1401
+ }
1402
+ }
1403
+ _extraProps = new WeakMap();
1404
+ _namespaces = new WeakMap();
1405
+ class UserApi {
1406
+ constructor(extraProps) {
1407
+ this.extraProps = extraProps;
1408
+ }
1409
+ getUser() {
1410
+ return operationsByTag.users.getUser({ ...this.extraProps });
1411
+ }
1412
+ updateUser({ user }) {
1413
+ return operationsByTag.users.updateUser({ body: user, ...this.extraProps });
1414
+ }
1415
+ deleteUser() {
1416
+ return operationsByTag.users.deleteUser({ ...this.extraProps });
1417
+ }
1418
+ }
1419
+ class AuthenticationApi {
1420
+ constructor(extraProps) {
1421
+ this.extraProps = extraProps;
1422
+ }
1423
+ getUserAPIKeys() {
1424
+ return operationsByTag.authentication.getUserAPIKeys({ ...this.extraProps });
1425
+ }
1426
+ createUserAPIKey({ name }) {
1427
+ return operationsByTag.authentication.createUserAPIKey({
1428
+ pathParams: { keyName: name },
1429
+ ...this.extraProps
1430
+ });
1431
+ }
1432
+ deleteUserAPIKey({ name }) {
1433
+ return operationsByTag.authentication.deleteUserAPIKey({
1434
+ pathParams: { keyName: name },
1435
+ ...this.extraProps
1436
+ });
1437
+ }
1438
+ }
1439
+ class WorkspaceApi {
1440
+ constructor(extraProps) {
1441
+ this.extraProps = extraProps;
1442
+ }
1443
+ getWorkspacesList() {
1444
+ return operationsByTag.workspaces.getWorkspacesList({ ...this.extraProps });
1445
+ }
1446
+ createWorkspace({ data }) {
1447
+ return operationsByTag.workspaces.createWorkspace({
1448
+ body: data,
1449
+ ...this.extraProps
1450
+ });
1451
+ }
1452
+ getWorkspace({ workspace }) {
1453
+ return operationsByTag.workspaces.getWorkspace({
1454
+ pathParams: { workspaceId: workspace },
1455
+ ...this.extraProps
1456
+ });
1457
+ }
1458
+ updateWorkspace({
1459
+ workspace,
1460
+ update
1461
+ }) {
1462
+ return operationsByTag.workspaces.updateWorkspace({
1463
+ pathParams: { workspaceId: workspace },
1464
+ body: update,
1465
+ ...this.extraProps
1466
+ });
1467
+ }
1468
+ deleteWorkspace({ workspace }) {
1469
+ return operationsByTag.workspaces.deleteWorkspace({
1470
+ pathParams: { workspaceId: workspace },
1471
+ ...this.extraProps
1472
+ });
1473
+ }
1474
+ getWorkspaceMembersList({ workspace }) {
1475
+ return operationsByTag.workspaces.getWorkspaceMembersList({
1476
+ pathParams: { workspaceId: workspace },
1477
+ ...this.extraProps
1478
+ });
1479
+ }
1480
+ updateWorkspaceMemberRole({
1481
+ workspace,
1482
+ user,
1483
+ role
1484
+ }) {
1485
+ return operationsByTag.workspaces.updateWorkspaceMemberRole({
1486
+ pathParams: { workspaceId: workspace, userId: user },
1487
+ body: { role },
1488
+ ...this.extraProps
1489
+ });
1490
+ }
1491
+ removeWorkspaceMember({
1492
+ workspace,
1493
+ user
1494
+ }) {
1495
+ return operationsByTag.workspaces.removeWorkspaceMember({
1496
+ pathParams: { workspaceId: workspace, userId: user },
1497
+ ...this.extraProps
1498
+ });
1499
+ }
1500
+ }
1501
+ class InvitesApi {
1502
+ constructor(extraProps) {
1503
+ this.extraProps = extraProps;
1504
+ }
1505
+ inviteWorkspaceMember({
1506
+ workspace,
1507
+ email,
1508
+ role
1509
+ }) {
1510
+ return operationsByTag.invites.inviteWorkspaceMember({
1511
+ pathParams: { workspaceId: workspace },
1512
+ body: { email, role },
1513
+ ...this.extraProps
1514
+ });
1515
+ }
1516
+ updateWorkspaceMemberInvite({
1517
+ workspace,
1518
+ invite,
1519
+ role
1520
+ }) {
1521
+ return operationsByTag.invites.updateWorkspaceMemberInvite({
1522
+ pathParams: { workspaceId: workspace, inviteId: invite },
1523
+ body: { role },
1524
+ ...this.extraProps
1525
+ });
1526
+ }
1527
+ cancelWorkspaceMemberInvite({
1528
+ workspace,
1529
+ invite
1530
+ }) {
1531
+ return operationsByTag.invites.cancelWorkspaceMemberInvite({
1532
+ pathParams: { workspaceId: workspace, inviteId: invite },
1533
+ ...this.extraProps
1534
+ });
1535
+ }
1536
+ acceptWorkspaceMemberInvite({
1537
+ workspace,
1538
+ key
1539
+ }) {
1540
+ return operationsByTag.invites.acceptWorkspaceMemberInvite({
1541
+ pathParams: { workspaceId: workspace, inviteKey: key },
1542
+ ...this.extraProps
1543
+ });
1544
+ }
1545
+ resendWorkspaceMemberInvite({
1546
+ workspace,
1547
+ invite
1548
+ }) {
1549
+ return operationsByTag.invites.resendWorkspaceMemberInvite({
1550
+ pathParams: { workspaceId: workspace, inviteId: invite },
1551
+ ...this.extraProps
1552
+ });
1553
+ }
1554
+ }
1555
+ class BranchApi {
1556
+ constructor(extraProps) {
1557
+ this.extraProps = extraProps;
1558
+ }
1559
+ getBranchList({
1560
+ workspace,
1561
+ region,
1562
+ database
1563
+ }) {
1564
+ return operationsByTag.branch.getBranchList({
1565
+ pathParams: { workspace, region, dbName: database },
1566
+ ...this.extraProps
1567
+ });
1568
+ }
1569
+ getBranchDetails({
1570
+ workspace,
1571
+ region,
1572
+ database,
1573
+ branch
1574
+ }) {
1575
+ return operationsByTag.branch.getBranchDetails({
1576
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1577
+ ...this.extraProps
1578
+ });
1579
+ }
1580
+ createBranch({
1581
+ workspace,
1582
+ region,
1583
+ database,
1584
+ branch,
1585
+ from,
1586
+ metadata
1587
+ }) {
1588
+ return operationsByTag.branch.createBranch({
1589
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1590
+ body: { from, metadata },
1591
+ ...this.extraProps
1592
+ });
1593
+ }
1594
+ deleteBranch({
1595
+ workspace,
1596
+ region,
1597
+ database,
1598
+ branch
1599
+ }) {
1600
+ return operationsByTag.branch.deleteBranch({
1601
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1602
+ ...this.extraProps
1603
+ });
1604
+ }
1605
+ copyBranch({
1606
+ workspace,
1607
+ region,
1608
+ database,
1609
+ branch,
1610
+ destinationBranch,
1611
+ limit
1612
+ }) {
1613
+ return operationsByTag.branch.copyBranch({
1614
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1615
+ body: { destinationBranch, limit },
1616
+ ...this.extraProps
1617
+ });
1618
+ }
1619
+ updateBranchMetadata({
1620
+ workspace,
1621
+ region,
1622
+ database,
1623
+ branch,
1624
+ metadata
1625
+ }) {
1626
+ return operationsByTag.branch.updateBranchMetadata({
1627
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1628
+ body: metadata,
1629
+ ...this.extraProps
1630
+ });
1631
+ }
1632
+ getBranchMetadata({
1633
+ workspace,
1634
+ region,
1635
+ database,
1636
+ branch
1637
+ }) {
1638
+ return operationsByTag.branch.getBranchMetadata({
1639
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1640
+ ...this.extraProps
1641
+ });
1642
+ }
1643
+ getBranchStats({
1644
+ workspace,
1645
+ region,
1646
+ database,
1647
+ branch
1648
+ }) {
1649
+ return operationsByTag.branch.getBranchStats({
1650
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1651
+ ...this.extraProps
1652
+ });
1653
+ }
1654
+ getGitBranchesMapping({
1655
+ workspace,
1656
+ region,
1657
+ database
1658
+ }) {
1659
+ return operationsByTag.branch.getGitBranchesMapping({
1660
+ pathParams: { workspace, region, dbName: database },
1661
+ ...this.extraProps
1662
+ });
1663
+ }
1664
+ addGitBranchesEntry({
1665
+ workspace,
1666
+ region,
1667
+ database,
1668
+ gitBranch,
1669
+ xataBranch
1670
+ }) {
1671
+ return operationsByTag.branch.addGitBranchesEntry({
1672
+ pathParams: { workspace, region, dbName: database },
1673
+ body: { gitBranch, xataBranch },
1674
+ ...this.extraProps
1675
+ });
1676
+ }
1677
+ removeGitBranchesEntry({
1678
+ workspace,
1679
+ region,
1680
+ database,
1681
+ gitBranch
1682
+ }) {
1683
+ return operationsByTag.branch.removeGitBranchesEntry({
1684
+ pathParams: { workspace, region, dbName: database },
1685
+ queryParams: { gitBranch },
1686
+ ...this.extraProps
1687
+ });
1688
+ }
1689
+ resolveBranch({
1690
+ workspace,
1691
+ region,
1692
+ database,
1693
+ gitBranch,
1694
+ fallbackBranch
1695
+ }) {
1696
+ return operationsByTag.branch.resolveBranch({
1697
+ pathParams: { workspace, region, dbName: database },
1698
+ queryParams: { gitBranch, fallbackBranch },
1699
+ ...this.extraProps
1700
+ });
1701
+ }
1702
+ }
1703
+ class TableApi {
1704
+ constructor(extraProps) {
1705
+ this.extraProps = extraProps;
1706
+ }
1707
+ createTable({
1708
+ workspace,
1709
+ region,
1710
+ database,
1711
+ branch,
1712
+ table
1713
+ }) {
1714
+ return operationsByTag.table.createTable({
1715
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1716
+ ...this.extraProps
1717
+ });
1718
+ }
1719
+ deleteTable({
1720
+ workspace,
1721
+ region,
1722
+ database,
1723
+ branch,
1724
+ table
1725
+ }) {
1726
+ return operationsByTag.table.deleteTable({
1727
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1728
+ ...this.extraProps
1729
+ });
1730
+ }
1731
+ updateTable({
1732
+ workspace,
1733
+ region,
1734
+ database,
1735
+ branch,
1736
+ table,
1737
+ update
1738
+ }) {
1739
+ return operationsByTag.table.updateTable({
1740
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1741
+ body: update,
1742
+ ...this.extraProps
1743
+ });
1744
+ }
1745
+ getTableSchema({
1746
+ workspace,
1747
+ region,
1748
+ database,
1749
+ branch,
1750
+ table
1751
+ }) {
1752
+ return operationsByTag.table.getTableSchema({
1753
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1754
+ ...this.extraProps
1755
+ });
1756
+ }
1757
+ setTableSchema({
1758
+ workspace,
1759
+ region,
1760
+ database,
1761
+ branch,
1762
+ table,
1763
+ schema
1764
+ }) {
1765
+ return operationsByTag.table.setTableSchema({
1766
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1767
+ body: schema,
1768
+ ...this.extraProps
1769
+ });
1770
+ }
1771
+ getTableColumns({
1772
+ workspace,
1773
+ region,
1774
+ database,
1775
+ branch,
1776
+ table
1777
+ }) {
1778
+ return operationsByTag.table.getTableColumns({
1779
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1780
+ ...this.extraProps
1781
+ });
1782
+ }
1783
+ addTableColumn({
1784
+ workspace,
1785
+ region,
1786
+ database,
1787
+ branch,
1788
+ table,
1789
+ column
1790
+ }) {
1791
+ return operationsByTag.table.addTableColumn({
1792
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1793
+ body: column,
1794
+ ...this.extraProps
1795
+ });
1796
+ }
1797
+ getColumn({
1798
+ workspace,
1799
+ region,
1800
+ database,
1801
+ branch,
1802
+ table,
1803
+ column
1804
+ }) {
1805
+ return operationsByTag.table.getColumn({
1806
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, columnName: column },
1807
+ ...this.extraProps
1808
+ });
1809
+ }
1810
+ updateColumn({
1811
+ workspace,
1812
+ region,
1813
+ database,
1814
+ branch,
1815
+ table,
1816
+ column,
1817
+ update
1818
+ }) {
1819
+ return operationsByTag.table.updateColumn({
1820
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, columnName: column },
1821
+ body: update,
1822
+ ...this.extraProps
1823
+ });
1824
+ }
1825
+ deleteColumn({
1826
+ workspace,
1827
+ region,
1828
+ database,
1829
+ branch,
1830
+ table,
1831
+ column
1832
+ }) {
1833
+ return operationsByTag.table.deleteColumn({
1834
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, columnName: column },
1835
+ ...this.extraProps
1836
+ });
1837
+ }
1838
+ }
1839
+ class RecordsApi {
1840
+ constructor(extraProps) {
1841
+ this.extraProps = extraProps;
1842
+ }
1843
+ insertRecord({
1844
+ workspace,
1845
+ region,
1846
+ database,
1847
+ branch,
1848
+ table,
1849
+ record,
1850
+ columns
1851
+ }) {
1852
+ return operationsByTag.records.insertRecord({
1853
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1854
+ queryParams: { columns },
1855
+ body: record,
1856
+ ...this.extraProps
1857
+ });
1858
+ }
1859
+ getRecord({
1860
+ workspace,
1861
+ region,
1862
+ database,
1863
+ branch,
1864
+ table,
1865
+ id,
1866
+ columns
1867
+ }) {
1868
+ return operationsByTag.records.getRecord({
1869
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, recordId: id },
1870
+ queryParams: { columns },
1871
+ ...this.extraProps
1872
+ });
1873
+ }
1874
+ insertRecordWithID({
1875
+ workspace,
1876
+ region,
1877
+ database,
1878
+ branch,
1879
+ table,
1880
+ id,
1881
+ record,
1882
+ columns,
1883
+ createOnly,
1884
+ ifVersion
1885
+ }) {
1886
+ return operationsByTag.records.insertRecordWithID({
1887
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, recordId: id },
1888
+ queryParams: { columns, createOnly, ifVersion },
1889
+ body: record,
1890
+ ...this.extraProps
1891
+ });
1892
+ }
1893
+ updateRecordWithID({
1894
+ workspace,
1895
+ region,
1896
+ database,
1897
+ branch,
1898
+ table,
1899
+ id,
1900
+ record,
1901
+ columns,
1902
+ ifVersion
1903
+ }) {
1904
+ return operationsByTag.records.updateRecordWithID({
1905
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, recordId: id },
1906
+ queryParams: { columns, ifVersion },
1907
+ body: record,
1908
+ ...this.extraProps
1909
+ });
1910
+ }
1911
+ upsertRecordWithID({
1912
+ workspace,
1913
+ region,
1914
+ database,
1915
+ branch,
1916
+ table,
1917
+ id,
1918
+ record,
1919
+ columns,
1920
+ ifVersion
1921
+ }) {
1922
+ return operationsByTag.records.upsertRecordWithID({
1923
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, recordId: id },
1924
+ queryParams: { columns, ifVersion },
1925
+ body: record,
1926
+ ...this.extraProps
1927
+ });
1928
+ }
1929
+ deleteRecord({
1930
+ workspace,
1931
+ region,
1932
+ database,
1933
+ branch,
1934
+ table,
1935
+ id,
1936
+ columns
1937
+ }) {
1938
+ return operationsByTag.records.deleteRecord({
1939
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, recordId: id },
1940
+ queryParams: { columns },
1941
+ ...this.extraProps
1942
+ });
1943
+ }
1944
+ bulkInsertTableRecords({
1945
+ workspace,
1946
+ region,
1947
+ database,
1948
+ branch,
1949
+ table,
1950
+ records,
1951
+ columns
1952
+ }) {
1953
+ return operationsByTag.records.bulkInsertTableRecords({
1954
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
1955
+ queryParams: { columns },
1956
+ body: { records },
1957
+ ...this.extraProps
1958
+ });
1959
+ }
1960
+ branchTransaction({
1961
+ workspace,
1962
+ region,
1963
+ database,
1964
+ branch,
1965
+ operations
1966
+ }) {
1967
+ return operationsByTag.records.branchTransaction({
1968
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
1969
+ body: { operations },
1970
+ ...this.extraProps
1971
+ });
1972
+ }
1973
+ }
1974
+ class FilesApi {
1975
+ constructor(extraProps) {
1976
+ this.extraProps = extraProps;
1977
+ }
1978
+ getFileItem({
1979
+ workspace,
1980
+ region,
1981
+ database,
1982
+ branch,
1983
+ table,
1984
+ record,
1985
+ column,
1986
+ fileId
1987
+ }) {
1988
+ return operationsByTag.files.getFileItem({
1989
+ pathParams: {
1990
+ workspace,
1991
+ region,
1992
+ dbBranchName: `${database}:${branch}`,
1993
+ tableName: table,
1994
+ recordId: record,
1995
+ columnName: column,
1996
+ fileId
1997
+ },
1998
+ ...this.extraProps
1999
+ });
2000
+ }
2001
+ putFileItem({
2002
+ workspace,
2003
+ region,
2004
+ database,
2005
+ branch,
2006
+ table,
2007
+ record,
2008
+ column,
2009
+ fileId,
2010
+ file
2011
+ }) {
2012
+ return operationsByTag.files.putFileItem({
2013
+ pathParams: {
2014
+ workspace,
2015
+ region,
2016
+ dbBranchName: `${database}:${branch}`,
2017
+ tableName: table,
2018
+ recordId: record,
2019
+ columnName: column,
2020
+ fileId
2021
+ },
2022
+ // @ts-ignore
2023
+ body: file,
2024
+ ...this.extraProps
2025
+ });
2026
+ }
2027
+ deleteFileItem({
2028
+ workspace,
2029
+ region,
2030
+ database,
2031
+ branch,
2032
+ table,
2033
+ record,
2034
+ column,
2035
+ fileId
2036
+ }) {
2037
+ return operationsByTag.files.deleteFileItem({
2038
+ pathParams: {
2039
+ workspace,
2040
+ region,
2041
+ dbBranchName: `${database}:${branch}`,
2042
+ tableName: table,
2043
+ recordId: record,
2044
+ columnName: column,
2045
+ fileId
2046
+ },
2047
+ ...this.extraProps
2048
+ });
2049
+ }
2050
+ getFile({
2051
+ workspace,
2052
+ region,
2053
+ database,
2054
+ branch,
2055
+ table,
2056
+ record,
2057
+ column
2058
+ }) {
2059
+ return operationsByTag.files.getFile({
2060
+ pathParams: {
2061
+ workspace,
2062
+ region,
2063
+ dbBranchName: `${database}:${branch}`,
2064
+ tableName: table,
2065
+ recordId: record,
2066
+ columnName: column
2067
+ },
2068
+ ...this.extraProps
2069
+ });
2070
+ }
2071
+ putFile({
2072
+ workspace,
2073
+ region,
2074
+ database,
2075
+ branch,
2076
+ table,
2077
+ record,
2078
+ column,
2079
+ file
2080
+ }) {
2081
+ return operationsByTag.files.putFile({
2082
+ pathParams: {
2083
+ workspace,
2084
+ region,
2085
+ dbBranchName: `${database}:${branch}`,
2086
+ tableName: table,
2087
+ recordId: record,
2088
+ columnName: column
2089
+ },
2090
+ body: file,
2091
+ ...this.extraProps
2092
+ });
2093
+ }
2094
+ deleteFile({
2095
+ workspace,
2096
+ region,
2097
+ database,
2098
+ branch,
2099
+ table,
2100
+ record,
2101
+ column
2102
+ }) {
2103
+ return operationsByTag.files.deleteFile({
2104
+ pathParams: {
2105
+ workspace,
2106
+ region,
2107
+ dbBranchName: `${database}:${branch}`,
2108
+ tableName: table,
2109
+ recordId: record,
2110
+ columnName: column
2111
+ },
2112
+ ...this.extraProps
2113
+ });
2114
+ }
2115
+ fileAccess({
2116
+ workspace,
2117
+ region,
2118
+ fileId,
2119
+ verify
2120
+ }) {
2121
+ return operationsByTag.files.fileAccess({
2122
+ pathParams: {
2123
+ workspace,
2124
+ region,
2125
+ fileId
2126
+ },
2127
+ queryParams: { verify },
2128
+ ...this.extraProps
2129
+ });
2130
+ }
2131
+ }
2132
+ class SearchAndFilterApi {
2133
+ constructor(extraProps) {
2134
+ this.extraProps = extraProps;
2135
+ }
2136
+ queryTable({
2137
+ workspace,
2138
+ region,
2139
+ database,
2140
+ branch,
2141
+ table,
2142
+ filter,
2143
+ sort,
2144
+ page,
2145
+ columns,
2146
+ consistency
2147
+ }) {
2148
+ return operationsByTag.searchAndFilter.queryTable({
2149
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2150
+ body: { filter, sort, page, columns, consistency },
2151
+ ...this.extraProps
2152
+ });
2153
+ }
2154
+ searchTable({
2155
+ workspace,
2156
+ region,
2157
+ database,
2158
+ branch,
2159
+ table,
2160
+ query,
2161
+ fuzziness,
2162
+ target,
2163
+ prefix,
2164
+ filter,
2165
+ highlight,
2166
+ boosters
2167
+ }) {
2168
+ return operationsByTag.searchAndFilter.searchTable({
2169
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2170
+ body: { query, fuzziness, target, prefix, filter, highlight, boosters },
2171
+ ...this.extraProps
2172
+ });
2173
+ }
2174
+ searchBranch({
2175
+ workspace,
2176
+ region,
2177
+ database,
2178
+ branch,
2179
+ tables,
2180
+ query,
2181
+ fuzziness,
2182
+ prefix,
2183
+ highlight
2184
+ }) {
2185
+ return operationsByTag.searchAndFilter.searchBranch({
2186
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2187
+ body: { tables, query, fuzziness, prefix, highlight },
2188
+ ...this.extraProps
2189
+ });
2190
+ }
2191
+ vectorSearchTable({
2192
+ workspace,
2193
+ region,
2194
+ database,
2195
+ branch,
2196
+ table,
2197
+ queryVector,
2198
+ column,
2199
+ similarityFunction,
2200
+ size,
2201
+ filter
2202
+ }) {
2203
+ return operationsByTag.searchAndFilter.vectorSearchTable({
2204
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2205
+ body: { queryVector, column, similarityFunction, size, filter },
2206
+ ...this.extraProps
2207
+ });
2208
+ }
2209
+ askTable({
2210
+ workspace,
2211
+ region,
2212
+ database,
2213
+ branch,
2214
+ table,
2215
+ options
2216
+ }) {
2217
+ return operationsByTag.searchAndFilter.askTable({
2218
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2219
+ body: { ...options },
2220
+ ...this.extraProps
2221
+ });
2222
+ }
2223
+ askTableSession({
2224
+ workspace,
2225
+ region,
2226
+ database,
2227
+ branch,
2228
+ table,
2229
+ sessionId,
2230
+ message
2231
+ }) {
2232
+ return operationsByTag.searchAndFilter.askTableSession({
2233
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table, sessionId },
2234
+ body: { message },
2235
+ ...this.extraProps
2236
+ });
2237
+ }
2238
+ summarizeTable({
2239
+ workspace,
2240
+ region,
2241
+ database,
2242
+ branch,
2243
+ table,
2244
+ filter,
2245
+ columns,
2246
+ summaries,
2247
+ sort,
2248
+ summariesFilter,
2249
+ page,
2250
+ consistency
2251
+ }) {
2252
+ return operationsByTag.searchAndFilter.summarizeTable({
2253
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2254
+ body: { filter, columns, summaries, sort, summariesFilter, page, consistency },
2255
+ ...this.extraProps
2256
+ });
2257
+ }
2258
+ aggregateTable({
2259
+ workspace,
2260
+ region,
2261
+ database,
2262
+ branch,
2263
+ table,
2264
+ filter,
2265
+ aggs
2266
+ }) {
2267
+ return operationsByTag.searchAndFilter.aggregateTable({
2268
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, tableName: table },
2269
+ body: { filter, aggs },
2270
+ ...this.extraProps
2271
+ });
2272
+ }
2273
+ }
2274
+ class MigrationRequestsApi {
2275
+ constructor(extraProps) {
2276
+ this.extraProps = extraProps;
2277
+ }
2278
+ queryMigrationRequests({
2279
+ workspace,
2280
+ region,
2281
+ database,
2282
+ filter,
2283
+ sort,
2284
+ page,
2285
+ columns
2286
+ }) {
2287
+ return operationsByTag.migrationRequests.queryMigrationRequests({
2288
+ pathParams: { workspace, region, dbName: database },
2289
+ body: { filter, sort, page, columns },
2290
+ ...this.extraProps
2291
+ });
2292
+ }
2293
+ createMigrationRequest({
2294
+ workspace,
2295
+ region,
2296
+ database,
2297
+ migration
2298
+ }) {
2299
+ return operationsByTag.migrationRequests.createMigrationRequest({
2300
+ pathParams: { workspace, region, dbName: database },
2301
+ body: migration,
2302
+ ...this.extraProps
2303
+ });
2304
+ }
2305
+ getMigrationRequest({
2306
+ workspace,
2307
+ region,
2308
+ database,
2309
+ migrationRequest
2310
+ }) {
2311
+ return operationsByTag.migrationRequests.getMigrationRequest({
2312
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
2313
+ ...this.extraProps
2314
+ });
2315
+ }
2316
+ updateMigrationRequest({
2317
+ workspace,
2318
+ region,
2319
+ database,
2320
+ migrationRequest,
2321
+ update
2322
+ }) {
2323
+ return operationsByTag.migrationRequests.updateMigrationRequest({
2324
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
2325
+ body: update,
2326
+ ...this.extraProps
2327
+ });
2328
+ }
2329
+ listMigrationRequestsCommits({
2330
+ workspace,
2331
+ region,
2332
+ database,
2333
+ migrationRequest,
2334
+ page
2335
+ }) {
2336
+ return operationsByTag.migrationRequests.listMigrationRequestsCommits({
2337
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
2338
+ body: { page },
2339
+ ...this.extraProps
2340
+ });
2341
+ }
2342
+ compareMigrationRequest({
2343
+ workspace,
2344
+ region,
2345
+ database,
2346
+ migrationRequest
2347
+ }) {
2348
+ return operationsByTag.migrationRequests.compareMigrationRequest({
2349
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
2350
+ ...this.extraProps
2351
+ });
2352
+ }
2353
+ getMigrationRequestIsMerged({
2354
+ workspace,
2355
+ region,
2356
+ database,
2357
+ migrationRequest
2358
+ }) {
2359
+ return operationsByTag.migrationRequests.getMigrationRequestIsMerged({
2360
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
2361
+ ...this.extraProps
2362
+ });
2363
+ }
2364
+ mergeMigrationRequest({
2365
+ workspace,
2366
+ region,
2367
+ database,
2368
+ migrationRequest
2369
+ }) {
2370
+ return operationsByTag.migrationRequests.mergeMigrationRequest({
2371
+ pathParams: { workspace, region, dbName: database, mrNumber: migrationRequest },
2372
+ ...this.extraProps
2373
+ });
2374
+ }
2375
+ }
2376
+ class MigrationsApi {
2377
+ constructor(extraProps) {
2378
+ this.extraProps = extraProps;
2379
+ }
2380
+ getBranchMigrationHistory({
2381
+ workspace,
2382
+ region,
2383
+ database,
2384
+ branch,
2385
+ limit,
2386
+ startFrom
2387
+ }) {
2388
+ return operationsByTag.migrations.getBranchMigrationHistory({
2389
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2390
+ body: { limit, startFrom },
2391
+ ...this.extraProps
2392
+ });
2393
+ }
2394
+ getBranchMigrationPlan({
2395
+ workspace,
2396
+ region,
2397
+ database,
2398
+ branch,
2399
+ schema
2400
+ }) {
2401
+ return operationsByTag.migrations.getBranchMigrationPlan({
2402
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2403
+ body: schema,
2404
+ ...this.extraProps
2405
+ });
2406
+ }
2407
+ executeBranchMigrationPlan({
2408
+ workspace,
2409
+ region,
2410
+ database,
2411
+ branch,
2412
+ plan
2413
+ }) {
2414
+ return operationsByTag.migrations.executeBranchMigrationPlan({
2415
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2416
+ body: plan,
2417
+ ...this.extraProps
2418
+ });
2419
+ }
2420
+ getBranchSchemaHistory({
2421
+ workspace,
2422
+ region,
2423
+ database,
2424
+ branch,
2425
+ page
2426
+ }) {
2427
+ return operationsByTag.migrations.getBranchSchemaHistory({
2428
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2429
+ body: { page },
2430
+ ...this.extraProps
2431
+ });
2432
+ }
2433
+ compareBranchWithUserSchema({
2434
+ workspace,
2435
+ region,
2436
+ database,
2437
+ branch,
2438
+ schema,
2439
+ schemaOperations,
2440
+ branchOperations
2441
+ }) {
2442
+ return operationsByTag.migrations.compareBranchWithUserSchema({
2443
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2444
+ body: { schema, schemaOperations, branchOperations },
2445
+ ...this.extraProps
2446
+ });
2447
+ }
2448
+ compareBranchSchemas({
2449
+ workspace,
2450
+ region,
2451
+ database,
2452
+ branch,
2453
+ compare,
2454
+ sourceBranchOperations,
2455
+ targetBranchOperations
2456
+ }) {
2457
+ return operationsByTag.migrations.compareBranchSchemas({
2458
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}`, branchName: compare },
2459
+ body: { sourceBranchOperations, targetBranchOperations },
2460
+ ...this.extraProps
2461
+ });
2462
+ }
2463
+ updateBranchSchema({
2464
+ workspace,
2465
+ region,
2466
+ database,
2467
+ branch,
2468
+ migration
2469
+ }) {
2470
+ return operationsByTag.migrations.updateBranchSchema({
2471
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2472
+ body: migration,
2473
+ ...this.extraProps
2474
+ });
2475
+ }
2476
+ previewBranchSchemaEdit({
2477
+ workspace,
2478
+ region,
2479
+ database,
2480
+ branch,
2481
+ data
2482
+ }) {
2483
+ return operationsByTag.migrations.previewBranchSchemaEdit({
2484
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2485
+ body: data,
2486
+ ...this.extraProps
2487
+ });
2488
+ }
2489
+ applyBranchSchemaEdit({
2490
+ workspace,
2491
+ region,
2492
+ database,
2493
+ branch,
2494
+ edits
2495
+ }) {
2496
+ return operationsByTag.migrations.applyBranchSchemaEdit({
2497
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2498
+ body: { edits },
2499
+ ...this.extraProps
2500
+ });
2501
+ }
2502
+ pushBranchMigrations({
2503
+ workspace,
2504
+ region,
2505
+ database,
2506
+ branch,
2507
+ migrations
2508
+ }) {
2509
+ return operationsByTag.migrations.pushBranchMigrations({
2510
+ pathParams: { workspace, region, dbBranchName: `${database}:${branch}` },
2511
+ body: { migrations },
2512
+ ...this.extraProps
2513
+ });
2514
+ }
2515
+ }
2516
+ class DatabaseApi {
2517
+ constructor(extraProps) {
2518
+ this.extraProps = extraProps;
2519
+ }
2520
+ getDatabaseList({ workspace }) {
2521
+ return operationsByTag.databases.getDatabaseList({
2522
+ pathParams: { workspaceId: workspace },
2523
+ ...this.extraProps
2524
+ });
2525
+ }
2526
+ createDatabase({
2527
+ workspace,
2528
+ database,
2529
+ data,
2530
+ headers
2531
+ }) {
2532
+ return operationsByTag.databases.createDatabase({
2533
+ pathParams: { workspaceId: workspace, dbName: database },
2534
+ body: data,
2535
+ headers,
2536
+ ...this.extraProps
2537
+ });
2538
+ }
2539
+ deleteDatabase({
2540
+ workspace,
2541
+ database
2542
+ }) {
2543
+ return operationsByTag.databases.deleteDatabase({
2544
+ pathParams: { workspaceId: workspace, dbName: database },
2545
+ ...this.extraProps
2546
+ });
2547
+ }
2548
+ getDatabaseMetadata({
2549
+ workspace,
2550
+ database
2551
+ }) {
2552
+ return operationsByTag.databases.getDatabaseMetadata({
2553
+ pathParams: { workspaceId: workspace, dbName: database },
2554
+ ...this.extraProps
2555
+ });
2556
+ }
2557
+ updateDatabaseMetadata({
2558
+ workspace,
2559
+ database,
2560
+ metadata
2561
+ }) {
2562
+ return operationsByTag.databases.updateDatabaseMetadata({
2563
+ pathParams: { workspaceId: workspace, dbName: database },
2564
+ body: metadata,
2565
+ ...this.extraProps
2566
+ });
2567
+ }
2568
+ renameDatabase({
2569
+ workspace,
2570
+ database,
2571
+ newName
2572
+ }) {
2573
+ return operationsByTag.databases.renameDatabase({
2574
+ pathParams: { workspaceId: workspace, dbName: database },
2575
+ body: { newName },
2576
+ ...this.extraProps
2577
+ });
2578
+ }
2579
+ getDatabaseGithubSettings({
2580
+ workspace,
2581
+ database
2582
+ }) {
2583
+ return operationsByTag.databases.getDatabaseGithubSettings({
2584
+ pathParams: { workspaceId: workspace, dbName: database },
2585
+ ...this.extraProps
2586
+ });
2587
+ }
2588
+ updateDatabaseGithubSettings({
2589
+ workspace,
2590
+ database,
2591
+ settings
2592
+ }) {
2593
+ return operationsByTag.databases.updateDatabaseGithubSettings({
2594
+ pathParams: { workspaceId: workspace, dbName: database },
2595
+ body: settings,
2596
+ ...this.extraProps
2597
+ });
2598
+ }
2599
+ deleteDatabaseGithubSettings({
2600
+ workspace,
2601
+ database
2602
+ }) {
2603
+ return operationsByTag.databases.deleteDatabaseGithubSettings({
2604
+ pathParams: { workspaceId: workspace, dbName: database },
2605
+ ...this.extraProps
2606
+ });
2607
+ }
2608
+ listRegions({ workspace }) {
2609
+ return operationsByTag.databases.listRegions({
2610
+ pathParams: { workspaceId: workspace },
2611
+ ...this.extraProps
2612
+ });
2613
+ }
2614
+ }
2615
+
2616
+ class XataApiPlugin {
2617
+ build(options) {
2618
+ return new XataApiClient(options);
2619
+ }
2620
+ }
2621
+
2622
+ class XataPlugin {
2623
+ }
2624
+
2625
+ class FilesPlugin extends XataPlugin {
2626
+ build(pluginOptions) {
2627
+ return {
2628
+ download: async (location) => {
2629
+ const { table, record, column, fileId = "" } = location ?? {};
2630
+ return await getFileItem({
2631
+ pathParams: {
2632
+ workspace: "{workspaceId}",
2633
+ dbBranchName: "{dbBranch}",
2634
+ region: "{region}",
2635
+ tableName: table ?? "",
2636
+ recordId: record ?? "",
2637
+ columnName: column ?? "",
2638
+ fileId
2639
+ },
2640
+ ...pluginOptions,
2641
+ rawResponse: true
2642
+ });
2643
+ },
2644
+ upload: async (location, file) => {
2645
+ const { table, record, column, fileId = "" } = location ?? {};
2646
+ const contentType = getContentType(file);
2647
+ return await putFileItem({
2648
+ ...pluginOptions,
2649
+ pathParams: {
2650
+ workspace: "{workspaceId}",
2651
+ dbBranchName: "{dbBranch}",
2652
+ region: "{region}",
2653
+ tableName: table ?? "",
2654
+ recordId: record ?? "",
2655
+ columnName: column ?? "",
2656
+ fileId
2657
+ },
2658
+ body: file,
2659
+ headers: { "Content-Type": contentType }
2660
+ });
2661
+ },
2662
+ delete: async (location) => {
2663
+ const { table, record, column, fileId = "" } = location ?? {};
2664
+ return await deleteFileItem({
2665
+ pathParams: {
2666
+ workspace: "{workspaceId}",
2667
+ dbBranchName: "{dbBranch}",
2668
+ region: "{region}",
2669
+ tableName: table ?? "",
2670
+ recordId: record ?? "",
2671
+ columnName: column ?? "",
2672
+ fileId
2673
+ },
2674
+ ...pluginOptions
2675
+ });
2676
+ }
2677
+ };
2678
+ }
2679
+ }
2680
+ function getContentType(file) {
2681
+ if (typeof file === "string") {
2682
+ return "text/plain";
2683
+ }
2684
+ if (isBlob(file)) {
2685
+ return file.type;
2686
+ }
2687
+ try {
2688
+ return file.type;
2689
+ } catch (e) {
2690
+ }
2691
+ return "application/octet-stream";
2692
+ }
2693
+
2694
+ function buildTransformString(transformations) {
2695
+ return transformations.flatMap(
2696
+ (t) => Object.entries(t).map(([key, value]) => {
2697
+ if (key === "trim") {
2698
+ const { left = 0, top = 0, right = 0, bottom = 0 } = value;
2699
+ return `${key}=${[top, right, bottom, left].join(";")}`;
2700
+ }
2701
+ if (key === "gravity" && typeof value === "object") {
2702
+ const { x = 0.5, y = 0.5 } = value;
2703
+ return `${key}=${[x, y].join("x")}`;
2704
+ }
2705
+ return `${key}=${value}`;
2706
+ })
2707
+ ).join(",");
2708
+ }
2709
+ function transformImage(url, ...transformations) {
2710
+ if (!isDefined(url))
2711
+ return void 0;
2712
+ const newTransformations = buildTransformString(transformations);
2713
+ const { hostname, pathname, search } = new URL(url);
2714
+ const pathParts = pathname.split("/");
2715
+ const transformIndex = pathParts.findIndex((part) => part === "transform");
2716
+ const removedItems = transformIndex >= 0 ? pathParts.splice(transformIndex, 2) : [];
2717
+ const transform = `/transform/${[removedItems[1], newTransformations].filter(isDefined).join(",")}`;
2718
+ const path = pathParts.join("/");
2719
+ return `https://${hostname}${transform}${path}${search}`;
2720
+ }
2721
+
2722
+ var __defProp$6 = Object.defineProperty;
2723
+ var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2724
+ var __publicField$6 = (obj, key, value) => {
2725
+ __defNormalProp$6(obj, typeof key !== "symbol" ? key + "" : key, value);
2726
+ return value;
2727
+ };
2728
+ class XataFile {
2729
+ constructor(file) {
2730
+ /**
2731
+ * Identifier of the file.
2732
+ */
2733
+ __publicField$6(this, "id");
2734
+ /**
2735
+ * Name of the file.
2736
+ */
2737
+ __publicField$6(this, "name");
2738
+ /**
2739
+ * Media type of the file.
2740
+ */
2741
+ __publicField$6(this, "mediaType");
2742
+ /**
2743
+ * Base64 encoded content of the file.
2744
+ */
2745
+ __publicField$6(this, "base64Content");
2746
+ /**
2747
+ * Whether to enable public url for the file.
2748
+ */
2749
+ __publicField$6(this, "enablePublicUrl");
2750
+ /**
2751
+ * Timeout for the signed url.
2752
+ */
2753
+ __publicField$6(this, "signedUrlTimeout");
2754
+ /**
2755
+ * Size of the file.
2756
+ */
2757
+ __publicField$6(this, "size");
2758
+ /**
2759
+ * Version of the file.
2760
+ */
2761
+ __publicField$6(this, "version");
2762
+ /**
2763
+ * Url of the file.
2764
+ */
2765
+ __publicField$6(this, "url");
2766
+ /**
2767
+ * Signed url of the file.
2768
+ */
2769
+ __publicField$6(this, "signedUrl");
2770
+ /**
2771
+ * Attributes of the file.
2772
+ */
2773
+ __publicField$6(this, "attributes");
2774
+ this.id = file.id;
2775
+ this.name = file.name || "";
2776
+ this.mediaType = file.mediaType || "application/octet-stream";
2777
+ this.base64Content = file.base64Content;
2778
+ this.enablePublicUrl = file.enablePublicUrl ?? false;
2779
+ this.signedUrlTimeout = file.signedUrlTimeout ?? 300;
2780
+ this.size = file.size ?? 0;
2781
+ this.version = file.version ?? 1;
2782
+ this.url = file.url || "";
2783
+ this.signedUrl = file.signedUrl;
2784
+ this.attributes = file.attributes || {};
2785
+ }
2786
+ static fromBuffer(buffer, options = {}) {
2787
+ const base64Content = buffer.toString("base64");
2788
+ return new XataFile({ ...options, base64Content });
2789
+ }
2790
+ toBuffer() {
2791
+ if (!this.base64Content) {
2792
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2793
+ }
2794
+ return Buffer.from(this.base64Content, "base64");
2795
+ }
2796
+ static fromArrayBuffer(arrayBuffer, options = {}) {
2797
+ const uint8Array = new Uint8Array(arrayBuffer);
2798
+ return this.fromUint8Array(uint8Array, options);
2799
+ }
2800
+ toArrayBuffer() {
2801
+ if (!this.base64Content) {
2802
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2803
+ }
2804
+ const binary = atob(this.base64Content);
2805
+ return new ArrayBuffer(binary.length);
2806
+ }
2807
+ static fromUint8Array(uint8Array, options = {}) {
2808
+ let binary = "";
2809
+ for (let i = 0; i < uint8Array.byteLength; i++) {
2810
+ binary += String.fromCharCode(uint8Array[i]);
2811
+ }
2812
+ const base64Content = btoa(binary);
2813
+ return new XataFile({ ...options, base64Content });
2814
+ }
2815
+ toUint8Array() {
2816
+ if (!this.base64Content) {
2817
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2818
+ }
2819
+ const binary = atob(this.base64Content);
2820
+ const uint8Array = new Uint8Array(binary.length);
2821
+ for (let i = 0; i < binary.length; i++) {
2822
+ uint8Array[i] = binary.charCodeAt(i);
2823
+ }
2824
+ return uint8Array;
2825
+ }
2826
+ static async fromBlob(file, options = {}) {
2827
+ const name = options.name ?? file.name;
2828
+ const mediaType = file.type;
2829
+ const arrayBuffer = await file.arrayBuffer();
2830
+ return this.fromArrayBuffer(arrayBuffer, { ...options, name, mediaType });
2831
+ }
2832
+ toBlob() {
2833
+ if (!this.base64Content) {
2834
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2835
+ }
2836
+ const binary = atob(this.base64Content);
2837
+ const uint8Array = new Uint8Array(binary.length);
2838
+ for (let i = 0; i < binary.length; i++) {
2839
+ uint8Array[i] = binary.charCodeAt(i);
2840
+ }
2841
+ return new Blob([uint8Array], { type: this.mediaType });
2842
+ }
2843
+ static fromString(string, options = {}) {
2844
+ const base64Content = btoa(string);
2845
+ return new XataFile({ ...options, base64Content });
2846
+ }
2847
+ toString() {
2848
+ if (!this.base64Content) {
2849
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2850
+ }
2851
+ return atob(this.base64Content);
2852
+ }
2853
+ static fromBase64(base64Content, options = {}) {
2854
+ return new XataFile({ ...options, base64Content });
2855
+ }
2856
+ toBase64() {
2857
+ if (!this.base64Content) {
2858
+ throw new Error(`File content is not available, please select property "base64Content" when querying the file`);
2859
+ }
2860
+ return this.base64Content;
2861
+ }
2862
+ transform(...options) {
2863
+ return {
2864
+ url: transformImage(this.url, ...options),
2865
+ signedUrl: transformImage(this.signedUrl, ...options),
2866
+ metadataUrl: transformImage(this.url, ...options, { format: "json" }),
2867
+ metadataSignedUrl: transformImage(this.signedUrl, ...options, { format: "json" })
2868
+ };
2869
+ }
2870
+ }
2871
+ const parseInputFileEntry = async (entry) => {
2872
+ if (!isDefined(entry))
2873
+ return null;
2874
+ const { id, name, mediaType, base64Content, enablePublicUrl, signedUrlTimeout } = await entry;
2875
+ return compactObject({
2876
+ id,
2877
+ // Name cannot be an empty string in our API
2878
+ name: name ? name : void 0,
2879
+ mediaType,
2880
+ base64Content,
2881
+ enablePublicUrl,
2882
+ signedUrlTimeout
2883
+ });
2884
+ };
2885
+
2886
+ function cleanFilter(filter) {
2887
+ if (!isDefined(filter))
2888
+ return void 0;
2889
+ if (!isObject(filter))
2890
+ return filter;
2891
+ const values = Object.fromEntries(
2892
+ Object.entries(filter).reduce((acc, [key, value]) => {
2893
+ if (!isDefined(value))
2894
+ return acc;
2895
+ if (Array.isArray(value)) {
2896
+ const clean = value.map((item) => cleanFilter(item)).filter((item) => isDefined(item));
2897
+ if (clean.length === 0)
2898
+ return acc;
2899
+ return [...acc, [key, clean]];
2900
+ }
2901
+ if (isObject(value)) {
2902
+ const clean = cleanFilter(value);
2903
+ if (!isDefined(clean))
2904
+ return acc;
2905
+ return [...acc, [key, clean]];
2906
+ }
2907
+ return [...acc, [key, value]];
2908
+ }, [])
2909
+ );
2910
+ return Object.keys(values).length > 0 ? values : void 0;
2911
+ }
2912
+
2913
+ function stringifyJson(value) {
2914
+ if (!isDefined(value))
2915
+ return value;
2916
+ if (isString(value))
2917
+ return value;
2918
+ try {
2919
+ return JSON.stringify(value);
2920
+ } catch (e) {
2921
+ return value;
2922
+ }
2923
+ }
2924
+ function parseJson(value) {
2925
+ try {
2926
+ return JSON.parse(value);
2927
+ } catch (e) {
2928
+ return value;
2929
+ }
2930
+ }
2931
+
2932
+ var __defProp$5 = Object.defineProperty;
2933
+ var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2934
+ var __publicField$5 = (obj, key, value) => {
2935
+ __defNormalProp$5(obj, typeof key !== "symbol" ? key + "" : key, value);
2936
+ return value;
2937
+ };
2938
+ var __accessCheck$6 = (obj, member, msg) => {
2939
+ if (!member.has(obj))
2940
+ throw TypeError("Cannot " + msg);
2941
+ };
2942
+ var __privateGet$6 = (obj, member, getter) => {
2943
+ __accessCheck$6(obj, member, "read from private field");
2944
+ return getter ? getter.call(obj) : member.get(obj);
2945
+ };
2946
+ var __privateAdd$6 = (obj, member, value) => {
2947
+ if (member.has(obj))
2948
+ throw TypeError("Cannot add the same private member more than once");
2949
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
2950
+ };
2951
+ var __privateSet$6 = (obj, member, value, setter) => {
2952
+ __accessCheck$6(obj, member, "write to private field");
2953
+ setter ? setter.call(obj, value) : member.set(obj, value);
2954
+ return value;
2955
+ };
2956
+ var _query, _page;
2957
+ class Page {
2958
+ constructor(query, meta, records = []) {
2959
+ __privateAdd$6(this, _query, void 0);
2960
+ /**
2961
+ * Page metadata, required to retrieve additional records.
2962
+ */
2963
+ __publicField$5(this, "meta");
2964
+ /**
2965
+ * The set of results for this page.
2966
+ */
2967
+ __publicField$5(this, "records");
2968
+ __privateSet$6(this, _query, query);
2969
+ this.meta = meta;
2970
+ this.records = new RecordArray(this, records);
2971
+ }
2972
+ /**
2973
+ * Retrieves the next page of results.
2974
+ * @param size Maximum number of results to be retrieved.
2975
+ * @param offset Number of results to skip when retrieving the results.
2976
+ * @returns The next page or results.
2977
+ */
2978
+ async nextPage(size, offset) {
2979
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
2980
+ }
2981
+ /**
2982
+ * Retrieves the previous page of results.
2983
+ * @param size Maximum number of results to be retrieved.
2984
+ * @param offset Number of results to skip when retrieving the results.
2985
+ * @returns The previous page or results.
2986
+ */
2987
+ async previousPage(size, offset) {
2988
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
2989
+ }
2990
+ /**
2991
+ * Retrieves the start page of results.
2992
+ * @param size Maximum number of results to be retrieved.
2993
+ * @param offset Number of results to skip when retrieving the results.
2994
+ * @returns The start page or results.
2995
+ */
2996
+ async startPage(size, offset) {
2997
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, start: this.meta.page.cursor } });
2998
+ }
2999
+ /**
3000
+ * Retrieves the end page of results.
3001
+ * @param size Maximum number of results to be retrieved.
3002
+ * @param offset Number of results to skip when retrieving the results.
3003
+ * @returns The end page or results.
3004
+ */
3005
+ async endPage(size, offset) {
3006
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, end: this.meta.page.cursor } });
3007
+ }
3008
+ /**
3009
+ * Shortcut method to check if there will be additional results if the next page of results is retrieved.
3010
+ * @returns Whether or not there will be additional results in the next page of results.
3011
+ */
3012
+ hasNextPage() {
3013
+ return this.meta.page.more;
3014
+ }
3015
+ }
3016
+ _query = new WeakMap();
3017
+ const PAGINATION_MAX_SIZE = 200;
3018
+ const PAGINATION_DEFAULT_SIZE = 20;
3019
+ const PAGINATION_MAX_OFFSET = 800;
3020
+ const PAGINATION_DEFAULT_OFFSET = 0;
3021
+ function isCursorPaginationOptions(options) {
3022
+ return isDefined(options) && (isDefined(options.start) || isDefined(options.end) || isDefined(options.after) || isDefined(options.before));
3023
+ }
3024
+ const _RecordArray = class _RecordArray extends Array {
3025
+ constructor(...args) {
3026
+ super(..._RecordArray.parseConstructorParams(...args));
3027
+ __privateAdd$6(this, _page, void 0);
3028
+ __privateSet$6(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
3029
+ }
3030
+ static parseConstructorParams(...args) {
3031
+ if (args.length === 1 && typeof args[0] === "number") {
3032
+ return new Array(args[0]);
3033
+ }
3034
+ if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
3035
+ const result = args[1] ?? args[0].records ?? [];
3036
+ return new Array(...result);
3037
+ }
3038
+ return new Array(...args);
3039
+ }
3040
+ toArray() {
3041
+ return new Array(...this);
3042
+ }
3043
+ toSerializable() {
3044
+ return JSON.parse(this.toString());
3045
+ }
3046
+ toString() {
3047
+ return JSON.stringify(this.toArray());
3048
+ }
3049
+ map(callbackfn, thisArg) {
3050
+ return this.toArray().map(callbackfn, thisArg);
3051
+ }
3052
+ /**
3053
+ * Retrieve next page of records
3054
+ *
3055
+ * @returns A new array of objects
3056
+ */
3057
+ async nextPage(size, offset) {
3058
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
3059
+ return new _RecordArray(newPage);
3060
+ }
3061
+ /**
3062
+ * Retrieve previous page of records
3063
+ *
3064
+ * @returns A new array of objects
3065
+ */
3066
+ async previousPage(size, offset) {
3067
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
3068
+ return new _RecordArray(newPage);
3069
+ }
3070
+ /**
3071
+ * Retrieve start page of records
3072
+ *
3073
+ * @returns A new array of objects
3074
+ */
3075
+ async startPage(size, offset) {
3076
+ const newPage = await __privateGet$6(this, _page).startPage(size, offset);
3077
+ return new _RecordArray(newPage);
3078
+ }
3079
+ /**
3080
+ * Retrieve end page of records
3081
+ *
3082
+ * @returns A new array of objects
3083
+ */
3084
+ async endPage(size, offset) {
3085
+ const newPage = await __privateGet$6(this, _page).endPage(size, offset);
3086
+ return new _RecordArray(newPage);
3087
+ }
3088
+ /**
3089
+ * @returns Boolean indicating if there is a next page
3090
+ */
3091
+ hasNextPage() {
3092
+ return __privateGet$6(this, _page).meta.page.more;
3093
+ }
3094
+ };
3095
+ _page = new WeakMap();
3096
+ let RecordArray = _RecordArray;
3097
+
3098
+ var __defProp$4 = Object.defineProperty;
3099
+ var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3100
+ var __publicField$4 = (obj, key, value) => {
3101
+ __defNormalProp$4(obj, typeof key !== "symbol" ? key + "" : key, value);
3102
+ return value;
3103
+ };
3104
+ var __accessCheck$5 = (obj, member, msg) => {
3105
+ if (!member.has(obj))
3106
+ throw TypeError("Cannot " + msg);
3107
+ };
3108
+ var __privateGet$5 = (obj, member, getter) => {
3109
+ __accessCheck$5(obj, member, "read from private field");
3110
+ return getter ? getter.call(obj) : member.get(obj);
3111
+ };
3112
+ var __privateAdd$5 = (obj, member, value) => {
3113
+ if (member.has(obj))
3114
+ throw TypeError("Cannot add the same private member more than once");
3115
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
3116
+ };
3117
+ var __privateSet$5 = (obj, member, value, setter) => {
3118
+ __accessCheck$5(obj, member, "write to private field");
3119
+ setter ? setter.call(obj, value) : member.set(obj, value);
3120
+ return value;
3121
+ };
3122
+ var __privateMethod$3 = (obj, member, method) => {
3123
+ __accessCheck$5(obj, member, "access private method");
3124
+ return method;
3125
+ };
3126
+ var _table$1, _repository, _data, _cleanFilterConstraint, cleanFilterConstraint_fn;
3127
+ const _Query = class _Query {
3128
+ constructor(repository, table, data, rawParent) {
3129
+ __privateAdd$5(this, _cleanFilterConstraint);
3130
+ __privateAdd$5(this, _table$1, void 0);
3131
+ __privateAdd$5(this, _repository, void 0);
3132
+ __privateAdd$5(this, _data, { filter: {} });
3133
+ // Implements pagination
3134
+ __publicField$4(this, "meta", { page: { cursor: "start", more: true, size: PAGINATION_DEFAULT_SIZE } });
3135
+ __publicField$4(this, "records", new RecordArray(this, []));
3136
+ __privateSet$5(this, _table$1, table);
3137
+ if (repository) {
3138
+ __privateSet$5(this, _repository, repository);
3139
+ } else {
3140
+ __privateSet$5(this, _repository, this);
3141
+ }
3142
+ const parent = cleanParent(data, rawParent);
3143
+ __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
3144
+ __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
3145
+ __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
3146
+ __privateGet$5(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
3147
+ __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
3148
+ __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
3149
+ __privateGet$5(this, _data).columns = data.columns ?? parent?.columns;
3150
+ __privateGet$5(this, _data).consistency = data.consistency ?? parent?.consistency;
3151
+ __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
3152
+ __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
3153
+ __privateGet$5(this, _data).fetchOptions = data.fetchOptions ?? parent?.fetchOptions;
3154
+ this.any = this.any.bind(this);
3155
+ this.all = this.all.bind(this);
3156
+ this.not = this.not.bind(this);
3157
+ this.filter = this.filter.bind(this);
3158
+ this.sort = this.sort.bind(this);
3159
+ this.none = this.none.bind(this);
3160
+ Object.defineProperty(this, "table", { enumerable: false });
3161
+ Object.defineProperty(this, "repository", { enumerable: false });
3162
+ }
3163
+ getQueryOptions() {
3164
+ return __privateGet$5(this, _data);
3165
+ }
3166
+ key() {
3167
+ const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$5(this, _data);
3168
+ const key = JSON.stringify({ columns, filter, sort, pagination });
3169
+ return toBase64(key);
3170
+ }
3171
+ /**
3172
+ * Builds a new query object representing a logical OR between the given subqueries.
3173
+ * @param queries An array of subqueries.
3174
+ * @returns A new Query object.
3175
+ */
3176
+ any(...queries) {
3177
+ const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
3178
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
3179
+ }
3180
+ /**
3181
+ * Builds a new query object representing a logical AND between the given subqueries.
3182
+ * @param queries An array of subqueries.
3183
+ * @returns A new Query object.
3184
+ */
3185
+ all(...queries) {
3186
+ const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
3187
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
3188
+ }
3189
+ /**
3190
+ * Builds a new query object representing a logical OR negating each subquery. In pseudo-code: !q1 OR !q2
3191
+ * @param queries An array of subqueries.
3192
+ * @returns A new Query object.
3193
+ */
3194
+ not(...queries) {
3195
+ const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
3196
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
3197
+ }
3198
+ /**
3199
+ * Builds a new query object representing a logical AND negating each subquery. In pseudo-code: !q1 AND !q2
3200
+ * @param queries An array of subqueries.
3201
+ * @returns A new Query object.
3202
+ */
3203
+ none(...queries) {
3204
+ const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
3205
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
3206
+ }
3207
+ filter(a, b) {
3208
+ if (arguments.length === 1) {
3209
+ const constraints = Object.entries(a ?? {}).map(([column, constraint]) => ({
3210
+ [column]: __privateMethod$3(this, _cleanFilterConstraint, cleanFilterConstraint_fn).call(this, column, constraint)
3211
+ }));
3212
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
3213
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
3214
+ } else {
3215
+ const constraints = isDefined(a) && isDefined(b) ? [{ [a]: __privateMethod$3(this, _cleanFilterConstraint, cleanFilterConstraint_fn).call(this, a, b) }] : void 0;
3216
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
3217
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
3218
+ }
3219
+ }
3220
+ sort(column, direction = "asc") {
3221
+ const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
3222
+ const sort = [...originalSort, { column, direction }];
3223
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
3224
+ }
3225
+ /**
3226
+ * Builds a new query specifying the set of columns to be returned in the query response.
3227
+ * @param columns Array of column names to be returned by the query.
3228
+ * @returns A new Query object.
3229
+ */
3230
+ select(columns) {
3231
+ return new _Query(
3232
+ __privateGet$5(this, _repository),
3233
+ __privateGet$5(this, _table$1),
3234
+ { columns },
3235
+ __privateGet$5(this, _data)
3236
+ );
3237
+ }
3238
+ getPaginated(options = {}) {
3239
+ const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
3240
+ return __privateGet$5(this, _repository).query(query);
3241
+ }
3242
+ /**
3243
+ * Get results in an iterator
3244
+ *
3245
+ * @async
3246
+ * @returns Async interable of results
3247
+ */
3248
+ async *[Symbol.asyncIterator]() {
3249
+ for await (const [record] of this.getIterator({ batchSize: 1 })) {
3250
+ yield record;
3251
+ }
3252
+ }
3253
+ async *getIterator(options = {}) {
3254
+ const { batchSize = 1 } = options;
3255
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
3256
+ let more = page.hasNextPage();
3257
+ yield page.records;
3258
+ while (more) {
3259
+ page = await page.nextPage();
3260
+ more = page.hasNextPage();
3261
+ yield page.records;
3262
+ }
3263
+ }
3264
+ async getMany(options = {}) {
3265
+ const { pagination = {}, ...rest } = options;
3266
+ const { size = PAGINATION_DEFAULT_SIZE, offset } = pagination;
3267
+ const batchSize = size <= PAGINATION_MAX_SIZE ? size : PAGINATION_MAX_SIZE;
3268
+ let page = await this.getPaginated({ ...rest, pagination: { size: batchSize, offset } });
3269
+ const results = [...page.records];
3270
+ while (page.hasNextPage() && results.length < size) {
3271
+ page = await page.nextPage();
3272
+ results.push(...page.records);
3273
+ }
3274
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
3275
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
3276
+ }
3277
+ const array = new RecordArray(page, results.slice(0, size));
3278
+ return array;
3279
+ }
3280
+ async getAll(options = {}) {
3281
+ const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
3282
+ const results = [];
3283
+ for await (const page of this.getIterator({ ...rest, batchSize })) {
3284
+ results.push(...page);
3285
+ }
3286
+ return results;
3287
+ }
3288
+ async getFirst(options = {}) {
3289
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
3290
+ return records[0] ?? null;
3291
+ }
3292
+ async getFirstOrThrow(options = {}) {
3293
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
3294
+ if (records[0] === void 0)
3295
+ throw new Error("No results found.");
3296
+ return records[0];
3297
+ }
3298
+ async summarize(params = {}) {
3299
+ const { summaries, summariesFilter, ...options } = params;
3300
+ const query = new _Query(
3301
+ __privateGet$5(this, _repository),
3302
+ __privateGet$5(this, _table$1),
3303
+ options,
3304
+ __privateGet$5(this, _data)
3305
+ );
3306
+ return __privateGet$5(this, _repository).summarizeTable(query, summaries, summariesFilter);
3307
+ }
3308
+ /**
3309
+ * Builds a new query object adding a cache TTL in milliseconds.
3310
+ * @param ttl The cache TTL in milliseconds.
3311
+ * @returns A new Query object.
3312
+ */
3313
+ cache(ttl) {
3314
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
3315
+ }
3316
+ /**
3317
+ * Retrieve next page of records
3318
+ *
3319
+ * @returns A new page object.
3320
+ */
3321
+ nextPage(size, offset) {
3322
+ return this.startPage(size, offset);
3323
+ }
3324
+ /**
3325
+ * Retrieve previous page of records
3326
+ *
3327
+ * @returns A new page object
3328
+ */
3329
+ previousPage(size, offset) {
3330
+ return this.startPage(size, offset);
3331
+ }
3332
+ /**
3333
+ * Retrieve start page of records
3334
+ *
3335
+ * @returns A new page object
3336
+ */
3337
+ startPage(size, offset) {
3338
+ return this.getPaginated({ pagination: { size, offset } });
3339
+ }
3340
+ /**
3341
+ * Retrieve last page of records
3342
+ *
3343
+ * @returns A new page object
3344
+ */
3345
+ endPage(size, offset) {
3346
+ return this.getPaginated({ pagination: { size, offset, before: "end" } });
3347
+ }
3348
+ /**
3349
+ * @returns Boolean indicating if there is a next page
3350
+ */
3351
+ hasNextPage() {
3352
+ return this.meta.page.more;
3353
+ }
3354
+ };
3355
+ _table$1 = new WeakMap();
3356
+ _repository = new WeakMap();
3357
+ _data = new WeakMap();
3358
+ _cleanFilterConstraint = new WeakSet();
3359
+ cleanFilterConstraint_fn = function(column, value) {
3360
+ const columnType = __privateGet$5(this, _table$1).schema?.columns.find(({ name }) => name === column)?.type;
3361
+ if (columnType === "multiple" && (isString(value) || isStringArray(value))) {
3362
+ return { $includes: value };
3363
+ }
3364
+ if (columnType === "link" && isObject(value) && isString(value.id)) {
3365
+ return value.id;
3366
+ }
3367
+ return value;
3368
+ };
3369
+ let Query = _Query;
3370
+ function cleanParent(data, parent) {
3371
+ if (isCursorPaginationOptions(data.pagination)) {
3372
+ return { ...parent, sort: void 0, filter: void 0 };
3373
+ }
3374
+ return parent;
3375
+ }
3376
+
3377
+ const RecordColumnTypes = [
3378
+ "bool",
3379
+ "int",
3380
+ "float",
3381
+ "string",
3382
+ "text",
3383
+ "email",
3384
+ "multiple",
3385
+ "link",
3386
+ "object",
3387
+ "datetime",
3388
+ "vector",
3389
+ "file[]",
3390
+ "file",
3391
+ "json"
3392
+ ];
3393
+ function isIdentifiable(x) {
3394
+ return isObject(x) && isString(x?.id);
3395
+ }
3396
+ function isXataRecord(x) {
3397
+ const record = x;
3398
+ const metadata = record?.getMetadata();
3399
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
3400
+ }
3401
+
3402
+ function isValidExpandedColumn(column) {
3403
+ return isObject(column) && isString(column.name);
3404
+ }
3405
+ function isValidSelectableColumns(columns) {
3406
+ if (!Array.isArray(columns)) {
3407
+ return false;
3408
+ }
3409
+ return columns.every((column) => {
3410
+ if (typeof column === "string") {
3411
+ return true;
3412
+ }
3413
+ if (typeof column === "object") {
3414
+ return isValidExpandedColumn(column);
3415
+ }
3416
+ return false;
3417
+ });
3418
+ }
3419
+
3420
+ function isSortFilterString(value) {
3421
+ return isString(value);
3422
+ }
3423
+ function isSortFilterBase(filter) {
3424
+ return isObject(filter) && Object.entries(filter).every(([key, value]) => {
3425
+ if (key === "*")
3426
+ return value === "random";
3427
+ return value === "asc" || value === "desc";
3428
+ });
3429
+ }
3430
+ function isSortFilterObject(filter) {
3431
+ return isObject(filter) && !isSortFilterBase(filter) && filter.column !== void 0;
3432
+ }
3433
+ function buildSortFilter(filter) {
3434
+ if (isSortFilterString(filter)) {
3435
+ return { [filter]: "asc" };
3436
+ } else if (Array.isArray(filter)) {
3437
+ return filter.map((item) => buildSortFilter(item));
3438
+ } else if (isSortFilterBase(filter)) {
3439
+ return filter;
3440
+ } else if (isSortFilterObject(filter)) {
3441
+ return { [filter.column]: filter.direction ?? "asc" };
3442
+ } else {
3443
+ throw new Error(`Invalid sort filter: ${filter}`);
3444
+ }
3445
+ }
3446
+
3447
+ var __accessCheck$4 = (obj, member, msg) => {
3448
+ if (!member.has(obj))
3449
+ throw TypeError("Cannot " + msg);
3450
+ };
3451
+ var __privateGet$4 = (obj, member, getter) => {
3452
+ __accessCheck$4(obj, member, "read from private field");
3453
+ return getter ? getter.call(obj) : member.get(obj);
3454
+ };
3455
+ var __privateAdd$4 = (obj, member, value) => {
3456
+ if (member.has(obj))
3457
+ throw TypeError("Cannot add the same private member more than once");
3458
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
3459
+ };
3460
+ var __privateSet$4 = (obj, member, value, setter) => {
3461
+ __accessCheck$4(obj, member, "write to private field");
3462
+ setter ? setter.call(obj, value) : member.set(obj, value);
3463
+ return value;
3464
+ };
3465
+ var __privateMethod$2 = (obj, member, method) => {
3466
+ __accessCheck$4(obj, member, "access private method");
3467
+ return method;
3468
+ };
3469
+ var _table, _getFetchProps, _db, _cache, _schemaTables$2, _trace, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _insertRecords, insertRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _updateRecords, updateRecords_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _deleteRecords, deleteRecords_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchemaTables$1, getSchemaTables_fn$1, _transformObjectToApi, transformObjectToApi_fn;
3470
+ const BULK_OPERATION_MAX_SIZE = 1e3;
3471
+ class Repository extends Query {
3472
+ }
3473
+ class RestRepository extends Query {
3474
+ constructor(options) {
3475
+ super(
3476
+ null,
3477
+ { name: options.table, schema: options.schemaTables?.find((table) => table.name === options.table) },
3478
+ {}
3479
+ );
3480
+ __privateAdd$4(this, _insertRecordWithoutId);
3481
+ __privateAdd$4(this, _insertRecordWithId);
3482
+ __privateAdd$4(this, _insertRecords);
3483
+ __privateAdd$4(this, _updateRecordWithID);
3484
+ __privateAdd$4(this, _updateRecords);
3485
+ __privateAdd$4(this, _upsertRecordWithID);
3486
+ __privateAdd$4(this, _deleteRecord);
3487
+ __privateAdd$4(this, _deleteRecords);
3488
+ __privateAdd$4(this, _setCacheQuery);
3489
+ __privateAdd$4(this, _getCacheQuery);
3490
+ __privateAdd$4(this, _getSchemaTables$1);
3491
+ __privateAdd$4(this, _transformObjectToApi);
3492
+ __privateAdd$4(this, _table, void 0);
3493
+ __privateAdd$4(this, _getFetchProps, void 0);
3494
+ __privateAdd$4(this, _db, void 0);
3495
+ __privateAdd$4(this, _cache, void 0);
3496
+ __privateAdd$4(this, _schemaTables$2, void 0);
3497
+ __privateAdd$4(this, _trace, void 0);
3498
+ __privateSet$4(this, _table, options.table);
3499
+ __privateSet$4(this, _db, options.db);
3500
+ __privateSet$4(this, _cache, options.pluginOptions.cache);
3501
+ __privateSet$4(this, _schemaTables$2, options.schemaTables);
3502
+ __privateSet$4(this, _getFetchProps, () => ({ ...options.pluginOptions, sessionID: generateUUID() }));
3503
+ const trace = options.pluginOptions.trace ?? defaultTrace;
3504
+ __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
3505
+ return trace(name, fn, {
3506
+ ...options2,
3507
+ [TraceAttributes.TABLE]: __privateGet$4(this, _table),
3508
+ [TraceAttributes.KIND]: "sdk-operation",
3509
+ [TraceAttributes.VERSION]: VERSION
3510
+ });
3511
+ });
3512
+ }
3513
+ async create(a, b, c, d) {
3514
+ return __privateGet$4(this, _trace).call(this, "create", async () => {
3515
+ const ifVersion = parseIfVersion(b, c, d);
3516
+ if (Array.isArray(a)) {
3517
+ if (a.length === 0)
3518
+ return [];
3519
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: true });
3520
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3521
+ const result = await this.read(ids, columns);
3522
+ return result;
3523
+ }
3524
+ if (isString(a) && isObject(b)) {
3525
+ if (a === "")
3526
+ throw new Error("The id can't be empty");
3527
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3528
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: true, ifVersion });
3529
+ }
3530
+ if (isObject(a) && isString(a.id)) {
3531
+ if (a.id === "")
3532
+ throw new Error("The id can't be empty");
3533
+ const columns = isValidSelectableColumns(b) ? b : void 0;
3534
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: true, ifVersion });
3535
+ }
3536
+ if (isObject(a)) {
3537
+ const columns = isValidSelectableColumns(b) ? b : void 0;
3538
+ return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
3539
+ }
3540
+ throw new Error("Invalid arguments for create method");
3541
+ });
3542
+ }
3543
+ async read(a, b) {
3544
+ return __privateGet$4(this, _trace).call(this, "read", async () => {
3545
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3546
+ if (Array.isArray(a)) {
3547
+ if (a.length === 0)
3548
+ return [];
3549
+ const ids = a.map((item) => extractId(item));
3550
+ const finalObjects = await this.getAll({ filter: { id: { $any: compact(ids) } }, columns });
3551
+ const dictionary = finalObjects.reduce((acc, object) => {
3552
+ acc[object.id] = object;
3553
+ return acc;
3554
+ }, {});
3555
+ return ids.map((id2) => dictionary[id2 ?? ""] ?? null);
3556
+ }
3557
+ const id = extractId(a);
3558
+ if (id) {
3559
+ try {
3560
+ const response = await getRecord({
3561
+ pathParams: {
3562
+ workspace: "{workspaceId}",
3563
+ dbBranchName: "{dbBranch}",
3564
+ region: "{region}",
3565
+ tableName: __privateGet$4(this, _table),
3566
+ recordId: id
3567
+ },
3568
+ queryParams: { columns },
3569
+ ...__privateGet$4(this, _getFetchProps).call(this)
3570
+ });
3571
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3572
+ return initObject(
3573
+ __privateGet$4(this, _db),
3574
+ schemaTables,
3575
+ __privateGet$4(this, _table),
3576
+ response,
3577
+ columns
3578
+ );
3579
+ } catch (e) {
3580
+ if (isObject(e) && e.status === 404) {
3581
+ return null;
3582
+ }
3583
+ throw e;
3584
+ }
3585
+ }
3586
+ return null;
3587
+ });
3588
+ }
3589
+ async readOrThrow(a, b) {
3590
+ return __privateGet$4(this, _trace).call(this, "readOrThrow", async () => {
3591
+ const result = await this.read(a, b);
3592
+ if (Array.isArray(result)) {
3593
+ const missingIds = compact(
3594
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
3595
+ );
3596
+ if (missingIds.length > 0) {
3597
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
3598
+ }
3599
+ return result;
3600
+ }
3601
+ if (result === null) {
3602
+ const id = extractId(a) ?? "unknown";
3603
+ throw new Error(`Record with id ${id} not found`);
3604
+ }
3605
+ return result;
3606
+ });
3607
+ }
3608
+ async update(a, b, c, d) {
3609
+ return __privateGet$4(this, _trace).call(this, "update", async () => {
3610
+ const ifVersion = parseIfVersion(b, c, d);
3611
+ if (Array.isArray(a)) {
3612
+ if (a.length === 0)
3613
+ return [];
3614
+ const existing = await this.read(a, ["id"]);
3615
+ const updates = a.filter((_item, index) => existing[index] !== null);
3616
+ await __privateMethod$2(this, _updateRecords, updateRecords_fn).call(this, updates, {
3617
+ ifVersion,
3618
+ upsert: false
3619
+ });
3620
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3621
+ const result = await this.read(a, columns);
3622
+ return result;
3623
+ }
3624
+ try {
3625
+ if (isString(a) && isObject(b)) {
3626
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3627
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3628
+ }
3629
+ if (isObject(a) && isString(a.id)) {
3630
+ const columns = isValidSelectableColumns(b) ? b : void 0;
3631
+ return await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3632
+ }
3633
+ } catch (error) {
3634
+ if (error.status === 422)
3635
+ return null;
3636
+ throw error;
3637
+ }
3638
+ throw new Error("Invalid arguments for update method");
3639
+ });
3640
+ }
3641
+ async updateOrThrow(a, b, c, d) {
3642
+ return __privateGet$4(this, _trace).call(this, "updateOrThrow", async () => {
3643
+ const result = await this.update(a, b, c, d);
3644
+ if (Array.isArray(result)) {
3645
+ const missingIds = compact(
3646
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
3647
+ );
3648
+ if (missingIds.length > 0) {
3649
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
3650
+ }
3651
+ return result;
3652
+ }
3653
+ if (result === null) {
3654
+ const id = extractId(a) ?? "unknown";
3655
+ throw new Error(`Record with id ${id} not found`);
3656
+ }
3657
+ return result;
3658
+ });
3659
+ }
3660
+ async createOrUpdate(a, b, c, d) {
3661
+ return __privateGet$4(this, _trace).call(this, "createOrUpdate", async () => {
3662
+ const ifVersion = parseIfVersion(b, c, d);
3663
+ if (Array.isArray(a)) {
3664
+ if (a.length === 0)
3665
+ return [];
3666
+ await __privateMethod$2(this, _updateRecords, updateRecords_fn).call(this, a, {
3667
+ ifVersion,
3668
+ upsert: true
3669
+ });
3670
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3671
+ const result = await this.read(a, columns);
3672
+ return result;
3673
+ }
3674
+ if (isString(a) && isObject(b)) {
3675
+ if (a === "")
3676
+ throw new Error("The id can't be empty");
3677
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3678
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns, { ifVersion });
3679
+ }
3680
+ if (isObject(a) && isString(a.id)) {
3681
+ if (a.id === "")
3682
+ throw new Error("The id can't be empty");
3683
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3684
+ return await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns, { ifVersion });
3685
+ }
3686
+ if (!isDefined(a) && isObject(b)) {
3687
+ return await this.create(b, c);
3688
+ }
3689
+ if (isObject(a) && !isDefined(a.id)) {
3690
+ return await this.create(a, b);
3691
+ }
3692
+ throw new Error("Invalid arguments for createOrUpdate method");
3693
+ });
3694
+ }
3695
+ async createOrReplace(a, b, c, d) {
3696
+ return __privateGet$4(this, _trace).call(this, "createOrReplace", async () => {
3697
+ const ifVersion = parseIfVersion(b, c, d);
3698
+ if (Array.isArray(a)) {
3699
+ if (a.length === 0)
3700
+ return [];
3701
+ const ids = await __privateMethod$2(this, _insertRecords, insertRecords_fn).call(this, a, { ifVersion, createOnly: false });
3702
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3703
+ const result = await this.read(ids, columns);
3704
+ return result;
3705
+ }
3706
+ if (isString(a) && isObject(b)) {
3707
+ if (a === "")
3708
+ throw new Error("The id can't be empty");
3709
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3710
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns, { createOnly: false, ifVersion });
3711
+ }
3712
+ if (isObject(a) && isString(a.id)) {
3713
+ if (a.id === "")
3714
+ throw new Error("The id can't be empty");
3715
+ const columns = isValidSelectableColumns(c) ? c : void 0;
3716
+ return await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns, { createOnly: false, ifVersion });
3717
+ }
3718
+ if (!isDefined(a) && isObject(b)) {
3719
+ return await this.create(b, c);
3720
+ }
3721
+ if (isObject(a) && !isDefined(a.id)) {
3722
+ return await this.create(a, b);
3723
+ }
3724
+ throw new Error("Invalid arguments for createOrReplace method");
3725
+ });
3726
+ }
3727
+ async delete(a, b) {
3728
+ return __privateGet$4(this, _trace).call(this, "delete", async () => {
3729
+ if (Array.isArray(a)) {
3730
+ if (a.length === 0)
3731
+ return [];
3732
+ const ids = a.map((o) => {
3733
+ if (isString(o))
3734
+ return o;
3735
+ if (isString(o.id))
3736
+ return o.id;
3737
+ throw new Error("Invalid arguments for delete method");
3738
+ });
3739
+ const columns = isValidSelectableColumns(b) ? b : ["*"];
3740
+ const result = await this.read(a, columns);
3741
+ await __privateMethod$2(this, _deleteRecords, deleteRecords_fn).call(this, ids);
3742
+ return result;
3743
+ }
3744
+ if (isString(a)) {
3745
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
3746
+ }
3747
+ if (isObject(a) && isString(a.id)) {
3748
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id, b);
3749
+ }
3750
+ throw new Error("Invalid arguments for delete method");
3751
+ });
3752
+ }
3753
+ async deleteOrThrow(a, b) {
3754
+ return __privateGet$4(this, _trace).call(this, "deleteOrThrow", async () => {
3755
+ const result = await this.delete(a, b);
3756
+ if (Array.isArray(result)) {
3757
+ const missingIds = compact(
3758
+ a.filter((_item, index) => result[index] === null).map((item) => extractId(item))
3759
+ );
3760
+ if (missingIds.length > 0) {
3761
+ throw new Error(`Could not find records with ids: ${missingIds.join(", ")}`);
3762
+ }
3763
+ return result;
3764
+ } else if (result === null) {
3765
+ const id = extractId(a) ?? "unknown";
3766
+ throw new Error(`Record with id ${id} not found`);
3767
+ }
3768
+ return result;
3769
+ });
3770
+ }
3771
+ async search(query, options = {}) {
3772
+ return __privateGet$4(this, _trace).call(this, "search", async () => {
3773
+ const { records } = await searchTable({
3774
+ pathParams: {
3775
+ workspace: "{workspaceId}",
3776
+ dbBranchName: "{dbBranch}",
3777
+ region: "{region}",
3778
+ tableName: __privateGet$4(this, _table)
3779
+ },
3780
+ body: {
3781
+ query,
3782
+ fuzziness: options.fuzziness,
3783
+ prefix: options.prefix,
3784
+ highlight: options.highlight,
3785
+ filter: options.filter,
3786
+ boosters: options.boosters,
3787
+ page: options.page,
3788
+ target: options.target
3789
+ },
3790
+ ...__privateGet$4(this, _getFetchProps).call(this)
3791
+ });
3792
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3793
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
3794
+ });
3795
+ }
3796
+ async vectorSearch(column, query, options) {
3797
+ return __privateGet$4(this, _trace).call(this, "vectorSearch", async () => {
3798
+ const { records } = await vectorSearchTable({
3799
+ pathParams: {
3800
+ workspace: "{workspaceId}",
3801
+ dbBranchName: "{dbBranch}",
3802
+ region: "{region}",
3803
+ tableName: __privateGet$4(this, _table)
3804
+ },
3805
+ body: {
3806
+ column,
3807
+ queryVector: query,
3808
+ similarityFunction: options?.similarityFunction,
3809
+ size: options?.size,
3810
+ filter: options?.filter
3811
+ },
3812
+ ...__privateGet$4(this, _getFetchProps).call(this)
3813
+ });
3814
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3815
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item, ["*"]));
3816
+ });
3817
+ }
3818
+ async aggregate(aggs, filter) {
3819
+ return __privateGet$4(this, _trace).call(this, "aggregate", async () => {
3820
+ const result = await aggregateTable({
3821
+ pathParams: {
3822
+ workspace: "{workspaceId}",
3823
+ dbBranchName: "{dbBranch}",
3824
+ region: "{region}",
3825
+ tableName: __privateGet$4(this, _table)
3826
+ },
3827
+ body: { aggs, filter },
3828
+ ...__privateGet$4(this, _getFetchProps).call(this)
3829
+ });
3830
+ return result;
3831
+ });
3832
+ }
3833
+ async query(query) {
3834
+ return __privateGet$4(this, _trace).call(this, "query", async () => {
3835
+ const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
3836
+ if (cacheQuery)
3837
+ return new Page(query, cacheQuery.meta, cacheQuery.records);
3838
+ const data = query.getQueryOptions();
3839
+ const { meta, records: objects } = await queryTable({
3840
+ pathParams: {
3841
+ workspace: "{workspaceId}",
3842
+ dbBranchName: "{dbBranch}",
3843
+ region: "{region}",
3844
+ tableName: __privateGet$4(this, _table)
3845
+ },
3846
+ body: {
3847
+ filter: cleanFilter(data.filter),
3848
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
3849
+ page: data.pagination,
3850
+ columns: data.columns ?? ["*"],
3851
+ consistency: data.consistency
3852
+ },
3853
+ fetchOptions: data.fetchOptions,
3854
+ ...__privateGet$4(this, _getFetchProps).call(this)
3855
+ });
3856
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3857
+ const records = objects.map(
3858
+ (record) => initObject(
3859
+ __privateGet$4(this, _db),
3860
+ schemaTables,
3861
+ __privateGet$4(this, _table),
3862
+ record,
3863
+ data.columns ?? ["*"]
3864
+ )
3865
+ );
3866
+ await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
3867
+ return new Page(query, meta, records);
3868
+ });
3869
+ }
3870
+ async summarizeTable(query, summaries, summariesFilter) {
3871
+ return __privateGet$4(this, _trace).call(this, "summarize", async () => {
3872
+ const data = query.getQueryOptions();
3873
+ const result = await summarizeTable({
3874
+ pathParams: {
3875
+ workspace: "{workspaceId}",
3876
+ dbBranchName: "{dbBranch}",
3877
+ region: "{region}",
3878
+ tableName: __privateGet$4(this, _table)
3879
+ },
3880
+ body: {
3881
+ filter: cleanFilter(data.filter),
3882
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
3883
+ columns: data.columns,
3884
+ consistency: data.consistency,
3885
+ page: data.pagination?.size !== void 0 ? { size: data.pagination?.size } : void 0,
3886
+ summaries,
3887
+ summariesFilter
3888
+ },
3889
+ ...__privateGet$4(this, _getFetchProps).call(this)
3890
+ });
3891
+ return result;
3892
+ });
3893
+ }
3894
+ ask(question, options) {
3895
+ const questionParam = options?.sessionId ? { message: question } : { question };
3896
+ const params = {
3897
+ pathParams: {
3898
+ workspace: "{workspaceId}",
3899
+ dbBranchName: "{dbBranch}",
3900
+ region: "{region}",
3901
+ tableName: __privateGet$4(this, _table),
3902
+ sessionId: options?.sessionId
3903
+ },
3904
+ body: {
3905
+ ...questionParam,
3906
+ rules: options?.rules,
3907
+ searchType: options?.searchType,
3908
+ search: options?.searchType === "keyword" ? options?.search : void 0,
3909
+ vectorSearch: options?.searchType === "vector" ? options?.vectorSearch : void 0
3910
+ },
3911
+ ...__privateGet$4(this, _getFetchProps).call(this)
3912
+ };
3913
+ if (options?.onMessage) {
3914
+ fetchSSERequest({
3915
+ endpoint: "dataPlane",
3916
+ url: "/db/{dbBranchName}/tables/{tableName}/ask/{sessionId}",
3917
+ method: "POST",
3918
+ onMessage: (message) => {
3919
+ options.onMessage?.({ answer: message.text, records: message.records });
3920
+ },
3921
+ ...params
3922
+ });
3923
+ } else {
3924
+ return askTableSession(params);
3925
+ }
3926
+ }
3927
+ }
3928
+ _table = new WeakMap();
3929
+ _getFetchProps = new WeakMap();
3930
+ _db = new WeakMap();
3931
+ _cache = new WeakMap();
3932
+ _schemaTables$2 = new WeakMap();
3933
+ _trace = new WeakMap();
3934
+ _insertRecordWithoutId = new WeakSet();
3935
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
3936
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3937
+ const response = await insertRecord({
3938
+ pathParams: {
3939
+ workspace: "{workspaceId}",
3940
+ dbBranchName: "{dbBranch}",
3941
+ region: "{region}",
3942
+ tableName: __privateGet$4(this, _table)
3943
+ },
3944
+ queryParams: { columns },
3945
+ body: record,
3946
+ ...__privateGet$4(this, _getFetchProps).call(this)
3947
+ });
3948
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3949
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
3950
+ };
3951
+ _insertRecordWithId = new WeakSet();
3952
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"], { createOnly, ifVersion }) {
3953
+ if (!recordId)
3954
+ return null;
3955
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3956
+ const response = await insertRecordWithID({
3957
+ pathParams: {
3958
+ workspace: "{workspaceId}",
3959
+ dbBranchName: "{dbBranch}",
3960
+ region: "{region}",
3961
+ tableName: __privateGet$4(this, _table),
3962
+ recordId
3963
+ },
3964
+ body: record,
3965
+ queryParams: { createOnly, columns, ifVersion },
3966
+ ...__privateGet$4(this, _getFetchProps).call(this)
3967
+ });
3968
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
3969
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
3970
+ };
3971
+ _insertRecords = new WeakSet();
3972
+ insertRecords_fn = async function(objects, { createOnly, ifVersion }) {
3973
+ const operations = await promiseMap(objects, async (object) => {
3974
+ const record = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
3975
+ return { insert: { table: __privateGet$4(this, _table), record, createOnly, ifVersion } };
3976
+ });
3977
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
3978
+ const ids = [];
3979
+ for (const operations2 of chunkedOperations) {
3980
+ const { results } = await branchTransaction({
3981
+ pathParams: {
3982
+ workspace: "{workspaceId}",
3983
+ dbBranchName: "{dbBranch}",
3984
+ region: "{region}"
3985
+ },
3986
+ body: { operations: operations2 },
3987
+ ...__privateGet$4(this, _getFetchProps).call(this)
3988
+ });
3989
+ for (const result of results) {
3990
+ if (result.operation === "insert") {
3991
+ ids.push(result.id);
3992
+ } else {
3993
+ ids.push(null);
3994
+ }
3995
+ }
3996
+ }
3997
+ return ids;
3998
+ };
3999
+ _updateRecordWithID = new WeakSet();
4000
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
4001
+ if (!recordId)
4002
+ return null;
4003
+ const { id: _id, ...record } = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
4004
+ try {
4005
+ const response = await updateRecordWithID({
4006
+ pathParams: {
4007
+ workspace: "{workspaceId}",
4008
+ dbBranchName: "{dbBranch}",
4009
+ region: "{region}",
4010
+ tableName: __privateGet$4(this, _table),
4011
+ recordId
4012
+ },
4013
+ queryParams: { columns, ifVersion },
4014
+ body: record,
4015
+ ...__privateGet$4(this, _getFetchProps).call(this)
4016
+ });
4017
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
4018
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
4019
+ } catch (e) {
4020
+ if (isObject(e) && e.status === 404) {
4021
+ return null;
4022
+ }
4023
+ throw e;
4024
+ }
4025
+ };
4026
+ _updateRecords = new WeakSet();
4027
+ updateRecords_fn = async function(objects, { ifVersion, upsert }) {
4028
+ const operations = await promiseMap(objects, async ({ id, ...object }) => {
4029
+ const fields = await __privateMethod$2(this, _transformObjectToApi, transformObjectToApi_fn).call(this, object);
4030
+ return { update: { table: __privateGet$4(this, _table), id, ifVersion, upsert, fields } };
4031
+ });
4032
+ const chunkedOperations = chunk(operations, BULK_OPERATION_MAX_SIZE);
4033
+ const ids = [];
4034
+ for (const operations2 of chunkedOperations) {
4035
+ const { results } = await branchTransaction({
4036
+ pathParams: {
4037
+ workspace: "{workspaceId}",
4038
+ dbBranchName: "{dbBranch}",
4039
+ region: "{region}"
4040
+ },
4041
+ body: { operations: operations2 },
4042
+ ...__privateGet$4(this, _getFetchProps).call(this)
4043
+ });
4044
+ for (const result of results) {
4045
+ if (result.operation === "update") {
4046
+ ids.push(result.id);
4047
+ } else {
4048
+ ids.push(null);
4049
+ }
4050
+ }
4051
+ }
4052
+ return ids;
4053
+ };
4054
+ _upsertRecordWithID = new WeakSet();
4055
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"], { ifVersion }) {
4056
+ if (!recordId)
4057
+ return null;
4058
+ const response = await upsertRecordWithID({
4059
+ pathParams: {
4060
+ workspace: "{workspaceId}",
4061
+ dbBranchName: "{dbBranch}",
4062
+ region: "{region}",
4063
+ tableName: __privateGet$4(this, _table),
4064
+ recordId
4065
+ },
4066
+ queryParams: { columns, ifVersion },
4067
+ body: object,
4068
+ ...__privateGet$4(this, _getFetchProps).call(this)
4069
+ });
4070
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
4071
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
4072
+ };
4073
+ _deleteRecord = new WeakSet();
4074
+ deleteRecord_fn = async function(recordId, columns = ["*"]) {
4075
+ if (!recordId)
4076
+ return null;
4077
+ try {
4078
+ const response = await deleteRecord({
4079
+ pathParams: {
4080
+ workspace: "{workspaceId}",
4081
+ dbBranchName: "{dbBranch}",
4082
+ region: "{region}",
4083
+ tableName: __privateGet$4(this, _table),
4084
+ recordId
4085
+ },
4086
+ queryParams: { columns },
4087
+ ...__privateGet$4(this, _getFetchProps).call(this)
4088
+ });
4089
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
4090
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response, columns);
4091
+ } catch (e) {
4092
+ if (isObject(e) && e.status === 404) {
4093
+ return null;
4094
+ }
4095
+ throw e;
4096
+ }
4097
+ };
4098
+ _deleteRecords = new WeakSet();
4099
+ deleteRecords_fn = async function(recordIds) {
4100
+ const chunkedOperations = chunk(
4101
+ compact(recordIds).map((id) => ({ delete: { table: __privateGet$4(this, _table), id } })),
4102
+ BULK_OPERATION_MAX_SIZE
4103
+ );
4104
+ for (const operations of chunkedOperations) {
4105
+ await branchTransaction({
4106
+ pathParams: {
4107
+ workspace: "{workspaceId}",
4108
+ dbBranchName: "{dbBranch}",
4109
+ region: "{region}"
4110
+ },
4111
+ body: { operations },
4112
+ ...__privateGet$4(this, _getFetchProps).call(this)
4113
+ });
4114
+ }
4115
+ };
4116
+ _setCacheQuery = new WeakSet();
4117
+ setCacheQuery_fn = async function(query, meta, records) {
4118
+ await __privateGet$4(this, _cache)?.set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: /* @__PURE__ */ new Date(), meta, records });
4119
+ };
4120
+ _getCacheQuery = new WeakSet();
4121
+ getCacheQuery_fn = async function(query) {
4122
+ const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
4123
+ const result = await __privateGet$4(this, _cache)?.get(key);
4124
+ if (!result)
4125
+ return null;
4126
+ const defaultTTL = __privateGet$4(this, _cache)?.defaultQueryTTL ?? -1;
4127
+ const { cache: ttl = defaultTTL } = query.getQueryOptions();
4128
+ if (ttl < 0)
4129
+ return null;
4130
+ const hasExpired = result.date.getTime() + ttl < Date.now();
4131
+ return hasExpired ? null : result;
4132
+ };
4133
+ _getSchemaTables$1 = new WeakSet();
4134
+ getSchemaTables_fn$1 = async function() {
4135
+ if (__privateGet$4(this, _schemaTables$2))
4136
+ return __privateGet$4(this, _schemaTables$2);
4137
+ const { schema } = await getBranchDetails({
4138
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4139
+ ...__privateGet$4(this, _getFetchProps).call(this)
4140
+ });
4141
+ __privateSet$4(this, _schemaTables$2, schema.tables);
4142
+ return schema.tables;
4143
+ };
4144
+ _transformObjectToApi = new WeakSet();
4145
+ transformObjectToApi_fn = async function(object) {
4146
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
4147
+ const schema = schemaTables.find((table) => table.name === __privateGet$4(this, _table));
4148
+ if (!schema)
4149
+ throw new Error(`Table ${__privateGet$4(this, _table)} not found in schema`);
4150
+ const result = {};
4151
+ for (const [key, value] of Object.entries(object)) {
4152
+ if (key === "xata")
4153
+ continue;
4154
+ const type = schema.columns.find((column) => column.name === key)?.type;
4155
+ switch (type) {
4156
+ case "link": {
4157
+ result[key] = isIdentifiable(value) ? value.id : value;
4158
+ break;
4159
+ }
4160
+ case "datetime": {
4161
+ result[key] = value instanceof Date ? value.toISOString() : value;
4162
+ break;
4163
+ }
4164
+ case `file`:
4165
+ result[key] = await parseInputFileEntry(value);
4166
+ break;
4167
+ case "file[]":
4168
+ result[key] = await promiseMap(value, (item) => parseInputFileEntry(item));
4169
+ break;
4170
+ case "json":
4171
+ result[key] = stringifyJson(value);
4172
+ break;
4173
+ default:
4174
+ result[key] = value;
4175
+ }
4176
+ }
4177
+ return result;
4178
+ };
4179
+ const removeLinksFromObject = (object) => {
4180
+ return Object.entries(object).reduce((acc, [key, value]) => {
4181
+ if (key === "xata")
4182
+ return acc;
4183
+ return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
4184
+ }, {});
4185
+ };
4186
+ const initObject = (db, schemaTables, table, object, selectedColumns) => {
4187
+ const data = {};
4188
+ const { xata, ...rest } = object ?? {};
4189
+ Object.assign(data, rest);
4190
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
4191
+ if (!columns)
4192
+ console.error(`Table ${table} not found in schema`);
4193
+ for (const column of columns ?? []) {
4194
+ if (!isValidColumn(selectedColumns, column))
4195
+ continue;
4196
+ const value = data[column.name];
4197
+ switch (column.type) {
4198
+ case "datetime": {
4199
+ const date = value !== void 0 ? new Date(value) : null;
4200
+ if (date !== null && isNaN(date.getTime())) {
4201
+ console.error(`Failed to parse date ${value} for field ${column.name}`);
4202
+ } else {
4203
+ data[column.name] = date;
4204
+ }
4205
+ break;
4206
+ }
4207
+ case "link": {
4208
+ const linkTable = column.link?.table;
4209
+ if (!linkTable) {
4210
+ console.error(`Failed to parse link for field ${column.name}`);
4211
+ } else if (isObject(value)) {
4212
+ const selectedLinkColumns = selectedColumns.reduce((acc, item) => {
4213
+ if (item === column.name) {
4214
+ return [...acc, "*"];
4215
+ }
4216
+ if (isString(item) && item.startsWith(`${column.name}.`)) {
4217
+ const [, ...path] = item.split(".");
4218
+ return [...acc, path.join(".")];
4219
+ }
4220
+ return acc;
4221
+ }, []);
4222
+ data[column.name] = initObject(
4223
+ db,
4224
+ schemaTables,
4225
+ linkTable,
4226
+ value,
4227
+ selectedLinkColumns
4228
+ );
4229
+ } else {
4230
+ data[column.name] = null;
4231
+ }
4232
+ break;
4233
+ }
4234
+ case "file":
4235
+ data[column.name] = isDefined(value) ? new XataFile(value) : null;
4236
+ break;
4237
+ case "file[]":
4238
+ data[column.name] = value?.map((item) => new XataFile(item)) ?? null;
4239
+ break;
4240
+ case "json":
4241
+ data[column.name] = parseJson(value);
4242
+ break;
4243
+ default:
4244
+ data[column.name] = value ?? null;
4245
+ if (column.notNull === true && value === null) {
4246
+ console.error(`Parse error, column ${column.name} is non nullable and value resolves null`);
4247
+ }
4248
+ break;
4249
+ }
4250
+ }
4251
+ const record = { ...data };
4252
+ const serializable = { xata, ...removeLinksFromObject(data) };
4253
+ const metadata = xata !== void 0 ? { ...xata, createdAt: new Date(xata.createdAt), updatedAt: new Date(xata.updatedAt) } : void 0;
4254
+ record.read = function(columns2) {
4255
+ return db[table].read(record["id"], columns2);
4256
+ };
4257
+ record.update = function(data2, b, c) {
4258
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
4259
+ const ifVersion = parseIfVersion(b, c);
4260
+ return db[table].update(record["id"], data2, columns2, { ifVersion });
4261
+ };
4262
+ record.replace = function(data2, b, c) {
4263
+ const columns2 = isValidSelectableColumns(b) ? b : ["*"];
4264
+ const ifVersion = parseIfVersion(b, c);
4265
+ return db[table].createOrReplace(record["id"], data2, columns2, { ifVersion });
4266
+ };
4267
+ record.delete = function() {
4268
+ return db[table].delete(record["id"]);
4269
+ };
4270
+ record.xata = Object.freeze(metadata);
4271
+ record.getMetadata = function() {
4272
+ return record.xata;
4273
+ };
4274
+ record.toSerializable = function() {
4275
+ return JSON.parse(JSON.stringify(serializable));
4276
+ };
4277
+ record.toString = function() {
4278
+ return JSON.stringify(serializable);
4279
+ };
4280
+ for (const prop of ["read", "update", "replace", "delete", "getMetadata", "toSerializable", "toString"]) {
4281
+ Object.defineProperty(record, prop, { enumerable: false });
4282
+ }
4283
+ Object.freeze(record);
4284
+ return record;
4285
+ };
4286
+ function extractId(value) {
4287
+ if (isString(value))
4288
+ return value;
4289
+ if (isObject(value) && isString(value.id))
4290
+ return value.id;
4291
+ return void 0;
4292
+ }
4293
+ function isValidColumn(columns, column) {
4294
+ if (columns.includes("*"))
4295
+ return true;
4296
+ return columns.filter((item) => isString(item) && item.startsWith(column.name)).length > 0;
4297
+ }
4298
+ function parseIfVersion(...args) {
4299
+ for (const arg of args) {
4300
+ if (isObject(arg) && isNumber(arg.ifVersion)) {
4301
+ return arg.ifVersion;
4302
+ }
4303
+ }
4304
+ return void 0;
4305
+ }
4306
+
4307
+ var __defProp$3 = Object.defineProperty;
4308
+ var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4309
+ var __publicField$3 = (obj, key, value) => {
4310
+ __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
4311
+ return value;
4312
+ };
4313
+ var __accessCheck$3 = (obj, member, msg) => {
4314
+ if (!member.has(obj))
4315
+ throw TypeError("Cannot " + msg);
4316
+ };
4317
+ var __privateGet$3 = (obj, member, getter) => {
4318
+ __accessCheck$3(obj, member, "read from private field");
4319
+ return getter ? getter.call(obj) : member.get(obj);
4320
+ };
4321
+ var __privateAdd$3 = (obj, member, value) => {
4322
+ if (member.has(obj))
4323
+ throw TypeError("Cannot add the same private member more than once");
4324
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
4325
+ };
4326
+ var __privateSet$3 = (obj, member, value, setter) => {
4327
+ __accessCheck$3(obj, member, "write to private field");
4328
+ setter ? setter.call(obj, value) : member.set(obj, value);
4329
+ return value;
4330
+ };
4331
+ var _map;
4332
+ class SimpleCache {
4333
+ constructor(options = {}) {
4334
+ __privateAdd$3(this, _map, void 0);
4335
+ __publicField$3(this, "capacity");
4336
+ __publicField$3(this, "defaultQueryTTL");
4337
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
4338
+ this.capacity = options.max ?? 500;
4339
+ this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
4340
+ }
4341
+ async getAll() {
4342
+ return Object.fromEntries(__privateGet$3(this, _map));
4343
+ }
4344
+ async get(key) {
4345
+ return __privateGet$3(this, _map).get(key) ?? null;
4346
+ }
4347
+ async set(key, value) {
4348
+ await this.delete(key);
4349
+ __privateGet$3(this, _map).set(key, value);
4350
+ if (__privateGet$3(this, _map).size > this.capacity) {
4351
+ const leastRecentlyUsed = __privateGet$3(this, _map).keys().next().value;
4352
+ await this.delete(leastRecentlyUsed);
4353
+ }
4354
+ }
4355
+ async delete(key) {
4356
+ __privateGet$3(this, _map).delete(key);
4357
+ }
4358
+ async clear() {
4359
+ return __privateGet$3(this, _map).clear();
4360
+ }
4361
+ }
4362
+ _map = new WeakMap();
4363
+
4364
+ const greaterThan = (value) => ({ $gt: value });
4365
+ const gt = greaterThan;
4366
+ const greaterThanEquals = (value) => ({ $ge: value });
4367
+ const greaterEquals = greaterThanEquals;
4368
+ const gte = greaterThanEquals;
4369
+ const ge = greaterThanEquals;
4370
+ const lessThan = (value) => ({ $lt: value });
4371
+ const lt = lessThan;
4372
+ const lessThanEquals = (value) => ({ $le: value });
4373
+ const lessEquals = lessThanEquals;
4374
+ const lte = lessThanEquals;
4375
+ const le = lessThanEquals;
4376
+ const exists = (column) => ({ $exists: column });
4377
+ const notExists = (column) => ({ $notExists: column });
4378
+ const startsWith = (value) => ({ $startsWith: value });
4379
+ const endsWith = (value) => ({ $endsWith: value });
4380
+ const pattern = (value) => ({ $pattern: value });
4381
+ const is = (value) => ({ $is: value });
4382
+ const equals = is;
4383
+ const isNot = (value) => ({ $isNot: value });
4384
+ const contains = (value) => ({ $contains: value });
4385
+ const includes = (value) => ({ $includes: value });
4386
+ const includesAll = (value) => ({ $includesAll: value });
4387
+ const includesNone = (value) => ({ $includesNone: value });
4388
+ const includesAny = (value) => ({ $includesAny: value });
4389
+
4390
+ var __accessCheck$2 = (obj, member, msg) => {
4391
+ if (!member.has(obj))
4392
+ throw TypeError("Cannot " + msg);
4393
+ };
4394
+ var __privateGet$2 = (obj, member, getter) => {
4395
+ __accessCheck$2(obj, member, "read from private field");
4396
+ return getter ? getter.call(obj) : member.get(obj);
4397
+ };
4398
+ var __privateAdd$2 = (obj, member, value) => {
4399
+ if (member.has(obj))
4400
+ throw TypeError("Cannot add the same private member more than once");
4401
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
4402
+ };
4403
+ var __privateSet$2 = (obj, member, value, setter) => {
4404
+ __accessCheck$2(obj, member, "write to private field");
4405
+ setter ? setter.call(obj, value) : member.set(obj, value);
4406
+ return value;
4407
+ };
4408
+ var _tables, _schemaTables$1;
4409
+ class SchemaPlugin extends XataPlugin {
4410
+ constructor(schemaTables) {
4411
+ super();
4412
+ __privateAdd$2(this, _tables, {});
4413
+ __privateAdd$2(this, _schemaTables$1, void 0);
4414
+ __privateSet$2(this, _schemaTables$1, schemaTables);
4415
+ }
4416
+ build(pluginOptions) {
4417
+ const db = new Proxy(
4418
+ {},
4419
+ {
4420
+ get: (_target, table) => {
4421
+ if (!isString(table))
4422
+ throw new Error("Invalid table name");
4423
+ if (__privateGet$2(this, _tables)[table] === void 0) {
4424
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
4425
+ }
4426
+ return __privateGet$2(this, _tables)[table];
4427
+ }
4428
+ }
4429
+ );
4430
+ const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
4431
+ for (const table of tableNames) {
4432
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
4433
+ }
4434
+ return db;
4435
+ }
4436
+ }
4437
+ _tables = new WeakMap();
4438
+ _schemaTables$1 = new WeakMap();
4439
+
4440
+ var __accessCheck$1 = (obj, member, msg) => {
4441
+ if (!member.has(obj))
4442
+ throw TypeError("Cannot " + msg);
4443
+ };
4444
+ var __privateGet$1 = (obj, member, getter) => {
4445
+ __accessCheck$1(obj, member, "read from private field");
4446
+ return getter ? getter.call(obj) : member.get(obj);
4447
+ };
4448
+ var __privateAdd$1 = (obj, member, value) => {
4449
+ if (member.has(obj))
4450
+ throw TypeError("Cannot add the same private member more than once");
4451
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
4452
+ };
4453
+ var __privateSet$1 = (obj, member, value, setter) => {
4454
+ __accessCheck$1(obj, member, "write to private field");
4455
+ setter ? setter.call(obj, value) : member.set(obj, value);
4456
+ return value;
4457
+ };
4458
+ var __privateMethod$1 = (obj, member, method) => {
4459
+ __accessCheck$1(obj, member, "access private method");
4460
+ return method;
4461
+ };
4462
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
4463
+ class SearchPlugin extends XataPlugin {
4464
+ constructor(db, schemaTables) {
4465
+ super();
4466
+ this.db = db;
4467
+ __privateAdd$1(this, _search);
4468
+ __privateAdd$1(this, _getSchemaTables);
4469
+ __privateAdd$1(this, _schemaTables, void 0);
4470
+ __privateSet$1(this, _schemaTables, schemaTables);
4471
+ }
4472
+ build(pluginOptions) {
4473
+ return {
4474
+ all: async (query, options = {}) => {
4475
+ const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
4476
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
4477
+ return records.map((record) => {
4478
+ const { table = "orphan" } = record.xata;
4479
+ return { table, record: initObject(this.db, schemaTables, table, record, ["*"]) };
4480
+ });
4481
+ },
4482
+ byTable: async (query, options = {}) => {
4483
+ const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, pluginOptions);
4484
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, pluginOptions);
4485
+ return records.reduce((acc, record) => {
4486
+ const { table = "orphan" } = record.xata;
4487
+ const items = acc[table] ?? [];
4488
+ const item = initObject(this.db, schemaTables, table, record, ["*"]);
4489
+ return { ...acc, [table]: [...items, item] };
4490
+ }, {});
4491
+ }
4492
+ };
4493
+ }
4494
+ }
4495
+ _schemaTables = new WeakMap();
4496
+ _search = new WeakSet();
4497
+ search_fn = async function(query, options, pluginOptions) {
4498
+ const { tables, fuzziness, highlight, prefix, page } = options ?? {};
4499
+ const { records } = await searchBranch({
4500
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4501
+ // @ts-ignore https://github.com/xataio/client-ts/issues/313
4502
+ body: { tables, query, fuzziness, prefix, highlight, page },
4503
+ ...pluginOptions
4504
+ });
4505
+ return records;
4506
+ };
4507
+ _getSchemaTables = new WeakSet();
4508
+ getSchemaTables_fn = async function(pluginOptions) {
4509
+ if (__privateGet$1(this, _schemaTables))
4510
+ return __privateGet$1(this, _schemaTables);
4511
+ const { schema } = await getBranchDetails({
4512
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4513
+ ...pluginOptions
4514
+ });
4515
+ __privateSet$1(this, _schemaTables, schema.tables);
4516
+ return schema.tables;
4517
+ };
4518
+
4519
+ function escapeElement(elementRepresentation) {
4520
+ const escaped = elementRepresentation.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
4521
+ return '"' + escaped + '"';
4522
+ }
4523
+ function arrayString(val) {
4524
+ let result = "{";
4525
+ for (let i = 0; i < val.length; i++) {
4526
+ if (i > 0) {
4527
+ result = result + ",";
4528
+ }
4529
+ if (val[i] === null || typeof val[i] === "undefined") {
4530
+ result = result + "NULL";
4531
+ } else if (Array.isArray(val[i])) {
4532
+ result = result + arrayString(val[i]);
4533
+ } else if (val[i] instanceof Buffer) {
4534
+ result += "\\\\x" + val[i].toString("hex");
4535
+ } else {
4536
+ result += escapeElement(prepareValue(val[i]));
4537
+ }
4538
+ }
4539
+ result = result + "}";
4540
+ return result;
4541
+ }
4542
+ function prepareValue(value) {
4543
+ if (!isDefined(value))
4544
+ return null;
4545
+ if (value instanceof Date) {
4546
+ return value.toISOString();
4547
+ }
4548
+ if (Array.isArray(value)) {
4549
+ return arrayString(value);
4550
+ }
4551
+ if (isObject(value)) {
4552
+ return JSON.stringify(value);
4553
+ }
4554
+ try {
4555
+ return value.toString();
4556
+ } catch (e) {
4557
+ return value;
4558
+ }
4559
+ }
4560
+ function prepareParams(param1, param2) {
4561
+ if (isString(param1)) {
4562
+ return { statement: param1, params: param2?.map((value) => prepareValue(value)) };
4563
+ }
4564
+ if (isStringArray(param1)) {
4565
+ const statement = param1.reduce((acc, curr, index) => {
4566
+ return acc + curr + (index < (param2?.length ?? 0) ? "$" + (index + 1) : "");
4567
+ }, "");
4568
+ return { statement, params: param2?.map((value) => prepareValue(value)) };
4569
+ }
4570
+ if (isObject(param1)) {
4571
+ const { statement, params, consistency } = param1;
4572
+ return { statement, params: params?.map((value) => prepareValue(value)), consistency };
4573
+ }
4574
+ throw new Error("Invalid query");
4575
+ }
4576
+
4577
+ class SQLPlugin extends XataPlugin {
4578
+ build(pluginOptions) {
4579
+ return async (param1, ...param2) => {
4580
+ const { statement, params, consistency } = prepareParams(param1, param2);
4581
+ const { records, warning } = await sqlQuery({
4582
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4583
+ body: { statement, params, consistency },
4584
+ ...pluginOptions
4585
+ });
4586
+ return { records, warning };
4587
+ };
4588
+ }
4589
+ }
4590
+
4591
+ class TransactionPlugin extends XataPlugin {
4592
+ build(pluginOptions) {
4593
+ return {
4594
+ run: async (operations) => {
4595
+ const response = await branchTransaction({
4596
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", region: "{region}" },
4597
+ body: { operations },
4598
+ ...pluginOptions
4599
+ });
4600
+ return response;
4601
+ }
4602
+ };
4603
+ }
4604
+ }
4605
+
4606
+ var __defProp$2 = Object.defineProperty;
4607
+ var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4608
+ var __publicField$2 = (obj, key, value) => {
4609
+ __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
4610
+ return value;
4611
+ };
4612
+ var __accessCheck = (obj, member, msg) => {
4613
+ if (!member.has(obj))
4614
+ throw TypeError("Cannot " + msg);
4615
+ };
4616
+ var __privateGet = (obj, member, getter) => {
4617
+ __accessCheck(obj, member, "read from private field");
4618
+ return getter ? getter.call(obj) : member.get(obj);
4619
+ };
4620
+ var __privateAdd = (obj, member, value) => {
4621
+ if (member.has(obj))
4622
+ throw TypeError("Cannot add the same private member more than once");
4623
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
4624
+ };
4625
+ var __privateSet = (obj, member, value, setter) => {
4626
+ __accessCheck(obj, member, "write to private field");
4627
+ setter ? setter.call(obj, value) : member.set(obj, value);
4628
+ return value;
4629
+ };
4630
+ var __privateMethod = (obj, member, method) => {
4631
+ __accessCheck(obj, member, "access private method");
4632
+ return method;
4633
+ };
4634
+ const buildClient = (plugins) => {
4635
+ var _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _a;
4636
+ return _a = class {
4637
+ constructor(options = {}, schemaTables) {
4638
+ __privateAdd(this, _parseOptions);
4639
+ __privateAdd(this, _getFetchProps);
4640
+ __privateAdd(this, _options, void 0);
4641
+ __publicField$2(this, "db");
4642
+ __publicField$2(this, "search");
4643
+ __publicField$2(this, "transactions");
4644
+ __publicField$2(this, "sql");
4645
+ __publicField$2(this, "files");
4646
+ const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
4647
+ __privateSet(this, _options, safeOptions);
4648
+ const pluginOptions = {
4649
+ ...__privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
4650
+ cache: safeOptions.cache,
4651
+ host: safeOptions.host
4652
+ };
4653
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
4654
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
4655
+ const transactions = new TransactionPlugin().build(pluginOptions);
4656
+ const sql = new SQLPlugin().build(pluginOptions);
4657
+ const files = new FilesPlugin().build(pluginOptions);
4658
+ this.db = db;
4659
+ this.search = search;
4660
+ this.transactions = transactions;
4661
+ this.sql = sql;
4662
+ this.files = files;
4663
+ for (const [key, namespace] of Object.entries(plugins ?? {})) {
4664
+ if (namespace === void 0)
4665
+ continue;
4666
+ this[key] = namespace.build(pluginOptions);
4667
+ }
4668
+ }
4669
+ async getConfig() {
4670
+ const databaseURL = __privateGet(this, _options).databaseURL;
4671
+ const branch = __privateGet(this, _options).branch;
4672
+ return { databaseURL, branch };
4673
+ }
4674
+ }, _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
4675
+ const enableBrowser = options?.enableBrowser ?? getEnableBrowserVariable() ?? false;
4676
+ const isBrowser = typeof window !== "undefined" && typeof Deno === "undefined";
4677
+ if (isBrowser && !enableBrowser) {
4678
+ throw new Error(
4679
+ "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."
4680
+ );
4681
+ }
4682
+ const fetch = getFetchImplementation(options?.fetch);
4683
+ const databaseURL = options?.databaseURL || getDatabaseURL();
4684
+ const apiKey = options?.apiKey || getAPIKey();
4685
+ const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
4686
+ const trace = options?.trace ?? defaultTrace;
4687
+ const clientName = options?.clientName;
4688
+ const host = options?.host ?? "production";
4689
+ const xataAgentExtra = options?.xataAgentExtra;
4690
+ if (!apiKey) {
4691
+ throw new Error("Option apiKey is required");
4692
+ }
4693
+ if (!databaseURL) {
4694
+ throw new Error("Option databaseURL is required");
4695
+ }
4696
+ const envBranch = getBranch();
4697
+ const previewBranch = getPreviewBranch();
4698
+ const branch = options?.branch || previewBranch || envBranch || "main";
4699
+ if (!!previewBranch && branch !== previewBranch) {
4700
+ console.warn(
4701
+ `Ignoring preview branch ${previewBranch} because branch option was passed to the client constructor with value ${branch}`
4702
+ );
4703
+ } else if (!!envBranch && branch !== envBranch) {
4704
+ console.warn(
4705
+ `Ignoring branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
4706
+ );
4707
+ } else if (!!previewBranch && !!envBranch && previewBranch !== envBranch) {
4708
+ console.warn(
4709
+ `Ignoring preview branch ${previewBranch} and branch ${envBranch} because branch option was passed to the client constructor with value ${branch}`
4710
+ );
4711
+ } else if (!previewBranch && !envBranch && options?.branch === void 0) {
4712
+ console.warn(
4713
+ `No branch was passed to the client constructor. Using default branch ${branch}. You can set the branch with the environment variable XATA_BRANCH or by passing the branch option to the client constructor.`
4714
+ );
4715
+ }
4716
+ return {
4717
+ fetch,
4718
+ databaseURL,
4719
+ apiKey,
4720
+ branch,
4721
+ cache,
4722
+ trace,
4723
+ host,
4724
+ clientID: generateUUID(),
4725
+ enableBrowser,
4726
+ clientName,
4727
+ xataAgentExtra
4728
+ };
4729
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = function({
4730
+ fetch,
4731
+ apiKey,
4732
+ databaseURL,
4733
+ branch,
4734
+ trace,
4735
+ clientID,
4736
+ clientName,
4737
+ xataAgentExtra
4738
+ }) {
4739
+ return {
4740
+ fetch,
4741
+ apiKey,
4742
+ apiUrl: "",
4743
+ // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
4744
+ workspacesApiUrl: (path, params) => {
4745
+ const hasBranch = params.dbBranchName ?? params.branch;
4746
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch !== void 0 ? `:${branch}` : "");
4747
+ return databaseURL + newPath;
4748
+ },
4749
+ trace,
4750
+ clientID,
4751
+ clientName,
4752
+ xataAgentExtra
4753
+ };
4754
+ }, _a;
4755
+ };
4756
+ class BaseClient extends buildClient() {
4757
+ }
4758
+
4759
+ var __defProp$1 = Object.defineProperty;
4760
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4761
+ var __publicField$1 = (obj, key, value) => {
4762
+ __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
4763
+ return value;
4764
+ };
4765
+ const META = "__";
4766
+ const VALUE = "___";
4767
+ class Serializer {
4768
+ constructor() {
4769
+ __publicField$1(this, "classes", {});
4770
+ }
4771
+ add(clazz) {
4772
+ this.classes[clazz.name] = clazz;
4773
+ }
4774
+ toJSON(data) {
4775
+ function visit(obj) {
4776
+ if (Array.isArray(obj))
4777
+ return obj.map(visit);
4778
+ const type = typeof obj;
4779
+ if (type === "undefined")
4780
+ return { [META]: "undefined" };
4781
+ if (type === "bigint")
4782
+ return { [META]: "bigint", [VALUE]: obj.toString() };
4783
+ if (obj === null || type !== "object")
4784
+ return obj;
4785
+ const constructor = obj.constructor;
4786
+ const o = { [META]: constructor.name };
4787
+ for (const [key, value] of Object.entries(obj)) {
4788
+ o[key] = visit(value);
4789
+ }
4790
+ if (constructor === Date)
4791
+ o[VALUE] = obj.toISOString();
4792
+ if (constructor === Map)
4793
+ o[VALUE] = Object.fromEntries(obj);
4794
+ if (constructor === Set)
4795
+ o[VALUE] = [...obj];
4796
+ return o;
4797
+ }
4798
+ return JSON.stringify(visit(data));
4799
+ }
4800
+ fromJSON(json) {
4801
+ return JSON.parse(json, (key, value) => {
4802
+ if (value && typeof value === "object" && !Array.isArray(value)) {
4803
+ const { [META]: clazz, [VALUE]: val, ...rest } = value;
4804
+ const constructor = this.classes[clazz];
4805
+ if (constructor) {
4806
+ return Object.assign(Object.create(constructor.prototype), rest);
4807
+ }
4808
+ if (clazz === "Date")
4809
+ return new Date(val);
4810
+ if (clazz === "Set")
4811
+ return new Set(val);
4812
+ if (clazz === "Map")
4813
+ return new Map(Object.entries(val));
4814
+ if (clazz === "bigint")
4815
+ return BigInt(val);
4816
+ if (clazz === "undefined")
4817
+ return void 0;
4818
+ return rest;
4819
+ }
4820
+ return value;
4821
+ });
4822
+ }
4823
+ }
4824
+ const defaultSerializer = new Serializer();
4825
+ const serialize = (data) => {
4826
+ return defaultSerializer.toJSON(data);
4827
+ };
4828
+ const deserialize = (json) => {
4829
+ return defaultSerializer.fromJSON(json);
4830
+ };
4831
+
4832
+ function buildWorkerRunner(config) {
4833
+ return function xataWorker(name, worker) {
4834
+ return async (...args) => {
4835
+ const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
4836
+ const result = await fetch(url, {
4837
+ method: "POST",
4838
+ headers: { "Content-Type": "application/json" },
4839
+ body: serialize({ args })
4840
+ });
4841
+ const text = await result.text();
4842
+ return deserialize(text);
4843
+ };
4844
+ };
4845
+ }
4846
+
4847
+ var __defProp = Object.defineProperty;
4848
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4849
+ var __publicField = (obj, key, value) => {
4850
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4851
+ return value;
4852
+ };
4853
+ class XataError extends Error {
4854
+ constructor(message, status) {
4855
+ super(message);
4856
+ __publicField(this, "status");
4857
+ this.status = status;
4858
+ }
4859
+ }
4860
+
4861
+ exports.BaseClient = BaseClient;
4862
+ exports.FetcherError = FetcherError;
4863
+ exports.FilesPlugin = FilesPlugin;
4864
+ exports.Operations = operationsByTag;
4865
+ exports.PAGINATION_DEFAULT_OFFSET = PAGINATION_DEFAULT_OFFSET;
4866
+ exports.PAGINATION_DEFAULT_SIZE = PAGINATION_DEFAULT_SIZE;
4867
+ exports.PAGINATION_MAX_OFFSET = PAGINATION_MAX_OFFSET;
4868
+ exports.PAGINATION_MAX_SIZE = PAGINATION_MAX_SIZE;
4869
+ exports.Page = Page;
4870
+ exports.Query = Query;
4871
+ exports.RecordArray = RecordArray;
4872
+ exports.RecordColumnTypes = RecordColumnTypes;
4873
+ exports.Repository = Repository;
4874
+ exports.RestRepository = RestRepository;
4875
+ exports.SQLPlugin = SQLPlugin;
4876
+ exports.SchemaPlugin = SchemaPlugin;
4877
+ exports.SearchPlugin = SearchPlugin;
4878
+ exports.Serializer = Serializer;
4879
+ exports.SimpleCache = SimpleCache;
4880
+ exports.XataApiClient = XataApiClient;
4881
+ exports.XataApiPlugin = XataApiPlugin;
4882
+ exports.XataError = XataError;
4883
+ exports.XataFile = XataFile;
4884
+ exports.XataPlugin = XataPlugin;
4885
+ exports.acceptWorkspaceMemberInvite = acceptWorkspaceMemberInvite;
4886
+ exports.addGitBranchesEntry = addGitBranchesEntry;
4887
+ exports.addTableColumn = addTableColumn;
4888
+ exports.aggregateTable = aggregateTable;
4889
+ exports.applyBranchSchemaEdit = applyBranchSchemaEdit;
4890
+ exports.askTable = askTable;
4891
+ exports.askTableSession = askTableSession;
4892
+ exports.branchTransaction = branchTransaction;
4893
+ exports.buildClient = buildClient;
4894
+ exports.buildPreviewBranchName = buildPreviewBranchName;
4895
+ exports.buildProviderString = buildProviderString;
4896
+ exports.buildWorkerRunner = buildWorkerRunner;
4897
+ exports.bulkInsertTableRecords = bulkInsertTableRecords;
4898
+ exports.cancelWorkspaceMemberInvite = cancelWorkspaceMemberInvite;
4899
+ exports.compareBranchSchemas = compareBranchSchemas;
4900
+ exports.compareBranchWithUserSchema = compareBranchWithUserSchema;
4901
+ exports.compareMigrationRequest = compareMigrationRequest;
4902
+ exports.contains = contains;
4903
+ exports.copyBranch = copyBranch;
4904
+ exports.createBranch = createBranch;
4905
+ exports.createDatabase = createDatabase;
4906
+ exports.createMigrationRequest = createMigrationRequest;
4907
+ exports.createTable = createTable;
4908
+ exports.createUserAPIKey = createUserAPIKey;
4909
+ exports.createWorkspace = createWorkspace;
4910
+ exports.deleteBranch = deleteBranch;
4911
+ exports.deleteColumn = deleteColumn;
4912
+ exports.deleteDatabase = deleteDatabase;
4913
+ exports.deleteDatabaseGithubSettings = deleteDatabaseGithubSettings;
4914
+ exports.deleteFile = deleteFile;
4915
+ exports.deleteFileItem = deleteFileItem;
4916
+ exports.deleteOAuthAccessToken = deleteOAuthAccessToken;
4917
+ exports.deleteRecord = deleteRecord;
4918
+ exports.deleteTable = deleteTable;
4919
+ exports.deleteUser = deleteUser;
4920
+ exports.deleteUserAPIKey = deleteUserAPIKey;
4921
+ exports.deleteUserOAuthClient = deleteUserOAuthClient;
4922
+ exports.deleteWorkspace = deleteWorkspace;
4923
+ exports.deserialize = deserialize;
4924
+ exports.endsWith = endsWith;
4925
+ exports.equals = equals;
4926
+ exports.executeBranchMigrationPlan = executeBranchMigrationPlan;
4927
+ exports.exists = exists;
4928
+ exports.fileAccess = fileAccess;
4929
+ exports.ge = ge;
4930
+ exports.getAPIKey = getAPIKey;
4931
+ exports.getAuthorizationCode = getAuthorizationCode;
4932
+ exports.getBranch = getBranch;
4933
+ exports.getBranchDetails = getBranchDetails;
4934
+ exports.getBranchList = getBranchList;
4935
+ exports.getBranchMetadata = getBranchMetadata;
4936
+ exports.getBranchMigrationHistory = getBranchMigrationHistory;
4937
+ exports.getBranchMigrationPlan = getBranchMigrationPlan;
4938
+ exports.getBranchSchemaHistory = getBranchSchemaHistory;
4939
+ exports.getBranchStats = getBranchStats;
4940
+ exports.getColumn = getColumn;
4941
+ exports.getDatabaseGithubSettings = getDatabaseGithubSettings;
4942
+ exports.getDatabaseList = getDatabaseList;
4943
+ exports.getDatabaseMetadata = getDatabaseMetadata;
4944
+ exports.getDatabaseURL = getDatabaseURL;
4945
+ exports.getFile = getFile;
4946
+ exports.getFileItem = getFileItem;
4947
+ exports.getGitBranchesMapping = getGitBranchesMapping;
4948
+ exports.getHostUrl = getHostUrl;
4949
+ exports.getMigrationRequest = getMigrationRequest;
4950
+ exports.getMigrationRequestIsMerged = getMigrationRequestIsMerged;
4951
+ exports.getPreviewBranch = getPreviewBranch;
4952
+ exports.getRecord = getRecord;
4953
+ exports.getTableColumns = getTableColumns;
4954
+ exports.getTableSchema = getTableSchema;
4955
+ exports.getUser = getUser;
4956
+ exports.getUserAPIKeys = getUserAPIKeys;
4957
+ exports.getUserOAuthAccessTokens = getUserOAuthAccessTokens;
4958
+ exports.getUserOAuthClients = getUserOAuthClients;
4959
+ exports.getWorkspace = getWorkspace;
4960
+ exports.getWorkspaceMembersList = getWorkspaceMembersList;
4961
+ exports.getWorkspacesList = getWorkspacesList;
4962
+ exports.grantAuthorizationCode = grantAuthorizationCode;
4963
+ exports.greaterEquals = greaterEquals;
4964
+ exports.greaterThan = greaterThan;
4965
+ exports.greaterThanEquals = greaterThanEquals;
4966
+ exports.gt = gt;
4967
+ exports.gte = gte;
4968
+ exports.includes = includes;
4969
+ exports.includesAll = includesAll;
4970
+ exports.includesAny = includesAny;
4971
+ exports.includesNone = includesNone;
4972
+ exports.insertRecord = insertRecord;
4973
+ exports.insertRecordWithID = insertRecordWithID;
4974
+ exports.inviteWorkspaceMember = inviteWorkspaceMember;
4975
+ exports.is = is;
4976
+ exports.isCursorPaginationOptions = isCursorPaginationOptions;
4977
+ exports.isHostProviderAlias = isHostProviderAlias;
4978
+ exports.isHostProviderBuilder = isHostProviderBuilder;
4979
+ exports.isIdentifiable = isIdentifiable;
4980
+ exports.isNot = isNot;
4981
+ exports.isValidExpandedColumn = isValidExpandedColumn;
4982
+ exports.isValidSelectableColumns = isValidSelectableColumns;
4983
+ exports.isXataRecord = isXataRecord;
4984
+ exports.le = le;
4985
+ exports.lessEquals = lessEquals;
4986
+ exports.lessThan = lessThan;
4987
+ exports.lessThanEquals = lessThanEquals;
4988
+ exports.listMigrationRequestsCommits = listMigrationRequestsCommits;
4989
+ exports.listRegions = listRegions;
4990
+ exports.lt = lt;
4991
+ exports.lte = lte;
4992
+ exports.mergeMigrationRequest = mergeMigrationRequest;
4993
+ exports.notExists = notExists;
4994
+ exports.operationsByTag = operationsByTag;
4995
+ exports.parseProviderString = parseProviderString;
4996
+ exports.parseWorkspacesUrlParts = parseWorkspacesUrlParts;
4997
+ exports.pattern = pattern;
4998
+ exports.previewBranchSchemaEdit = previewBranchSchemaEdit;
4999
+ exports.pushBranchMigrations = pushBranchMigrations;
5000
+ exports.putFile = putFile;
5001
+ exports.putFileItem = putFileItem;
5002
+ exports.queryMigrationRequests = queryMigrationRequests;
5003
+ exports.queryTable = queryTable;
5004
+ exports.removeGitBranchesEntry = removeGitBranchesEntry;
5005
+ exports.removeWorkspaceMember = removeWorkspaceMember;
5006
+ exports.renameDatabase = renameDatabase;
5007
+ exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite;
5008
+ exports.resolveBranch = resolveBranch;
5009
+ exports.searchBranch = searchBranch;
5010
+ exports.searchTable = searchTable;
5011
+ exports.serialize = serialize;
5012
+ exports.setTableSchema = setTableSchema;
5013
+ exports.sqlQuery = sqlQuery;
5014
+ exports.startsWith = startsWith;
5015
+ exports.summarizeTable = summarizeTable;
5016
+ exports.transformImage = transformImage;
5017
+ exports.updateBranchMetadata = updateBranchMetadata;
5018
+ exports.updateBranchSchema = updateBranchSchema;
5019
+ exports.updateColumn = updateColumn;
5020
+ exports.updateDatabaseGithubSettings = updateDatabaseGithubSettings;
5021
+ exports.updateDatabaseMetadata = updateDatabaseMetadata;
5022
+ exports.updateMigrationRequest = updateMigrationRequest;
5023
+ exports.updateOAuthAccessToken = updateOAuthAccessToken;
5024
+ exports.updateRecordWithID = updateRecordWithID;
5025
+ exports.updateTable = updateTable;
5026
+ exports.updateUser = updateUser;
5027
+ exports.updateWorkspace = updateWorkspace;
5028
+ exports.updateWorkspaceMemberInvite = updateWorkspaceMemberInvite;
5029
+ exports.updateWorkspaceMemberRole = updateWorkspaceMemberRole;
5030
+ exports.upsertRecordWithID = upsertRecordWithID;
5031
+ exports.vectorSearchTable = vectorSearchTable;
5032
+ //# sourceMappingURL=index.cjs.map