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