@xata.io/client 0.0.0-alpha.vf71bb14 → 0.0.0-alpha.vf95371f

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