@xata.io/client 0.0.0-alpha.vfb85b8b → 0.0.0-alpha.vfee45b2

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 (69) hide show
  1. package/.eslintrc.cjs +2 -3
  2. package/CHANGELOG.md +84 -0
  3. package/dist/index.cjs +2057 -0
  4. package/dist/index.cjs.map +1 -0
  5. package/dist/index.d.ts +3556 -6
  6. package/dist/index.mjs +1955 -0
  7. package/dist/index.mjs.map +1 -0
  8. package/package.json +9 -5
  9. package/rollup.config.js +29 -0
  10. package/tsconfig.json +6 -4
  11. package/dist/api/client.d.ts +0 -95
  12. package/dist/api/client.js +0 -251
  13. package/dist/api/components.d.ts +0 -1437
  14. package/dist/api/components.js +0 -998
  15. package/dist/api/fetcher.d.ts +0 -40
  16. package/dist/api/fetcher.js +0 -79
  17. package/dist/api/index.d.ts +0 -7
  18. package/dist/api/index.js +0 -21
  19. package/dist/api/parameters.d.ts +0 -16
  20. package/dist/api/parameters.js +0 -2
  21. package/dist/api/providers.d.ts +0 -8
  22. package/dist/api/providers.js +0 -30
  23. package/dist/api/responses.d.ts +0 -50
  24. package/dist/api/responses.js +0 -2
  25. package/dist/api/schemas.d.ts +0 -311
  26. package/dist/api/schemas.js +0 -2
  27. package/dist/client.d.ts +0 -39
  28. package/dist/client.js +0 -124
  29. package/dist/index.js +0 -29
  30. package/dist/namespace.d.ts +0 -7
  31. package/dist/namespace.js +0 -6
  32. package/dist/schema/filters.d.ts +0 -96
  33. package/dist/schema/filters.js +0 -2
  34. package/dist/schema/filters.spec.d.ts +0 -1
  35. package/dist/schema/filters.spec.js +0 -177
  36. package/dist/schema/index.d.ts +0 -21
  37. package/dist/schema/index.js +0 -49
  38. package/dist/schema/operators.d.ts +0 -74
  39. package/dist/schema/operators.js +0 -93
  40. package/dist/schema/pagination.d.ts +0 -83
  41. package/dist/schema/pagination.js +0 -93
  42. package/dist/schema/query.d.ts +0 -118
  43. package/dist/schema/query.js +0 -242
  44. package/dist/schema/record.d.ts +0 -66
  45. package/dist/schema/record.js +0 -13
  46. package/dist/schema/repository.d.ts +0 -134
  47. package/dist/schema/repository.js +0 -284
  48. package/dist/schema/selection.d.ts +0 -25
  49. package/dist/schema/selection.js +0 -2
  50. package/dist/schema/selection.spec.d.ts +0 -1
  51. package/dist/schema/selection.spec.js +0 -204
  52. package/dist/schema/sorting.d.ts +0 -17
  53. package/dist/schema/sorting.js +0 -28
  54. package/dist/schema/sorting.spec.d.ts +0 -1
  55. package/dist/schema/sorting.spec.js +0 -11
  56. package/dist/search/index.d.ts +0 -20
  57. package/dist/search/index.js +0 -30
  58. package/dist/util/branches.d.ts +0 -5
  59. package/dist/util/branches.js +0 -7
  60. package/dist/util/config.d.ts +0 -11
  61. package/dist/util/config.js +0 -121
  62. package/dist/util/environment.d.ts +0 -5
  63. package/dist/util/environment.js +0 -68
  64. package/dist/util/fetch.d.ts +0 -2
  65. package/dist/util/fetch.js +0 -13
  66. package/dist/util/lang.d.ts +0 -5
  67. package/dist/util/lang.js +0 -22
  68. package/dist/util/types.d.ts +0 -25
  69. package/dist/util/types.js +0 -2
