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