@xata.io/client 0.0.0-alpha.vf170c2c → 0.0.0-alpha.vf1de7db

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