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