@xata.io/client 0.8.2 → 0.9.0

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