package/dist/index.cjs ADDED
@@ -0,0 +1,2057 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ function notEmpty(value) {
6
+ return value !== null && value !== void 0;
7
+ }
8
+ function compact(arr) {
9
+ return arr.filter(notEmpty);
10
+ }
11
+ function isObject(value) {
12
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
13
+ }
14
+ function isDefined(value) {
15
+ return value !== null && value !== void 0;
16
+ }
17
+ function isString(value) {
18
+ return isDefined(value) && typeof value === "string";
19
+ }
20
+ function toBase64(value) {
21
+ try {
22
+ return btoa(value);
23
+ } catch (err) {
24
+ return Buffer.from(value).toString("base64");
25
+ }
26
+ }
27
+
28
+ function getEnvVariable(name) {
29
+ try {
30
+ if (isObject(process) && isString(process?.env?.[name])) {
31
+ return process.env[name];
32
+ }
33
+ } catch (err) {
34
+ }
35
+ try {
36
+ if (isObject(Deno) && isString(Deno?.env?.get(name))) {
37
+ return Deno.env.get(name);
38
+ }
39
+ } catch (err) {
40
+ }
41
+ }
42
+ async function getGitBranch() {
43
+ try {
44
+ if (typeof require === "function") {
45
+ const req = require;
46
+ return req("child_process").execSync("git branch --show-current", { encoding: "utf-8" }).trim();
47
+ }
48
+ } catch (err) {
49
+ }
50
+ try {
51
+ if (isObject(Deno)) {
52
+ const process2 = Deno.run({
53
+ cmd: ["git", "branch", "--show-current"],
54
+ stdout: "piped",
55
+ stderr: "piped"
56
+ });
57
+ return new TextDecoder().decode(await process2.output()).trim();
58
+ }
59
+ } catch (err) {
60
+ }
61
+ }
62
+
63
+ function getAPIKey() {
64
+ try {
65
+ return getEnvVariable("XATA_API_KEY") ?? XATA_API_KEY;
66
+ } catch (err) {
67
+ return void 0;
68
+ }
69
+ }
70
+
71
+ function getFetchImplementation(userFetch) {
72
+ const globalFetch = typeof fetch !== "undefined" ? fetch : void 0;
73
+ const fetchImpl = userFetch ?? globalFetch;
74
+ if (!fetchImpl) {
75
+ throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
76
+ }
77
+ return fetchImpl;
78
+ }
79
+
80
+ class ErrorWithCause extends Error {
81
+ constructor(message, options) {
82
+ super(message, options);
83
+ }
84
+ }
85
+ class FetcherError extends ErrorWithCause {
86
+ constructor(status, data) {
87
+ super(getMessage(data));
88
+ this.status = status;
89
+ this.errors = isBulkError(data) ? data.errors : void 0;
90
+ if (data instanceof Error) {
91
+ this.stack = data.stack;
92
+ this.cause = data.cause;
93
+ }
94
+ }
95
+ }
96
+ function isBulkError(error) {
97
+ return isObject(error) && Array.isArray(error.errors);
98
+ }
99
+ function isErrorWithMessage(error) {
100
+ return isObject(error) && isString(error.message);
101
+ }
102
+ function getMessage(data) {
103
+ if (data instanceof Error) {
104
+ return data.message;
105
+ } else if (isString(data)) {
106
+ return data;
107
+ } else if (isErrorWithMessage(data)) {
108
+ return data.message;
109
+ } else if (isBulkError(data)) {
110
+ return "Bulk operation failed";
111
+ } else {
112
+ return "Unexpected error";
113
+ }
114
+ }
115
+
116
+ const resolveUrl = (url, queryParams = {}, pathParams = {}) => {
117
+ const query = new URLSearchParams(queryParams).toString();
118
+ const queryString = query.length > 0 ? `?${query}` : "";
119
+ return url.replace(/\{\w*\}/g, (key) => pathParams[key.slice(1, -1)]) + queryString;
120
+ };
121
+ function buildBaseUrl({
122
+ path,
123
+ workspacesApiUrl,
124
+ apiUrl,
125
+ pathParams
126
+ }) {
127
+ if (!pathParams?.workspace)
128
+ return `${apiUrl}${path}`;
129
+ const url = typeof workspacesApiUrl === "string" ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams);
130
+ return url.replace("{workspaceId}", pathParams.workspace);
131
+ }
132
+ function hostHeader(url) {
133
+ const pattern = /.*:\/\/(?<host>[^/]+).*/;
134
+ const { groups } = pattern.exec(url) ?? {};
135
+ return groups?.host ? { Host: groups.host } : {};
136
+ }
137
+ async function fetch$1({
138
+ url: path,
139
+ method,
140
+ body,
141
+ headers,
142
+ pathParams,
143
+ queryParams,
144
+ fetchImpl,
145
+ apiKey,
146
+ apiUrl,
147
+ workspacesApiUrl
148
+ }) {
149
+ const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl });
150
+ const fullUrl = resolveUrl(baseUrl, queryParams, pathParams);
151
+ const url = fullUrl.includes("localhost") ? fullUrl.replace(/^[^.]+\./, "http://") : fullUrl;
152
+ const response = await fetchImpl(url, {
153
+ method: method.toUpperCase(),
154
+ body: body ? JSON.stringify(body) : void 0,
155
+ headers: {
156
+ "Content-Type": "application/json",
157
+ ...headers,
158
+ ...hostHeader(fullUrl),
159
+ Authorization: `Bearer ${apiKey}`
160
+ }
161
+ });
162
+ if (response.status === 204) {
163
+ return {};
164
+ }
165
+ try {
166
+ const jsonResponse = await response.json();
167
+ if (response.ok) {
168
+ return jsonResponse;
169
+ }
170
+ throw new FetcherError(response.status, jsonResponse);
171
+ } catch (error) {
172
+ throw new FetcherError(response.status, error);
173
+ }
174
+ }
175
+
176
+ const getUser = (variables) => fetch$1({ url: "/user", method: "get", ...variables });
177
+ const updateUser = (variables) => fetch$1({ url: "/user", method: "put", ...variables });
178
+ const deleteUser = (variables) => fetch$1({ url: "/user", method: "delete", ...variables });
179
+ const getUserAPIKeys = (variables) => fetch$1({
180
+ url: "/user/keys",
181
+ method: "get",
182
+ ...variables
183
+ });
184
+ const createUserAPIKey = (variables) => fetch$1({
185
+ url: "/user/keys/{keyName}",
186
+ method: "post",
187
+ ...variables
188
+ });
189
+ const deleteUserAPIKey = (variables) => fetch$1({
190
+ url: "/user/keys/{keyName}",
191
+ method: "delete",
192
+ ...variables
193
+ });
194
+ const createWorkspace = (variables) => fetch$1({
195
+ url: "/workspaces",
196
+ method: "post",
197
+ ...variables
198
+ });
199
+ const getWorkspacesList = (variables) => fetch$1({
200
+ url: "/workspaces",
201
+ method: "get",
202
+ ...variables
203
+ });
204
+ const getWorkspace = (variables) => fetch$1({
205
+ url: "/workspaces/{workspaceId}",
206
+ method: "get",
207
+ ...variables
208
+ });
209
+ const updateWorkspace = (variables) => fetch$1({
210
+ url: "/workspaces/{workspaceId}",
211
+ method: "put",
212
+ ...variables
213
+ });
214
+ const deleteWorkspace = (variables) => fetch$1({
215
+ url: "/workspaces/{workspaceId}",
216
+ method: "delete",
217
+ ...variables
218
+ });
219
+ const getWorkspaceMembersList = (variables) => fetch$1({
220
+ url: "/workspaces/{workspaceId}/members",
221
+ method: "get",
222
+ ...variables
223
+ });
224
+ const updateWorkspaceMemberRole = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/members/{userId}", method: "put", ...variables });
225
+ const removeWorkspaceMember = (variables) => fetch$1({
226
+ url: "/workspaces/{workspaceId}/members/{userId}",
227
+ method: "delete",
228
+ ...variables
229
+ });
230
+ const inviteWorkspaceMember = (variables) => fetch$1({ url: "/workspaces/{workspaceId}/invites", method: "post", ...variables });
231
+ const cancelWorkspaceMemberInvite = (variables) => fetch$1({
232
+ url: "/workspaces/{workspaceId}/invites/{inviteId}",
233
+ method: "delete",
234
+ ...variables
235
+ });
236
+ const resendWorkspaceMemberInvite = (variables) => fetch$1({
237
+ url: "/workspaces/{workspaceId}/invites/{inviteId}/resend",
238
+ method: "post",
239
+ ...variables
240
+ });
241
+ const acceptWorkspaceMemberInvite = (variables) => fetch$1({
242
+ url: "/workspaces/{workspaceId}/invites/{inviteKey}/accept",
243
+ method: "post",
244
+ ...variables
245
+ });
246
+ const getDatabaseList = (variables) => fetch$1({
247
+ url: "/dbs",
248
+ method: "get",
249
+ ...variables
250
+ });
251
+ const getBranchList = (variables) => fetch$1({
252
+ url: "/dbs/{dbName}",
253
+ method: "get",
254
+ ...variables
255
+ });
256
+ const createDatabase = (variables) => fetch$1({
257
+ url: "/dbs/{dbName}",
258
+ method: "put",
259
+ ...variables
260
+ });
261
+ const deleteDatabase = (variables) => fetch$1({
262
+ url: "/dbs/{dbName}",
263
+ method: "delete",
264
+ ...variables
265
+ });
266
+ const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
267
+ const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
268
+ const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
269
+ const resolveBranch = (variables) => fetch$1({
270
+ url: "/dbs/{dbName}/resolveBranch",
271
+ method: "get",
272
+ ...variables
273
+ });
274
+ const getBranchDetails = (variables) => fetch$1({
275
+ url: "/db/{dbBranchName}",
276
+ method: "get",
277
+ ...variables
278
+ });
279
+ const createBranch = (variables) => fetch$1({
280
+ url: "/db/{dbBranchName}",
281
+ method: "put",
282
+ ...variables
283
+ });
284
+ const deleteBranch = (variables) => fetch$1({
285
+ url: "/db/{dbBranchName}",
286
+ method: "delete",
287
+ ...variables
288
+ });
289
+ const updateBranchMetadata = (variables) => fetch$1({
290
+ url: "/db/{dbBranchName}/metadata",
291
+ method: "put",
292
+ ...variables
293
+ });
294
+ const getBranchMetadata = (variables) => fetch$1({
295
+ url: "/db/{dbBranchName}/metadata",
296
+ method: "get",
297
+ ...variables
298
+ });
299
+ const getBranchMigrationHistory = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations", method: "get", ...variables });
300
+ const executeBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/execute", method: "post", ...variables });
301
+ const getBranchMigrationPlan = (variables) => fetch$1({ url: "/db/{dbBranchName}/migrations/plan", method: "post", ...variables });
302
+ const getBranchStats = (variables) => fetch$1({
303
+ url: "/db/{dbBranchName}/stats",
304
+ method: "get",
305
+ ...variables
306
+ });
307
+ const createTable = (variables) => fetch$1({
308
+ url: "/db/{dbBranchName}/tables/{tableName}",
309
+ method: "put",
310
+ ...variables
311
+ });
312
+ const deleteTable = (variables) => fetch$1({
313
+ url: "/db/{dbBranchName}/tables/{tableName}",
314
+ method: "delete",
315
+ ...variables
316
+ });
317
+ const updateTable = (variables) => fetch$1({
318
+ url: "/db/{dbBranchName}/tables/{tableName}",
319
+ method: "patch",
320
+ ...variables
321
+ });
322
+ const getTableSchema = (variables) => fetch$1({
323
+ url: "/db/{dbBranchName}/tables/{tableName}/schema",
324
+ method: "get",
325
+ ...variables
326
+ });
327
+ const setTableSchema = (variables) => fetch$1({
328
+ url: "/db/{dbBranchName}/tables/{tableName}/schema",
329
+ method: "put",
330
+ ...variables
331
+ });
332
+ const getTableColumns = (variables) => fetch$1({
333
+ url: "/db/{dbBranchName}/tables/{tableName}/columns",
334
+ method: "get",
335
+ ...variables
336
+ });
337
+ const addTableColumn = (variables) => fetch$1({
338
+ url: "/db/{dbBranchName}/tables/{tableName}/columns",
339
+ method: "post",
340
+ ...variables
341
+ });
342
+ const getColumn = (variables) => fetch$1({
343
+ url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
344
+ method: "get",
345
+ ...variables
346
+ });
347
+ const deleteColumn = (variables) => fetch$1({
348
+ url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
349
+ method: "delete",
350
+ ...variables
351
+ });
352
+ const updateColumn = (variables) => fetch$1({
353
+ url: "/db/{dbBranchName}/tables/{tableName}/columns/{columnName}",
354
+ method: "patch",
355
+ ...variables
356
+ });
357
+ const insertRecord = (variables) => fetch$1({
358
+ url: "/db/{dbBranchName}/tables/{tableName}/data",
359
+ method: "post",
360
+ ...variables
361
+ });
362
+ const insertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables });
363
+ const updateRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables });
364
+ const upsertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables });
365
+ const deleteRecord = (variables) => fetch$1({
366
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
367
+ method: "delete",
368
+ ...variables
369
+ });
370
+ const getRecord = (variables) => fetch$1({
371
+ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}",
372
+ method: "get",
373
+ ...variables
374
+ });
375
+ const bulkInsertTableRecords = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/bulk", method: "post", ...variables });
376
+ const queryTable = (variables) => fetch$1({
377
+ url: "/db/{dbBranchName}/tables/{tableName}/query",
378
+ method: "post",
379
+ ...variables
380
+ });
381
+ const searchTable = (variables) => fetch$1({
382
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
383
+ method: "post",
384
+ ...variables
385
+ });
386
+ const searchBranch = (variables) => fetch$1({
387
+ url: "/db/{dbBranchName}/search",
388
+ method: "post",
389
+ ...variables
390
+ });
391
+ const operationsByTag = {
392
+ users: { getUser, updateUser, deleteUser, getUserAPIKeys, createUserAPIKey, deleteUserAPIKey },
393
+ workspaces: {
394
+ createWorkspace,
395
+ getWorkspacesList,
396
+ getWorkspace,
397
+ updateWorkspace,
398
+ deleteWorkspace,
399
+ getWorkspaceMembersList,
400
+ updateWorkspaceMemberRole,
401
+ removeWorkspaceMember,
402
+ inviteWorkspaceMember,
403
+ cancelWorkspaceMemberInvite,
404
+ resendWorkspaceMemberInvite,
405
+ acceptWorkspaceMemberInvite
406
+ },
407
+ database: {
408
+ getDatabaseList,
409
+ createDatabase,
410
+ deleteDatabase,
411
+ getGitBranchesMapping,
412
+ addGitBranchesEntry,
413
+ removeGitBranchesEntry,
414
+ resolveBranch
415
+ },
416
+ branch: {
417
+ getBranchList,
418
+ getBranchDetails,
419
+ createBranch,
420
+ deleteBranch,
421
+ updateBranchMetadata,
422
+ getBranchMetadata,
423
+ getBranchMigrationHistory,
424
+ executeBranchMigrationPlan,
425
+ getBranchMigrationPlan,
426
+ getBranchStats
427
+ },
428
+ table: {
429
+ createTable,
430
+ deleteTable,
431
+ updateTable,
432
+ getTableSchema,
433
+ setTableSchema,
434
+ getTableColumns,
435
+ addTableColumn,
436
+ getColumn,
437
+ deleteColumn,
438
+ updateColumn
439
+ },
440
+ records: {
441
+ insertRecord,
442
+ insertRecordWithID,
443
+ updateRecordWithID,
444
+ upsertRecordWithID,
445
+ deleteRecord,
446
+ getRecord,
447
+ bulkInsertTableRecords,
448
+ queryTable,
449
+ searchTable,
450
+ searchBranch
451
+ }
452
+ };
453
+
454
+ function getHostUrl(provider, type) {
455
+ if (isValidAlias(provider)) {
456
+ return providers[provider][type];
457
+ } else if (isValidBuilder(provider)) {
458
+ return provider[type];
459
+ }
460
+ throw new Error("Invalid API provider");
461
+ }
462
+ const providers = {
463
+ production: {
464
+ main: "https://api.xata.io",
465
+ workspaces: "https://{workspaceId}.xata.sh"
466
+ },
467
+ staging: {
468
+ main: "https://staging.xatabase.co",
469
+ workspaces: "https://{workspaceId}.staging.xatabase.co"
470
+ }
471
+ };
472
+ function isValidAlias(alias) {
473
+ return isString(alias) && Object.keys(providers).includes(alias);
474
+ }
475
+ function isValidBuilder(builder) {
476
+ return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
477
+ }
478
+
479
+ var __accessCheck$7 = (obj, member, msg) => {
480
+ if (!member.has(obj))
481
+ throw TypeError("Cannot " + msg);
482
+ };
483
+ var __privateGet$7 = (obj, member, getter) => {
484
+ __accessCheck$7(obj, member, "read from private field");
485
+ return getter ? getter.call(obj) : member.get(obj);
486
+ };
487
+ var __privateAdd$7 = (obj, member, value) => {
488
+ if (member.has(obj))
489
+ throw TypeError("Cannot add the same private member more than once");
490
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
491
+ };
492
+ var __privateSet$6 = (obj, member, value, setter) => {
493
+ __accessCheck$7(obj, member, "write to private field");
494
+ setter ? setter.call(obj, value) : member.set(obj, value);
495
+ return value;
496
+ };
497
+ var _extraProps, _namespaces;
498
+ class XataApiClient {
499
+ constructor(options = {}) {
500
+ __privateAdd$7(this, _extraProps, void 0);
501
+ __privateAdd$7(this, _namespaces, {});
502
+ const provider = options.host ?? "production";
503
+ const apiKey = options?.apiKey ?? getAPIKey();
504
+ if (!apiKey) {
505
+ throw new Error("Could not resolve a valid apiKey");
506
+ }
507
+ __privateSet$6(this, _extraProps, {
508
+ apiUrl: getHostUrl(provider, "main"),
509
+ workspacesApiUrl: getHostUrl(provider, "workspaces"),
510
+ fetchImpl: getFetchImplementation(options.fetch),
511
+ apiKey
512
+ });
513
+ }
514
+ get user() {
515
+ if (!__privateGet$7(this, _namespaces).user)
516
+ __privateGet$7(this, _namespaces).user = new UserApi(__privateGet$7(this, _extraProps));
517
+ return __privateGet$7(this, _namespaces).user;
518
+ }
519
+ get workspaces() {
520
+ if (!__privateGet$7(this, _namespaces).workspaces)
521
+ __privateGet$7(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$7(this, _extraProps));
522
+ return __privateGet$7(this, _namespaces).workspaces;
523
+ }
524
+ get databases() {
525
+ if (!__privateGet$7(this, _namespaces).databases)
526
+ __privateGet$7(this, _namespaces).databases = new DatabaseApi(__privateGet$7(this, _extraProps));
527
+ return __privateGet$7(this, _namespaces).databases;
528
+ }
529
+ get branches() {
530
+ if (!__privateGet$7(this, _namespaces).branches)
531
+ __privateGet$7(this, _namespaces).branches = new BranchApi(__privateGet$7(this, _extraProps));
532
+ return __privateGet$7(this, _namespaces).branches;
533
+ }
534
+ get tables() {
535
+ if (!__privateGet$7(this, _namespaces).tables)
536
+ __privateGet$7(this, _namespaces).tables = new TableApi(__privateGet$7(this, _extraProps));
537
+ return __privateGet$7(this, _namespaces).tables;
538
+ }
539
+ get records() {
540
+ if (!__privateGet$7(this, _namespaces).records)
541
+ __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
542
+ return __privateGet$7(this, _namespaces).records;
543
+ }
544
+ }
545
+ _extraProps = new WeakMap();
546
+ _namespaces = new WeakMap();
547
+ class UserApi {
548
+ constructor(extraProps) {
549
+ this.extraProps = extraProps;
550
+ }
551
+ getUser() {
552
+ return operationsByTag.users.getUser({ ...this.extraProps });
553
+ }
554
+ updateUser(user) {
555
+ return operationsByTag.users.updateUser({ body: user, ...this.extraProps });
556
+ }
557
+ deleteUser() {
558
+ return operationsByTag.users.deleteUser({ ...this.extraProps });
559
+ }
560
+ getUserAPIKeys() {
561
+ return operationsByTag.users.getUserAPIKeys({ ...this.extraProps });
562
+ }
563
+ createUserAPIKey(keyName) {
564
+ return operationsByTag.users.createUserAPIKey({
565
+ pathParams: { keyName },
566
+ ...this.extraProps
567
+ });
568
+ }
569
+ deleteUserAPIKey(keyName) {
570
+ return operationsByTag.users.deleteUserAPIKey({
571
+ pathParams: { keyName },
572
+ ...this.extraProps
573
+ });
574
+ }
575
+ }
576
+ class WorkspaceApi {
577
+ constructor(extraProps) {
578
+ this.extraProps = extraProps;
579
+ }
580
+ createWorkspace(workspaceMeta) {
581
+ return operationsByTag.workspaces.createWorkspace({
582
+ body: workspaceMeta,
583
+ ...this.extraProps
584
+ });
585
+ }
586
+ getWorkspacesList() {
587
+ return operationsByTag.workspaces.getWorkspacesList({ ...this.extraProps });
588
+ }
589
+ getWorkspace(workspaceId) {
590
+ return operationsByTag.workspaces.getWorkspace({
591
+ pathParams: { workspaceId },
592
+ ...this.extraProps
593
+ });
594
+ }
595
+ updateWorkspace(workspaceId, workspaceMeta) {
596
+ return operationsByTag.workspaces.updateWorkspace({
597
+ pathParams: { workspaceId },
598
+ body: workspaceMeta,
599
+ ...this.extraProps
600
+ });
601
+ }
602
+ deleteWorkspace(workspaceId) {
603
+ return operationsByTag.workspaces.deleteWorkspace({
604
+ pathParams: { workspaceId },
605
+ ...this.extraProps
606
+ });
607
+ }
608
+ getWorkspaceMembersList(workspaceId) {
609
+ return operationsByTag.workspaces.getWorkspaceMembersList({
610
+ pathParams: { workspaceId },
611
+ ...this.extraProps
612
+ });
613
+ }
614
+ updateWorkspaceMemberRole(workspaceId, userId, role) {
615
+ return operationsByTag.workspaces.updateWorkspaceMemberRole({
616
+ pathParams: { workspaceId, userId },
617
+ body: { role },
618
+ ...this.extraProps
619
+ });
620
+ }
621
+ removeWorkspaceMember(workspaceId, userId) {
622
+ return operationsByTag.workspaces.removeWorkspaceMember({
623
+ pathParams: { workspaceId, userId },
624
+ ...this.extraProps
625
+ });
626
+ }
627
+ inviteWorkspaceMember(workspaceId, email, role) {
628
+ return operationsByTag.workspaces.inviteWorkspaceMember({
629
+ pathParams: { workspaceId },
630
+ body: { email, role },
631
+ ...this.extraProps
632
+ });
633
+ }
634
+ cancelWorkspaceMemberInvite(workspaceId, inviteId) {
635
+ return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
636
+ pathParams: { workspaceId, inviteId },
637
+ ...this.extraProps
638
+ });
639
+ }
640
+ resendWorkspaceMemberInvite(workspaceId, inviteId) {
641
+ return operationsByTag.workspaces.resendWorkspaceMemberInvite({
642
+ pathParams: { workspaceId, inviteId },
643
+ ...this.extraProps
644
+ });
645
+ }
646
+ acceptWorkspaceMemberInvite(workspaceId, inviteKey) {
647
+ return operationsByTag.workspaces.acceptWorkspaceMemberInvite({
648
+ pathParams: { workspaceId, inviteKey },
649
+ ...this.extraProps
650
+ });
651
+ }
652
+ }
653
+ class DatabaseApi {
654
+ constructor(extraProps) {
655
+ this.extraProps = extraProps;
656
+ }
657
+ getDatabaseList(workspace) {
658
+ return operationsByTag.database.getDatabaseList({
659
+ pathParams: { workspace },
660
+ ...this.extraProps
661
+ });
662
+ }
663
+ createDatabase(workspace, dbName, options = {}) {
664
+ return operationsByTag.database.createDatabase({
665
+ pathParams: { workspace, dbName },
666
+ body: options,
667
+ ...this.extraProps
668
+ });
669
+ }
670
+ deleteDatabase(workspace, dbName) {
671
+ return operationsByTag.database.deleteDatabase({
672
+ pathParams: { workspace, dbName },
673
+ ...this.extraProps
674
+ });
675
+ }
676
+ getGitBranchesMapping(workspace, dbName) {
677
+ return operationsByTag.database.getGitBranchesMapping({
678
+ pathParams: { workspace, dbName },
679
+ ...this.extraProps
680
+ });
681
+ }
682
+ addGitBranchesEntry(workspace, dbName, body) {
683
+ return operationsByTag.database.addGitBranchesEntry({
684
+ pathParams: { workspace, dbName },
685
+ body,
686
+ ...this.extraProps
687
+ });
688
+ }
689
+ removeGitBranchesEntry(workspace, dbName, gitBranch) {
690
+ return operationsByTag.database.removeGitBranchesEntry({
691
+ pathParams: { workspace, dbName },
692
+ queryParams: { gitBranch },
693
+ ...this.extraProps
694
+ });
695
+ }
696
+ resolveBranch(workspace, dbName, gitBranch) {
697
+ return operationsByTag.database.resolveBranch({
698
+ pathParams: { workspace, dbName },
699
+ queryParams: { gitBranch },
700
+ ...this.extraProps
701
+ });
702
+ }
703
+ }
704
+ class BranchApi {
705
+ constructor(extraProps) {
706
+ this.extraProps = extraProps;
707
+ }
708
+ getBranchList(workspace, dbName) {
709
+ return operationsByTag.branch.getBranchList({
710
+ pathParams: { workspace, dbName },
711
+ ...this.extraProps
712
+ });
713
+ }
714
+ getBranchDetails(workspace, database, branch) {
715
+ return operationsByTag.branch.getBranchDetails({
716
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
717
+ ...this.extraProps
718
+ });
719
+ }
720
+ createBranch(workspace, database, branch, from, options = {}) {
721
+ return operationsByTag.branch.createBranch({
722
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
723
+ queryParams: isString(from) ? { from } : void 0,
724
+ body: options,
725
+ ...this.extraProps
726
+ });
727
+ }
728
+ deleteBranch(workspace, database, branch) {
729
+ return operationsByTag.branch.deleteBranch({
730
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
731
+ ...this.extraProps
732
+ });
733
+ }
734
+ updateBranchMetadata(workspace, database, branch, metadata = {}) {
735
+ return operationsByTag.branch.updateBranchMetadata({
736
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
737
+ body: metadata,
738
+ ...this.extraProps
739
+ });
740
+ }
741
+ getBranchMetadata(workspace, database, branch) {
742
+ return operationsByTag.branch.getBranchMetadata({
743
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
744
+ ...this.extraProps
745
+ });
746
+ }
747
+ getBranchMigrationHistory(workspace, database, branch, options = {}) {
748
+ return operationsByTag.branch.getBranchMigrationHistory({
749
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
750
+ body: options,
751
+ ...this.extraProps
752
+ });
753
+ }
754
+ executeBranchMigrationPlan(workspace, database, branch, migrationPlan) {
755
+ return operationsByTag.branch.executeBranchMigrationPlan({
756
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
757
+ body: migrationPlan,
758
+ ...this.extraProps
759
+ });
760
+ }
761
+ getBranchMigrationPlan(workspace, database, branch, schema) {
762
+ return operationsByTag.branch.getBranchMigrationPlan({
763
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
764
+ body: schema,
765
+ ...this.extraProps
766
+ });
767
+ }
768
+ getBranchStats(workspace, database, branch) {
769
+ return operationsByTag.branch.getBranchStats({
770
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
771
+ ...this.extraProps
772
+ });
773
+ }
774
+ }
775
+ class TableApi {
776
+ constructor(extraProps) {
777
+ this.extraProps = extraProps;
778
+ }
779
+ createTable(workspace, database, branch, tableName) {
780
+ return operationsByTag.table.createTable({
781
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
782
+ ...this.extraProps
783
+ });
784
+ }
785
+ deleteTable(workspace, database, branch, tableName) {
786
+ return operationsByTag.table.deleteTable({
787
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
788
+ ...this.extraProps
789
+ });
790
+ }
791
+ updateTable(workspace, database, branch, tableName, options) {
792
+ return operationsByTag.table.updateTable({
793
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
794
+ body: options,
795
+ ...this.extraProps
796
+ });
797
+ }
798
+ getTableSchema(workspace, database, branch, tableName) {
799
+ return operationsByTag.table.getTableSchema({
800
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
801
+ ...this.extraProps
802
+ });
803
+ }
804
+ setTableSchema(workspace, database, branch, tableName, options) {
805
+ return operationsByTag.table.setTableSchema({
806
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
807
+ body: options,
808
+ ...this.extraProps
809
+ });
810
+ }
811
+ getTableColumns(workspace, database, branch, tableName) {
812
+ return operationsByTag.table.getTableColumns({
813
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
814
+ ...this.extraProps
815
+ });
816
+ }
817
+ addTableColumn(workspace, database, branch, tableName, column) {
818
+ return operationsByTag.table.addTableColumn({
819
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
820
+ body: column,
821
+ ...this.extraProps
822
+ });
823
+ }
824
+ getColumn(workspace, database, branch, tableName, columnName) {
825
+ return operationsByTag.table.getColumn({
826
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, columnName },
827
+ ...this.extraProps
828
+ });
829
+ }
830
+ deleteColumn(workspace, database, branch, tableName, columnName) {
831
+ return operationsByTag.table.deleteColumn({
832
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, columnName },
833
+ ...this.extraProps
834
+ });
835
+ }
836
+ updateColumn(workspace, database, branch, tableName, columnName, options) {
837
+ return operationsByTag.table.updateColumn({
838
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, columnName },
839
+ body: options,
840
+ ...this.extraProps
841
+ });
842
+ }
843
+ }
844
+ class RecordsApi {
845
+ constructor(extraProps) {
846
+ this.extraProps = extraProps;
847
+ }
848
+ insertRecord(workspace, database, branch, tableName, record) {
849
+ return operationsByTag.records.insertRecord({
850
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
851
+ body: record,
852
+ ...this.extraProps
853
+ });
854
+ }
855
+ insertRecordWithID(workspace, database, branch, tableName, recordId, record, options = {}) {
856
+ return operationsByTag.records.insertRecordWithID({
857
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
858
+ queryParams: options,
859
+ body: record,
860
+ ...this.extraProps
861
+ });
862
+ }
863
+ updateRecordWithID(workspace, database, branch, tableName, recordId, record, options = {}) {
864
+ return operationsByTag.records.updateRecordWithID({
865
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
866
+ queryParams: options,
867
+ body: record,
868
+ ...this.extraProps
869
+ });
870
+ }
871
+ upsertRecordWithID(workspace, database, branch, tableName, recordId, record, options = {}) {
872
+ return operationsByTag.records.upsertRecordWithID({
873
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
874
+ queryParams: options,
875
+ body: record,
876
+ ...this.extraProps
877
+ });
878
+ }
879
+ deleteRecord(workspace, database, branch, tableName, recordId) {
880
+ return operationsByTag.records.deleteRecord({
881
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
882
+ ...this.extraProps
883
+ });
884
+ }
885
+ getRecord(workspace, database, branch, tableName, recordId, options = {}) {
886
+ return operationsByTag.records.getRecord({
887
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
888
+ ...this.extraProps
889
+ });
890
+ }
891
+ bulkInsertTableRecords(workspace, database, branch, tableName, records) {
892
+ return operationsByTag.records.bulkInsertTableRecords({
893
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
894
+ body: { records },
895
+ ...this.extraProps
896
+ });
897
+ }
898
+ queryTable(workspace, database, branch, tableName, query) {
899
+ return operationsByTag.records.queryTable({
900
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
901
+ body: query,
902
+ ...this.extraProps
903
+ });
904
+ }
905
+ searchTable(workspace, database, branch, tableName, query) {
906
+ return operationsByTag.records.searchTable({
907
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
908
+ body: query,
909
+ ...this.extraProps
910
+ });
911
+ }
912
+ searchBranch(workspace, database, branch, query) {
913
+ return operationsByTag.records.searchBranch({
914
+ pathParams: { workspace, dbBranchName: `${database}:${branch}` },
915
+ body: query,
916
+ ...this.extraProps
917
+ });
918
+ }
919
+ }
920
+
921
+ class XataApiPlugin {
922
+ async build(options) {
923
+ const { fetchImpl, apiKey } = await options.getFetchProps();
924
+ return new XataApiClient({ fetch: fetchImpl, apiKey });
925
+ }
926
+ }
927
+
928
+ class XataPlugin {
929
+ }
930
+
931
+ var __accessCheck$6 = (obj, member, msg) => {
932
+ if (!member.has(obj))
933
+ throw TypeError("Cannot " + msg);
934
+ };
935
+ var __privateGet$6 = (obj, member, getter) => {
936
+ __accessCheck$6(obj, member, "read from private field");
937
+ return getter ? getter.call(obj) : member.get(obj);
938
+ };
939
+ var __privateAdd$6 = (obj, member, value) => {
940
+ if (member.has(obj))
941
+ throw TypeError("Cannot add the same private member more than once");
942
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
943
+ };
944
+ var __privateSet$5 = (obj, member, value, setter) => {
945
+ __accessCheck$6(obj, member, "write to private field");
946
+ setter ? setter.call(obj, value) : member.set(obj, value);
947
+ return value;
948
+ };
949
+ var _query;
950
+ class Page {
951
+ constructor(query, meta, records = []) {
952
+ __privateAdd$6(this, _query, void 0);
953
+ __privateSet$5(this, _query, query);
954
+ this.meta = meta;
955
+ this.records = records;
956
+ }
957
+ async nextPage(size, offset) {
958
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
959
+ }
960
+ async previousPage(size, offset) {
961
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
962
+ }
963
+ async firstPage(size, offset) {
964
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
965
+ }
966
+ async lastPage(size, offset) {
967
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
968
+ }
969
+ hasNextPage() {
970
+ return this.meta.page.more;
971
+ }
972
+ }
973
+ _query = new WeakMap();
974
+ const PAGINATION_MAX_SIZE = 200;
975
+ const PAGINATION_DEFAULT_SIZE = 200;
976
+ const PAGINATION_MAX_OFFSET = 800;
977
+ const PAGINATION_DEFAULT_OFFSET = 0;
978
+ function isCursorPaginationOptions(options) {
979
+ return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
980
+ }
981
+
982
+ var __accessCheck$5 = (obj, member, msg) => {
983
+ if (!member.has(obj))
984
+ throw TypeError("Cannot " + msg);
985
+ };
986
+ var __privateGet$5 = (obj, member, getter) => {
987
+ __accessCheck$5(obj, member, "read from private field");
988
+ return getter ? getter.call(obj) : member.get(obj);
989
+ };
990
+ var __privateAdd$5 = (obj, member, value) => {
991
+ if (member.has(obj))
992
+ throw TypeError("Cannot add the same private member more than once");
993
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
994
+ };
995
+ var __privateSet$4 = (obj, member, value, setter) => {
996
+ __accessCheck$5(obj, member, "write to private field");
997
+ setter ? setter.call(obj, value) : member.set(obj, value);
998
+ return value;
999
+ };
1000
+ var _table$1, _repository, _data;
1001
+ const _Query = class {
1002
+ constructor(repository, table, data, rawParent) {
1003
+ __privateAdd$5(this, _table$1, void 0);
1004
+ __privateAdd$5(this, _repository, void 0);
1005
+ __privateAdd$5(this, _data, { filter: {} });
1006
+ this.meta = { page: { cursor: "start", more: true } };
1007
+ this.records = [];
1008
+ __privateSet$4(this, _table$1, table);
1009
+ if (repository) {
1010
+ __privateSet$4(this, _repository, repository);
1011
+ } else {
1012
+ __privateSet$4(this, _repository, this);
1013
+ }
1014
+ const parent = cleanParent(data, rawParent);
1015
+ __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
1016
+ __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
1017
+ __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
1018
+ __privateGet$5(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
1019
+ __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1020
+ __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1021
+ __privateGet$5(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
1022
+ __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1023
+ __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
1024
+ this.any = this.any.bind(this);
1025
+ this.all = this.all.bind(this);
1026
+ this.not = this.not.bind(this);
1027
+ this.filter = this.filter.bind(this);
1028
+ this.sort = this.sort.bind(this);
1029
+ this.none = this.none.bind(this);
1030
+ Object.defineProperty(this, "table", { enumerable: false });
1031
+ Object.defineProperty(this, "repository", { enumerable: false });
1032
+ }
1033
+ getQueryOptions() {
1034
+ return __privateGet$5(this, _data);
1035
+ }
1036
+ key() {
1037
+ const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$5(this, _data);
1038
+ const key = JSON.stringify({ columns, filter, sort, pagination });
1039
+ return toBase64(key);
1040
+ }
1041
+ any(...queries) {
1042
+ const $any = queries.map((query) => query.getQueryOptions().filter ?? {});
1043
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
1044
+ }
1045
+ all(...queries) {
1046
+ const $all = queries.map((query) => query.getQueryOptions().filter ?? {});
1047
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1048
+ }
1049
+ not(...queries) {
1050
+ const $not = queries.map((query) => query.getQueryOptions().filter ?? {});
1051
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
1052
+ }
1053
+ none(...queries) {
1054
+ const $none = queries.map((query) => query.getQueryOptions().filter ?? {});
1055
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
1056
+ }
1057
+ filter(a, b) {
1058
+ if (arguments.length === 1) {
1059
+ const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
1060
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1061
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1062
+ } else {
1063
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat([{ [a]: b }]));
1064
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
1065
+ }
1066
+ }
1067
+ sort(column, direction) {
1068
+ const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
1069
+ const sort = [...originalSort, { column, direction }];
1070
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
1071
+ }
1072
+ select(columns) {
1073
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { columns }, __privateGet$5(this, _data));
1074
+ }
1075
+ getPaginated(options = {}) {
1076
+ const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
1077
+ return __privateGet$5(this, _repository).query(query);
1078
+ }
1079
+ async *[Symbol.asyncIterator]() {
1080
+ for await (const [record] of this.getIterator({ batchSize: 1 })) {
1081
+ yield record;
1082
+ }
1083
+ }
1084
+ async *getIterator(options = {}) {
1085
+ const { batchSize = 1 } = options;
1086
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
1087
+ let more = page.hasNextPage();
1088
+ yield page.records;
1089
+ while (more) {
1090
+ page = await page.nextPage();
1091
+ more = page.hasNextPage();
1092
+ yield page.records;
1093
+ }
1094
+ }
1095
+ async getMany(options = {}) {
1096
+ const { records } = await this.getPaginated(options);
1097
+ return records;
1098
+ }
1099
+ async getAll(options = {}) {
1100
+ const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
1101
+ const results = [];
1102
+ for await (const page of this.getIterator({ ...rest, batchSize })) {
1103
+ results.push(...page);
1104
+ }
1105
+ return results;
1106
+ }
1107
+ async getFirst(options = {}) {
1108
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1109
+ return records[0] ?? null;
1110
+ }
1111
+ cache(ttl) {
1112
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1113
+ }
1114
+ nextPage(size, offset) {
1115
+ return this.firstPage(size, offset);
1116
+ }
1117
+ previousPage(size, offset) {
1118
+ return this.firstPage(size, offset);
1119
+ }
1120
+ firstPage(size, offset) {
1121
+ return this.getPaginated({ pagination: { size, offset } });
1122
+ }
1123
+ lastPage(size, offset) {
1124
+ return this.getPaginated({ pagination: { size, offset, before: "end" } });
1125
+ }
1126
+ hasNextPage() {
1127
+ return this.meta.page.more;
1128
+ }
1129
+ };
1130
+ let Query = _Query;
1131
+ _table$1 = new WeakMap();
1132
+ _repository = new WeakMap();
1133
+ _data = new WeakMap();
1134
+ function cleanParent(data, parent) {
1135
+ if (isCursorPaginationOptions(data.pagination)) {
1136
+ return { ...parent, sorting: void 0, filter: void 0 };
1137
+ }
1138
+ return parent;
1139
+ }
1140
+
1141
+ function isIdentifiable(x) {
1142
+ return isObject(x) && isString(x?.id);
1143
+ }
1144
+ function isXataRecord(x) {
1145
+ return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1146
+ }
1147
+
1148
+ function isSortFilterString(value) {
1149
+ return isString(value);
1150
+ }
1151
+ function isSortFilterBase(filter) {
1152
+ return isObject(filter) && Object.values(filter).every((value) => value === "asc" || value === "desc");
1153
+ }
1154
+ function isSortFilterObject(filter) {
1155
+ return isObject(filter) && !isSortFilterBase(filter) && filter.column !== void 0;
1156
+ }
1157
+ function buildSortFilter(filter) {
1158
+ if (isSortFilterString(filter)) {
1159
+ return { [filter]: "asc" };
1160
+ } else if (Array.isArray(filter)) {
1161
+ return filter.map((item) => buildSortFilter(item));
1162
+ } else if (isSortFilterBase(filter)) {
1163
+ return filter;
1164
+ } else if (isSortFilterObject(filter)) {
1165
+ return { [filter.column]: filter.direction ?? "asc" };
1166
+ } else {
1167
+ throw new Error(`Invalid sort filter: ${filter}`);
1168
+ }
1169
+ }
1170
+
1171
+ var __accessCheck$4 = (obj, member, msg) => {
1172
+ if (!member.has(obj))
1173
+ throw TypeError("Cannot " + msg);
1174
+ };
1175
+ var __privateGet$4 = (obj, member, getter) => {
1176
+ __accessCheck$4(obj, member, "read from private field");
1177
+ return getter ? getter.call(obj) : member.get(obj);
1178
+ };
1179
+ var __privateAdd$4 = (obj, member, value) => {
1180
+ if (member.has(obj))
1181
+ throw TypeError("Cannot add the same private member more than once");
1182
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1183
+ };
1184
+ var __privateSet$3 = (obj, member, value, setter) => {
1185
+ __accessCheck$4(obj, member, "write to private field");
1186
+ setter ? setter.call(obj, value) : member.set(obj, value);
1187
+ return value;
1188
+ };
1189
+ var __privateMethod$2 = (obj, member, method) => {
1190
+ __accessCheck$4(obj, member, "access private method");
1191
+ return method;
1192
+ };
1193
+ var _table, _getFetchProps, _cache, _schema$1, _insertRecordWithoutId, insertRecordWithoutId_fn, _insertRecordWithId, insertRecordWithId_fn, _bulkInsertTableRecords, bulkInsertTableRecords_fn, _updateRecordWithID, updateRecordWithID_fn, _upsertRecordWithID, upsertRecordWithID_fn, _deleteRecord, deleteRecord_fn, _invalidateCache, invalidateCache_fn, _setCacheRecord, setCacheRecord_fn, _getCacheRecord, getCacheRecord_fn, _setCacheQuery, setCacheQuery_fn, _getCacheQuery, getCacheQuery_fn, _getSchema$1, getSchema_fn$1;
1194
+ class Repository extends Query {
1195
+ }
1196
+ class RestRepository extends Query {
1197
+ constructor(options) {
1198
+ super(null, options.table, {});
1199
+ __privateAdd$4(this, _insertRecordWithoutId);
1200
+ __privateAdd$4(this, _insertRecordWithId);
1201
+ __privateAdd$4(this, _bulkInsertTableRecords);
1202
+ __privateAdd$4(this, _updateRecordWithID);
1203
+ __privateAdd$4(this, _upsertRecordWithID);
1204
+ __privateAdd$4(this, _deleteRecord);
1205
+ __privateAdd$4(this, _invalidateCache);
1206
+ __privateAdd$4(this, _setCacheRecord);
1207
+ __privateAdd$4(this, _getCacheRecord);
1208
+ __privateAdd$4(this, _setCacheQuery);
1209
+ __privateAdd$4(this, _getCacheQuery);
1210
+ __privateAdd$4(this, _getSchema$1);
1211
+ __privateAdd$4(this, _table, void 0);
1212
+ __privateAdd$4(this, _getFetchProps, void 0);
1213
+ __privateAdd$4(this, _cache, void 0);
1214
+ __privateAdd$4(this, _schema$1, void 0);
1215
+ __privateSet$3(this, _table, options.table);
1216
+ __privateSet$3(this, _getFetchProps, options.pluginOptions.getFetchProps);
1217
+ this.db = options.db;
1218
+ __privateSet$3(this, _cache, options.pluginOptions.cache);
1219
+ }
1220
+ async create(a, b) {
1221
+ if (Array.isArray(a)) {
1222
+ const records = await __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a);
1223
+ await Promise.all(records.map((record) => __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record)));
1224
+ return records;
1225
+ }
1226
+ if (isString(a) && isObject(b)) {
1227
+ if (a === "")
1228
+ throw new Error("The id can't be empty");
1229
+ const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b);
1230
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1231
+ return record;
1232
+ }
1233
+ if (isObject(a) && isString(a.id)) {
1234
+ if (a.id === "")
1235
+ throw new Error("The id can't be empty");
1236
+ const record = await __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 });
1237
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1238
+ return record;
1239
+ }
1240
+ if (isObject(a)) {
1241
+ const record = await __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a);
1242
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1243
+ return record;
1244
+ }
1245
+ throw new Error("Invalid arguments for create method");
1246
+ }
1247
+ async read(recordId) {
1248
+ const cacheRecord = await __privateMethod$2(this, _getCacheRecord, getCacheRecord_fn).call(this, recordId);
1249
+ if (cacheRecord)
1250
+ return cacheRecord;
1251
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1252
+ try {
1253
+ const response = await getRecord({
1254
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1255
+ ...fetchProps
1256
+ });
1257
+ const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1258
+ return initObject(this.db, schema, __privateGet$4(this, _table), response);
1259
+ } catch (e) {
1260
+ if (isObject(e) && e.status === 404) {
1261
+ return null;
1262
+ }
1263
+ throw e;
1264
+ }
1265
+ }
1266
+ async update(a, b) {
1267
+ if (Array.isArray(a)) {
1268
+ if (a.length > 100) {
1269
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1270
+ }
1271
+ return Promise.all(a.map((object) => this.update(object)));
1272
+ }
1273
+ if (isString(a) && isObject(b)) {
1274
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1275
+ const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b);
1276
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1277
+ return record;
1278
+ }
1279
+ if (isObject(a) && isString(a.id)) {
1280
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1281
+ const record = await __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1282
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1283
+ return record;
1284
+ }
1285
+ throw new Error("Invalid arguments for update method");
1286
+ }
1287
+ async createOrUpdate(a, b) {
1288
+ if (Array.isArray(a)) {
1289
+ if (a.length > 100) {
1290
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1291
+ }
1292
+ return Promise.all(a.map((object) => this.createOrUpdate(object)));
1293
+ }
1294
+ if (isString(a) && isObject(b)) {
1295
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1296
+ const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b);
1297
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1298
+ return record;
1299
+ }
1300
+ if (isObject(a) && isString(a.id)) {
1301
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1302
+ const record = await __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 });
1303
+ await __privateMethod$2(this, _setCacheRecord, setCacheRecord_fn).call(this, record);
1304
+ return record;
1305
+ }
1306
+ throw new Error("Invalid arguments for createOrUpdate method");
1307
+ }
1308
+ async delete(a) {
1309
+ if (Array.isArray(a)) {
1310
+ if (a.length > 100) {
1311
+ console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1312
+ }
1313
+ await Promise.all(a.map((id) => this.delete(id)));
1314
+ return;
1315
+ }
1316
+ if (isString(a)) {
1317
+ await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a);
1318
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a);
1319
+ return;
1320
+ }
1321
+ if (isObject(a) && isString(a.id)) {
1322
+ await __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id);
1323
+ await __privateMethod$2(this, _invalidateCache, invalidateCache_fn).call(this, a.id);
1324
+ return;
1325
+ }
1326
+ throw new Error("Invalid arguments for delete method");
1327
+ }
1328
+ async search(query, options = {}) {
1329
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1330
+ const { records } = await searchTable({
1331
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1332
+ body: {
1333
+ query,
1334
+ fuzziness: options.fuzziness,
1335
+ filter: options.filter
1336
+ },
1337
+ ...fetchProps
1338
+ });
1339
+ const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1340
+ return records.map((item) => initObject(this.db, schema, __privateGet$4(this, _table), item));
1341
+ }
1342
+ async query(query) {
1343
+ const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1344
+ if (cacheQuery)
1345
+ return new Page(query, cacheQuery.meta, cacheQuery.records);
1346
+ const data = query.getQueryOptions();
1347
+ const body = {
1348
+ filter: Object.values(data.filter ?? {}).some(Boolean) ? data.filter : void 0,
1349
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1350
+ page: data.pagination,
1351
+ columns: data.columns
1352
+ };
1353
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1354
+ const { meta, records: objects } = await queryTable({
1355
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1356
+ body,
1357
+ ...fetchProps
1358
+ });
1359
+ const schema = await __privateMethod$2(this, _getSchema$1, getSchema_fn$1).call(this);
1360
+ const records = objects.map((record) => initObject(this.db, schema, __privateGet$4(this, _table), record));
1361
+ await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1362
+ return new Page(query, meta, records);
1363
+ }
1364
+ }
1365
+ _table = new WeakMap();
1366
+ _getFetchProps = new WeakMap();
1367
+ _cache = new WeakMap();
1368
+ _schema$1 = new WeakMap();
1369
+ _insertRecordWithoutId = new WeakSet();
1370
+ insertRecordWithoutId_fn = async function(object) {
1371
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1372
+ const record = transformObjectLinks(object);
1373
+ const response = await insertRecord({
1374
+ pathParams: {
1375
+ workspace: "{workspaceId}",
1376
+ dbBranchName: "{dbBranch}",
1377
+ tableName: __privateGet$4(this, _table)
1378
+ },
1379
+ body: record,
1380
+ ...fetchProps
1381
+ });
1382
+ const finalObject = await this.read(response.id);
1383
+ if (!finalObject) {
1384
+ throw new Error("The server failed to save the record");
1385
+ }
1386
+ return finalObject;
1387
+ };
1388
+ _insertRecordWithId = new WeakSet();
1389
+ insertRecordWithId_fn = async function(recordId, object) {
1390
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1391
+ const record = transformObjectLinks(object);
1392
+ const response = await insertRecordWithID({
1393
+ pathParams: {
1394
+ workspace: "{workspaceId}",
1395
+ dbBranchName: "{dbBranch}",
1396
+ tableName: __privateGet$4(this, _table),
1397
+ recordId
1398
+ },
1399
+ body: record,
1400
+ queryParams: { createOnly: true },
1401
+ ...fetchProps
1402
+ });
1403
+ const finalObject = await this.read(response.id);
1404
+ if (!finalObject) {
1405
+ throw new Error("The server failed to save the record");
1406
+ }
1407
+ return finalObject;
1408
+ };
1409
+ _bulkInsertTableRecords = new WeakSet();
1410
+ bulkInsertTableRecords_fn = async function(objects) {
1411
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1412
+ const records = objects.map((object) => transformObjectLinks(object));
1413
+ const response = await bulkInsertTableRecords({
1414
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1415
+ body: { records },
1416
+ ...fetchProps
1417
+ });
1418
+ const finalObjects = await this.any(...response.recordIDs.map((id) => this.filter("id", id))).getAll();
1419
+ if (finalObjects.length !== objects.length) {
1420
+ throw new Error("The server failed to save some records");
1421
+ }
1422
+ return finalObjects;
1423
+ };
1424
+ _updateRecordWithID = new WeakSet();
1425
+ updateRecordWithID_fn = async function(recordId, object) {
1426
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1427
+ const record = transformObjectLinks(object);
1428
+ const response = await updateRecordWithID({
1429
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1430
+ body: record,
1431
+ ...fetchProps
1432
+ });
1433
+ const item = await this.read(response.id);
1434
+ if (!item)
1435
+ throw new Error("The server failed to save the record");
1436
+ return item;
1437
+ };
1438
+ _upsertRecordWithID = new WeakSet();
1439
+ upsertRecordWithID_fn = async function(recordId, object) {
1440
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1441
+ const response = await upsertRecordWithID({
1442
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1443
+ body: object,
1444
+ ...fetchProps
1445
+ });
1446
+ const item = await this.read(response.id);
1447
+ if (!item)
1448
+ throw new Error("The server failed to save the record");
1449
+ return item;
1450
+ };
1451
+ _deleteRecord = new WeakSet();
1452
+ deleteRecord_fn = async function(recordId) {
1453
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1454
+ await deleteRecord({
1455
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1456
+ ...fetchProps
1457
+ });
1458
+ };
1459
+ _invalidateCache = new WeakSet();
1460
+ invalidateCache_fn = async function(recordId) {
1461
+ await __privateGet$4(this, _cache).delete(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1462
+ const cacheItems = await __privateGet$4(this, _cache).getAll();
1463
+ const queries = Object.entries(cacheItems).filter(([key]) => key.startsWith("query_"));
1464
+ for (const [key, value] of queries) {
1465
+ const ids = getIds(value);
1466
+ if (ids.includes(recordId))
1467
+ await __privateGet$4(this, _cache).delete(key);
1468
+ }
1469
+ };
1470
+ _setCacheRecord = new WeakSet();
1471
+ setCacheRecord_fn = async function(record) {
1472
+ if (!__privateGet$4(this, _cache).cacheRecords)
1473
+ return;
1474
+ await __privateGet$4(this, _cache).set(`rec_${__privateGet$4(this, _table)}:${record.id}`, record);
1475
+ };
1476
+ _getCacheRecord = new WeakSet();
1477
+ getCacheRecord_fn = async function(recordId) {
1478
+ if (!__privateGet$4(this, _cache).cacheRecords)
1479
+ return null;
1480
+ return __privateGet$4(this, _cache).get(`rec_${__privateGet$4(this, _table)}:${recordId}`);
1481
+ };
1482
+ _setCacheQuery = new WeakSet();
1483
+ setCacheQuery_fn = async function(query, meta, records) {
1484
+ await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1485
+ };
1486
+ _getCacheQuery = new WeakSet();
1487
+ getCacheQuery_fn = async function(query) {
1488
+ const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
1489
+ const result = await __privateGet$4(this, _cache).get(key);
1490
+ if (!result)
1491
+ return null;
1492
+ const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1493
+ if (ttl < 0)
1494
+ return null;
1495
+ const hasExpired = result.date.getTime() + ttl < Date.now();
1496
+ return hasExpired ? null : result;
1497
+ };
1498
+ _getSchema$1 = new WeakSet();
1499
+ getSchema_fn$1 = async function() {
1500
+ if (__privateGet$4(this, _schema$1))
1501
+ return __privateGet$4(this, _schema$1);
1502
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1503
+ const { schema } = await getBranchDetails({
1504
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1505
+ ...fetchProps
1506
+ });
1507
+ __privateSet$3(this, _schema$1, schema);
1508
+ return schema;
1509
+ };
1510
+ const transformObjectLinks = (object) => {
1511
+ return Object.entries(object).reduce((acc, [key, value]) => {
1512
+ if (key === "xata")
1513
+ return acc;
1514
+ return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1515
+ }, {});
1516
+ };
1517
+ const initObject = (db, schema, table, object) => {
1518
+ const result = {};
1519
+ Object.assign(result, object);
1520
+ const { columns } = schema.tables.find(({ name }) => name === table) ?? {};
1521
+ if (!columns)
1522
+ console.error(`Table ${table} not found in schema`);
1523
+ for (const column of columns ?? []) {
1524
+ const value = result[column.name];
1525
+ switch (column.type) {
1526
+ case "datetime": {
1527
+ const date = new Date(value);
1528
+ if (isNaN(date.getTime())) {
1529
+ console.error(`Failed to parse date ${value} for field ${column.name}`);
1530
+ } else {
1531
+ result[column.name] = date;
1532
+ }
1533
+ break;
1534
+ }
1535
+ case "link": {
1536
+ const linkTable = column.link?.table;
1537
+ if (!linkTable) {
1538
+ console.error(`Failed to parse link for field ${column.name}`);
1539
+ } else if (isObject(value)) {
1540
+ result[column.name] = initObject(db, schema, linkTable, value);
1541
+ }
1542
+ break;
1543
+ }
1544
+ }
1545
+ }
1546
+ result.read = function() {
1547
+ return db[table].read(result["id"]);
1548
+ };
1549
+ result.update = function(data) {
1550
+ return db[table].update(result["id"], data);
1551
+ };
1552
+ result.delete = function() {
1553
+ return db[table].delete(result["id"]);
1554
+ };
1555
+ for (const prop of ["read", "update", "delete"]) {
1556
+ Object.defineProperty(result, prop, { enumerable: false });
1557
+ }
1558
+ Object.freeze(result);
1559
+ return result;
1560
+ };
1561
+ function getIds(value) {
1562
+ if (Array.isArray(value)) {
1563
+ return value.map((item) => getIds(item)).flat();
1564
+ }
1565
+ if (!isObject(value))
1566
+ return [];
1567
+ const nestedIds = Object.values(value).map((item) => getIds(item)).flat();
1568
+ return isString(value.id) ? [value.id, ...nestedIds] : nestedIds;
1569
+ }
1570
+
1571
+ var __accessCheck$3 = (obj, member, msg) => {
1572
+ if (!member.has(obj))
1573
+ throw TypeError("Cannot " + msg);
1574
+ };
1575
+ var __privateGet$3 = (obj, member, getter) => {
1576
+ __accessCheck$3(obj, member, "read from private field");
1577
+ return getter ? getter.call(obj) : member.get(obj);
1578
+ };
1579
+ var __privateAdd$3 = (obj, member, value) => {
1580
+ if (member.has(obj))
1581
+ throw TypeError("Cannot add the same private member more than once");
1582
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1583
+ };
1584
+ var __privateSet$2 = (obj, member, value, setter) => {
1585
+ __accessCheck$3(obj, member, "write to private field");
1586
+ setter ? setter.call(obj, value) : member.set(obj, value);
1587
+ return value;
1588
+ };
1589
+ var _map;
1590
+ class SimpleCache {
1591
+ constructor(options = {}) {
1592
+ __privateAdd$3(this, _map, void 0);
1593
+ __privateSet$2(this, _map, /* @__PURE__ */ new Map());
1594
+ this.capacity = options.max ?? 500;
1595
+ this.cacheRecords = options.cacheRecords ?? true;
1596
+ this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1597
+ }
1598
+ async getAll() {
1599
+ return Object.fromEntries(__privateGet$3(this, _map));
1600
+ }
1601
+ async get(key) {
1602
+ return __privateGet$3(this, _map).get(key) ?? null;
1603
+ }
1604
+ async set(key, value) {
1605
+ await this.delete(key);
1606
+ __privateGet$3(this, _map).set(key, value);
1607
+ if (__privateGet$3(this, _map).size > this.capacity) {
1608
+ const leastRecentlyUsed = __privateGet$3(this, _map).keys().next().value;
1609
+ await this.delete(leastRecentlyUsed);
1610
+ }
1611
+ }
1612
+ async delete(key) {
1613
+ __privateGet$3(this, _map).delete(key);
1614
+ }
1615
+ async clear() {
1616
+ return __privateGet$3(this, _map).clear();
1617
+ }
1618
+ }
1619
+ _map = new WeakMap();
1620
+
1621
+ const gt = (value) => ({ $gt: value });
1622
+ const ge = (value) => ({ $ge: value });
1623
+ const gte = (value) => ({ $ge: value });
1624
+ const lt = (value) => ({ $lt: value });
1625
+ const lte = (value) => ({ $le: value });
1626
+ const le = (value) => ({ $le: value });
1627
+ const exists = (column) => ({ $exists: column });
1628
+ const notExists = (column) => ({ $notExists: column });
1629
+ const startsWith = (value) => ({ $startsWith: value });
1630
+ const endsWith = (value) => ({ $endsWith: value });
1631
+ const pattern = (value) => ({ $pattern: value });
1632
+ const is = (value) => ({ $is: value });
1633
+ const isNot = (value) => ({ $isNot: value });
1634
+ const contains = (value) => ({ $contains: value });
1635
+ const includes = (value) => ({ $includes: value });
1636
+ const includesAll = (value) => ({ $includesAll: value });
1637
+ const includesNone = (value) => ({ $includesNone: value });
1638
+ const includesAny = (value) => ({ $includesAny: value });
1639
+
1640
+ var __accessCheck$2 = (obj, member, msg) => {
1641
+ if (!member.has(obj))
1642
+ throw TypeError("Cannot " + msg);
1643
+ };
1644
+ var __privateGet$2 = (obj, member, getter) => {
1645
+ __accessCheck$2(obj, member, "read from private field");
1646
+ return getter ? getter.call(obj) : member.get(obj);
1647
+ };
1648
+ var __privateAdd$2 = (obj, member, value) => {
1649
+ if (member.has(obj))
1650
+ throw TypeError("Cannot add the same private member more than once");
1651
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1652
+ };
1653
+ var _tables;
1654
+ class SchemaPlugin extends XataPlugin {
1655
+ constructor(tableNames) {
1656
+ super();
1657
+ this.tableNames = tableNames;
1658
+ __privateAdd$2(this, _tables, {});
1659
+ }
1660
+ build(pluginOptions) {
1661
+ const db = new Proxy({}, {
1662
+ get: (_target, table) => {
1663
+ if (!isString(table))
1664
+ throw new Error("Invalid table name");
1665
+ if (__privateGet$2(this, _tables)[table] === void 0) {
1666
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table });
1667
+ }
1668
+ return __privateGet$2(this, _tables)[table];
1669
+ }
1670
+ });
1671
+ for (const table of this.tableNames ?? []) {
1672
+ db[table] = new RestRepository({ db, pluginOptions, table });
1673
+ }
1674
+ return db;
1675
+ }
1676
+ }
1677
+ _tables = new WeakMap();
1678
+
1679
+ var __accessCheck$1 = (obj, member, msg) => {
1680
+ if (!member.has(obj))
1681
+ throw TypeError("Cannot " + msg);
1682
+ };
1683
+ var __privateGet$1 = (obj, member, getter) => {
1684
+ __accessCheck$1(obj, member, "read from private field");
1685
+ return getter ? getter.call(obj) : member.get(obj);
1686
+ };
1687
+ var __privateAdd$1 = (obj, member, value) => {
1688
+ if (member.has(obj))
1689
+ throw TypeError("Cannot add the same private member more than once");
1690
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1691
+ };
1692
+ var __privateSet$1 = (obj, member, value, setter) => {
1693
+ __accessCheck$1(obj, member, "write to private field");
1694
+ setter ? setter.call(obj, value) : member.set(obj, value);
1695
+ return value;
1696
+ };
1697
+ var __privateMethod$1 = (obj, member, method) => {
1698
+ __accessCheck$1(obj, member, "access private method");
1699
+ return method;
1700
+ };
1701
+ var _schema, _search, search_fn, _getSchema, getSchema_fn;
1702
+ class SearchPlugin extends XataPlugin {
1703
+ constructor(db) {
1704
+ super();
1705
+ this.db = db;
1706
+ __privateAdd$1(this, _search);
1707
+ __privateAdd$1(this, _getSchema);
1708
+ __privateAdd$1(this, _schema, void 0);
1709
+ }
1710
+ build({ getFetchProps }) {
1711
+ return {
1712
+ all: async (query, options = {}) => {
1713
+ const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1714
+ const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
1715
+ return records.map((record) => {
1716
+ const { table = "orphan" } = record.xata;
1717
+ return { table, record: initObject(this.db, schema, table, record) };
1718
+ });
1719
+ },
1720
+ byTable: async (query, options = {}) => {
1721
+ const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1722
+ const schema = await __privateMethod$1(this, _getSchema, getSchema_fn).call(this, getFetchProps);
1723
+ return records.reduce((acc, record) => {
1724
+ const { table = "orphan" } = record.xata;
1725
+ const items = acc[table] ?? [];
1726
+ const item = initObject(this.db, schema, table, record);
1727
+ return { ...acc, [table]: [...items, item] };
1728
+ }, {});
1729
+ }
1730
+ };
1731
+ }
1732
+ }
1733
+ _schema = new WeakMap();
1734
+ _search = new WeakSet();
1735
+ search_fn = async function(query, options, getFetchProps) {
1736
+ const fetchProps = await getFetchProps();
1737
+ const { tables, fuzziness } = options ?? {};
1738
+ const { records } = await searchBranch({
1739
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1740
+ body: { tables, query, fuzziness },
1741
+ ...fetchProps
1742
+ });
1743
+ return records;
1744
+ };
1745
+ _getSchema = new WeakSet();
1746
+ getSchema_fn = async function(getFetchProps) {
1747
+ if (__privateGet$1(this, _schema))
1748
+ return __privateGet$1(this, _schema);
1749
+ const fetchProps = await getFetchProps();
1750
+ const { schema } = await getBranchDetails({
1751
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1752
+ ...fetchProps
1753
+ });
1754
+ __privateSet$1(this, _schema, schema);
1755
+ return schema;
1756
+ };
1757
+
1758
+ const isBranchStrategyBuilder = (strategy) => {
1759
+ return typeof strategy === "function";
1760
+ };
1761
+
1762
+ const envBranchNames = [
1763
+ "XATA_BRANCH",
1764
+ "VERCEL_GIT_COMMIT_REF",
1765
+ "CF_PAGES_BRANCH",
1766
+ "BRANCH"
1767
+ ];
1768
+ async function getCurrentBranchName(options) {
1769
+ const env = getBranchByEnvVariable();
1770
+ if (env) {
1771
+ const details = await getDatabaseBranch(env, options);
1772
+ if (details)
1773
+ return env;
1774
+ console.warn(`Branch ${env} not found in Xata. Ignoring...`);
1775
+ }
1776
+ const gitBranch = await getGitBranch();
1777
+ return resolveXataBranch(gitBranch, options);
1778
+ }
1779
+ async function getCurrentBranchDetails(options) {
1780
+ const branch = await getCurrentBranchName(options);
1781
+ return getDatabaseBranch(branch, options);
1782
+ }
1783
+ async function resolveXataBranch(gitBranch, options) {
1784
+ const databaseURL = options?.databaseURL || getDatabaseURL();
1785
+ const apiKey = options?.apiKey || getAPIKey();
1786
+ if (!databaseURL)
1787
+ throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
1788
+ if (!apiKey)
1789
+ throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
1790
+ const [protocol, , host, , dbName] = databaseURL.split("/");
1791
+ const [workspace] = host.split(".");
1792
+ const { branch } = await resolveBranch({
1793
+ apiKey,
1794
+ apiUrl: databaseURL,
1795
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
1796
+ workspacesApiUrl: `${protocol}//${host}`,
1797
+ pathParams: { dbName, workspace },
1798
+ queryParams: { gitBranch, fallbackBranch: getEnvVariable("XATA_FALLBACK_BRANCH") }
1799
+ });
1800
+ return branch;
1801
+ }
1802
+ async function getDatabaseBranch(branch, options) {
1803
+ const databaseURL = options?.databaseURL || getDatabaseURL();
1804
+ const apiKey = options?.apiKey || getAPIKey();
1805
+ if (!databaseURL)
1806
+ throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
1807
+ if (!apiKey)
1808
+ throw new Error("An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely");
1809
+ const [protocol, , host, , database] = databaseURL.split("/");
1810
+ const [workspace] = host.split(".");
1811
+ const dbBranchName = `${database}:${branch}`;
1812
+ try {
1813
+ return await getBranchDetails({
1814
+ apiKey,
1815
+ apiUrl: databaseURL,
1816
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
1817
+ workspacesApiUrl: `${protocol}//${host}`,
1818
+ pathParams: {
1819
+ dbBranchName,
1820
+ workspace
1821
+ }
1822
+ });
1823
+ } catch (err) {
1824
+ if (isObject(err) && err.status === 404)
1825
+ return null;
1826
+ throw err;
1827
+ }
1828
+ }
1829
+ function getBranchByEnvVariable() {
1830
+ for (const name of envBranchNames) {
1831
+ const value = getEnvVariable(name);
1832
+ if (value) {
1833
+ return value;
1834
+ }
1835
+ }
1836
+ try {
1837
+ return XATA_BRANCH;
1838
+ } catch (err) {
1839
+ }
1840
+ }
1841
+ function getDatabaseURL() {
1842
+ try {
1843
+ return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
1844
+ } catch (err) {
1845
+ return void 0;
1846
+ }
1847
+ }
1848
+
1849
+ var __accessCheck = (obj, member, msg) => {
1850
+ if (!member.has(obj))
1851
+ throw TypeError("Cannot " + msg);
1852
+ };
1853
+ var __privateGet = (obj, member, getter) => {
1854
+ __accessCheck(obj, member, "read from private field");
1855
+ return getter ? getter.call(obj) : member.get(obj);
1856
+ };
1857
+ var __privateAdd = (obj, member, value) => {
1858
+ if (member.has(obj))
1859
+ throw TypeError("Cannot add the same private member more than once");
1860
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1861
+ };
1862
+ var __privateSet = (obj, member, value, setter) => {
1863
+ __accessCheck(obj, member, "write to private field");
1864
+ setter ? setter.call(obj, value) : member.set(obj, value);
1865
+ return value;
1866
+ };
1867
+ var __privateMethod = (obj, member, method) => {
1868
+ __accessCheck(obj, member, "access private method");
1869
+ return method;
1870
+ };
1871
+ const buildClient = (plugins) => {
1872
+ var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1873
+ return _a = class {
1874
+ constructor(options = {}, tables) {
1875
+ __privateAdd(this, _parseOptions);
1876
+ __privateAdd(this, _getFetchProps);
1877
+ __privateAdd(this, _evaluateBranch);
1878
+ __privateAdd(this, _branch, void 0);
1879
+ const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
1880
+ const pluginOptions = {
1881
+ getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1882
+ cache: safeOptions.cache
1883
+ };
1884
+ const db = new SchemaPlugin(tables).build(pluginOptions);
1885
+ const search = new SearchPlugin(db).build(pluginOptions);
1886
+ this.db = db;
1887
+ this.search = search;
1888
+ for (const [key, namespace] of Object.entries(plugins ?? {})) {
1889
+ if (namespace === void 0)
1890
+ continue;
1891
+ const result = namespace.build(pluginOptions);
1892
+ if (result instanceof Promise) {
1893
+ void result.then((namespace2) => {
1894
+ this[key] = namespace2;
1895
+ });
1896
+ } else {
1897
+ this[key] = result;
1898
+ }
1899
+ }
1900
+ }
1901
+ }, _branch = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
1902
+ const fetch = getFetchImplementation(options?.fetch);
1903
+ const databaseURL = options?.databaseURL || getDatabaseURL();
1904
+ const apiKey = options?.apiKey || getAPIKey();
1905
+ const cache = options?.cache ?? new SimpleCache({ cacheRecords: false, defaultQueryTTL: 0 });
1906
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
1907
+ if (!databaseURL || !apiKey) {
1908
+ throw new Error("Options databaseURL and apiKey are required");
1909
+ }
1910
+ return { fetch, databaseURL, apiKey, branch, cache };
1911
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
1912
+ fetch,
1913
+ apiKey,
1914
+ databaseURL,
1915
+ branch
1916
+ }) {
1917
+ const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
1918
+ if (!branchValue)
1919
+ throw new Error("Unable to resolve branch value");
1920
+ return {
1921
+ fetchImpl: fetch,
1922
+ apiKey,
1923
+ apiUrl: "",
1924
+ workspacesApiUrl: (path, params) => {
1925
+ const hasBranch = params.dbBranchName ?? params.branch;
1926
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branchValue}` : "");
1927
+ return databaseURL + newPath;
1928
+ }
1929
+ };
1930
+ }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1931
+ if (__privateGet(this, _branch))
1932
+ return __privateGet(this, _branch);
1933
+ if (param === void 0)
1934
+ return void 0;
1935
+ const strategies = Array.isArray(param) ? [...param] : [param];
1936
+ const evaluateBranch = async (strategy) => {
1937
+ return isBranchStrategyBuilder(strategy) ? await strategy() : strategy;
1938
+ };
1939
+ for await (const strategy of strategies) {
1940
+ const branch = await evaluateBranch(strategy);
1941
+ if (branch) {
1942
+ __privateSet(this, _branch, branch);
1943
+ return branch;
1944
+ }
1945
+ }
1946
+ }, _a;
1947
+ };
1948
+ class BaseClient extends buildClient() {
1949
+ }
1950
+
1951
+ class XataError extends Error {
1952
+ constructor(message, status) {
1953
+ super(message);
1954
+ this.status = status;
1955
+ }
1956
+ }
1957
+
1958
+ exports.BaseClient = BaseClient;
1959
+ exports.Operations = operationsByTag;
1960
+ exports.PAGINATION_DEFAULT_OFFSET = PAGINATION_DEFAULT_OFFSET;
1961
+ exports.PAGINATION_DEFAULT_SIZE = PAGINATION_DEFAULT_SIZE;
1962
+ exports.PAGINATION_MAX_OFFSET = PAGINATION_MAX_OFFSET;
1963
+ exports.PAGINATION_MAX_SIZE = PAGINATION_MAX_SIZE;
1964
+ exports.Page = Page;
1965
+ exports.Query = Query;
1966
+ exports.Repository = Repository;
1967
+ exports.RestRepository = RestRepository;
1968
+ exports.SchemaPlugin = SchemaPlugin;
1969
+ exports.SearchPlugin = SearchPlugin;
1970
+ exports.SimpleCache = SimpleCache;
1971
+ exports.XataApiClient = XataApiClient;
1972
+ exports.XataApiPlugin = XataApiPlugin;
1973
+ exports.XataError = XataError;
1974
+ exports.XataPlugin = XataPlugin;
1975
+ exports.acceptWorkspaceMemberInvite = acceptWorkspaceMemberInvite;
1976
+ exports.addGitBranchesEntry = addGitBranchesEntry;
1977
+ exports.addTableColumn = addTableColumn;
1978
+ exports.buildClient = buildClient;
1979
+ exports.bulkInsertTableRecords = bulkInsertTableRecords;
1980
+ exports.cancelWorkspaceMemberInvite = cancelWorkspaceMemberInvite;
1981
+ exports.contains = contains;
1982
+ exports.createBranch = createBranch;
1983
+ exports.createDatabase = createDatabase;
1984
+ exports.createTable = createTable;
1985
+ exports.createUserAPIKey = createUserAPIKey;
1986
+ exports.createWorkspace = createWorkspace;
1987
+ exports.deleteBranch = deleteBranch;
1988
+ exports.deleteColumn = deleteColumn;
1989
+ exports.deleteDatabase = deleteDatabase;
1990
+ exports.deleteRecord = deleteRecord;
1991
+ exports.deleteTable = deleteTable;
1992
+ exports.deleteUser = deleteUser;
1993
+ exports.deleteUserAPIKey = deleteUserAPIKey;
1994
+ exports.deleteWorkspace = deleteWorkspace;
1995
+ exports.endsWith = endsWith;
1996
+ exports.executeBranchMigrationPlan = executeBranchMigrationPlan;
1997
+ exports.exists = exists;
1998
+ exports.ge = ge;
1999
+ exports.getAPIKey = getAPIKey;
2000
+ exports.getBranchDetails = getBranchDetails;
2001
+ exports.getBranchList = getBranchList;
2002
+ exports.getBranchMetadata = getBranchMetadata;
2003
+ exports.getBranchMigrationHistory = getBranchMigrationHistory;
2004
+ exports.getBranchMigrationPlan = getBranchMigrationPlan;
2005
+ exports.getBranchStats = getBranchStats;
2006
+ exports.getColumn = getColumn;
2007
+ exports.getCurrentBranchDetails = getCurrentBranchDetails;
2008
+ exports.getCurrentBranchName = getCurrentBranchName;
2009
+ exports.getDatabaseList = getDatabaseList;
2010
+ exports.getDatabaseURL = getDatabaseURL;
2011
+ exports.getGitBranchesMapping = getGitBranchesMapping;
2012
+ exports.getRecord = getRecord;
2013
+ exports.getTableColumns = getTableColumns;
2014
+ exports.getTableSchema = getTableSchema;
2015
+ exports.getUser = getUser;
2016
+ exports.getUserAPIKeys = getUserAPIKeys;
2017
+ exports.getWorkspace = getWorkspace;
2018
+ exports.getWorkspaceMembersList = getWorkspaceMembersList;
2019
+ exports.getWorkspacesList = getWorkspacesList;
2020
+ exports.gt = gt;
2021
+ exports.gte = gte;
2022
+ exports.includes = includes;
2023
+ exports.includesAll = includesAll;
2024
+ exports.includesAny = includesAny;
2025
+ exports.includesNone = includesNone;
2026
+ exports.insertRecord = insertRecord;
2027
+ exports.insertRecordWithID = insertRecordWithID;
2028
+ exports.inviteWorkspaceMember = inviteWorkspaceMember;
2029
+ exports.is = is;
2030
+ exports.isCursorPaginationOptions = isCursorPaginationOptions;
2031
+ exports.isIdentifiable = isIdentifiable;
2032
+ exports.isNot = isNot;
2033
+ exports.isXataRecord = isXataRecord;
2034
+ exports.le = le;
2035
+ exports.lt = lt;
2036
+ exports.lte = lte;
2037
+ exports.notExists = notExists;
2038
+ exports.operationsByTag = operationsByTag;
2039
+ exports.pattern = pattern;
2040
+ exports.queryTable = queryTable;
2041
+ exports.removeGitBranchesEntry = removeGitBranchesEntry;
2042
+ exports.removeWorkspaceMember = removeWorkspaceMember;
2043
+ exports.resendWorkspaceMemberInvite = resendWorkspaceMemberInvite;
2044
+ exports.resolveBranch = resolveBranch;
2045
+ exports.searchBranch = searchBranch;
2046
+ exports.searchTable = searchTable;
2047
+ exports.setTableSchema = setTableSchema;
2048
+ exports.startsWith = startsWith;
2049
+ exports.updateBranchMetadata = updateBranchMetadata;
2050
+ exports.updateColumn = updateColumn;
2051
+ exports.updateRecordWithID = updateRecordWithID;
2052
+ exports.updateTable = updateTable;
2053
+ exports.updateUser = updateUser;
2054
+ exports.updateWorkspace = updateWorkspace;
2055
+ exports.updateWorkspaceMemberRole = updateWorkspaceMemberRole;
2056
+ exports.upsertRecordWithID = upsertRecordWithID;
2057
+ //# sourceMappingURL=index.cjs.map