@xata.io/client 0.0.0-alpha.vf6f2567 → 0.0.0-alpha.vf721f5c

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