@xata.io/client 0.0.0-alpha.vee88fdc → 0.0.0-alpha.veec3be2

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