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

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