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

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