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

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