@xata.io/client 0.0.0-alpha.vf2696e7 → 0.0.0-alpha.vf2ed8b7

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.vf2ed8b7";
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(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,
@@ -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,25 @@ 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",
253
386
  method: "get",
254
387
  ...variables
255
388
  });
256
- const createBranch = (variables) => fetch$1({
389
+ const getGitBranchesMapping = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "get", ...variables });
390
+ const addGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "post", ...variables });
391
+ const removeGitBranchesEntry = (variables) => fetch$1({ url: "/dbs/{dbName}/gitBranches", method: "delete", ...variables });
392
+ const resolveBranch = (variables) => fetch$1({
393
+ url: "/dbs/{dbName}/resolveBranch",
394
+ method: "get",
395
+ ...variables
396
+ });
397
+ const getBranchDetails = (variables) => fetch$1({
257
398
  url: "/db/{dbBranchName}",
258
- method: "put",
399
+ method: "get",
259
400
  ...variables
260
401
  });
402
+ const createBranch = (variables) => fetch$1({ url: "/db/{dbBranchName}", method: "put", ...variables });
261
403
  const deleteBranch = (variables) => fetch$1({
262
404
  url: "/db/{dbBranchName}",
263
405
  method: "delete",
@@ -331,11 +473,7 @@ const updateColumn = (variables) => fetch$1({
331
473
  method: "patch",
332
474
  ...variables
333
475
  });
334
- const insertRecord = (variables) => fetch$1({
335
- url: "/db/{dbBranchName}/tables/{tableName}/data",
336
- method: "post",
337
- ...variables
338
- });
476
+ const insertRecord = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data", method: "post", ...variables });
339
477
  const insertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "put", ...variables });
340
478
  const updateRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "patch", ...variables });
341
479
  const upsertRecordWithID = (variables) => fetch$1({ url: "/db/{dbBranchName}/tables/{tableName}/data/{recordId}", method: "post", ...variables });
@@ -355,6 +493,11 @@ const queryTable = (variables) => fetch$1({
355
493
  method: "post",
356
494
  ...variables
357
495
  });
496
+ const searchTable = (variables) => fetch$1({
497
+ url: "/db/{dbBranchName}/tables/{tableName}/search",
498
+ method: "post",
499
+ ...variables
500
+ });
358
501
  const searchBranch = (variables) => fetch$1({
359
502
  url: "/db/{dbBranchName}/search",
360
503
  method: "post",
@@ -372,11 +515,21 @@ const operationsByTag = {
372
515
  updateWorkspaceMemberRole,
373
516
  removeWorkspaceMember,
374
517
  inviteWorkspaceMember,
518
+ updateWorkspaceMemberInvite,
375
519
  cancelWorkspaceMemberInvite,
376
520
  resendWorkspaceMemberInvite,
377
521
  acceptWorkspaceMemberInvite
378
522
  },
379
- database: { getDatabaseList, createDatabase, deleteDatabase },
523
+ database: {
524
+ getDatabaseList,
525
+ createDatabase,
526
+ deleteDatabase,
527
+ getDatabaseMetadata,
528
+ getGitBranchesMapping,
529
+ addGitBranchesEntry,
530
+ removeGitBranchesEntry,
531
+ resolveBranch
532
+ },
380
533
  branch: {
381
534
  getBranchList,
382
535
  getBranchDetails,
@@ -410,14 +563,15 @@ const operationsByTag = {
410
563
  getRecord,
411
564
  bulkInsertTableRecords,
412
565
  queryTable,
566
+ searchTable,
413
567
  searchBranch
414
568
  }
415
569
  };
416
570
 
417
571
  function getHostUrl(provider, type) {
418
- if (isValidAlias(provider)) {
572
+ if (isHostProviderAlias(provider)) {
419
573
  return providers[provider][type];
420
- } else if (isValidBuilder(provider)) {
574
+ } else if (isHostProviderBuilder(provider)) {
421
575
  return provider[type];
422
576
  }
423
577
  throw new Error("Invalid API provider");
@@ -432,10 +586,10 @@ const providers = {
432
586
  workspaces: "https://{workspaceId}.staging.xatabase.co"
433
587
  }
434
588
  };
435
- function isValidAlias(alias) {
589
+ function isHostProviderAlias(alias) {
436
590
  return isString(alias) && Object.keys(providers).includes(alias);
437
591
  }
438
- function isValidBuilder(builder) {
592
+ function isHostProviderBuilder(builder) {
439
593
  return isObject(builder) && isString(builder.main) && isString(builder.workspaces);
440
594
  }
441
595
 
@@ -443,7 +597,7 @@ var __accessCheck$7 = (obj, member, msg) => {
443
597
  if (!member.has(obj))
444
598
  throw TypeError("Cannot " + msg);
445
599
  };
446
- var __privateGet$6 = (obj, member, getter) => {
600
+ var __privateGet$7 = (obj, member, getter) => {
447
601
  __accessCheck$7(obj, member, "read from private field");
448
602
  return getter ? getter.call(obj) : member.get(obj);
449
603
  };
@@ -452,7 +606,7 @@ var __privateAdd$7 = (obj, member, value) => {
452
606
  throw TypeError("Cannot add the same private member more than once");
453
607
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
454
608
  };
455
- var __privateSet$5 = (obj, member, value, setter) => {
609
+ var __privateSet$7 = (obj, member, value, setter) => {
456
610
  __accessCheck$7(obj, member, "write to private field");
457
611
  setter ? setter.call(obj, value) : member.set(obj, value);
458
612
  return value;
@@ -463,46 +617,48 @@ class XataApiClient {
463
617
  __privateAdd$7(this, _extraProps, void 0);
464
618
  __privateAdd$7(this, _namespaces, {});
465
619
  const provider = options.host ?? "production";
466
- const apiKey = options?.apiKey ?? getAPIKey();
620
+ const apiKey = options.apiKey ?? getAPIKey();
621
+ const trace = options.trace ?? defaultTrace;
467
622
  if (!apiKey) {
468
623
  throw new Error("Could not resolve a valid apiKey");
469
624
  }
470
- __privateSet$5(this, _extraProps, {
625
+ __privateSet$7(this, _extraProps, {
471
626
  apiUrl: getHostUrl(provider, "main"),
472
627
  workspacesApiUrl: getHostUrl(provider, "workspaces"),
473
628
  fetchImpl: getFetchImplementation(options.fetch),
474
- apiKey
629
+ apiKey,
630
+ trace
475
631
  });
476
632
  }
477
633
  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;
634
+ if (!__privateGet$7(this, _namespaces).user)
635
+ __privateGet$7(this, _namespaces).user = new UserApi(__privateGet$7(this, _extraProps));
636
+ return __privateGet$7(this, _namespaces).user;
481
637
  }
482
638
  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;
639
+ if (!__privateGet$7(this, _namespaces).workspaces)
640
+ __privateGet$7(this, _namespaces).workspaces = new WorkspaceApi(__privateGet$7(this, _extraProps));
641
+ return __privateGet$7(this, _namespaces).workspaces;
486
642
  }
487
643
  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;
644
+ if (!__privateGet$7(this, _namespaces).databases)
645
+ __privateGet$7(this, _namespaces).databases = new DatabaseApi(__privateGet$7(this, _extraProps));
646
+ return __privateGet$7(this, _namespaces).databases;
491
647
  }
492
648
  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;
649
+ if (!__privateGet$7(this, _namespaces).branches)
650
+ __privateGet$7(this, _namespaces).branches = new BranchApi(__privateGet$7(this, _extraProps));
651
+ return __privateGet$7(this, _namespaces).branches;
496
652
  }
497
653
  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;
654
+ if (!__privateGet$7(this, _namespaces).tables)
655
+ __privateGet$7(this, _namespaces).tables = new TableApi(__privateGet$7(this, _extraProps));
656
+ return __privateGet$7(this, _namespaces).tables;
501
657
  }
502
658
  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;
659
+ if (!__privateGet$7(this, _namespaces).records)
660
+ __privateGet$7(this, _namespaces).records = new RecordsApi(__privateGet$7(this, _extraProps));
661
+ return __privateGet$7(this, _namespaces).records;
506
662
  }
507
663
  }
508
664
  _extraProps = new WeakMap();
@@ -594,6 +750,13 @@ class WorkspaceApi {
594
750
  ...this.extraProps
595
751
  });
596
752
  }
753
+ updateWorkspaceMemberInvite(workspaceId, inviteId, role) {
754
+ return operationsByTag.workspaces.updateWorkspaceMemberInvite({
755
+ pathParams: { workspaceId, inviteId },
756
+ body: { role },
757
+ ...this.extraProps
758
+ });
759
+ }
597
760
  cancelWorkspaceMemberInvite(workspaceId, inviteId) {
598
761
  return operationsByTag.workspaces.cancelWorkspaceMemberInvite({
599
762
  pathParams: { workspaceId, inviteId },
@@ -636,6 +799,39 @@ class DatabaseApi {
636
799
  ...this.extraProps
637
800
  });
638
801
  }
802
+ getDatabaseMetadata(workspace, dbName) {
803
+ return operationsByTag.database.getDatabaseMetadata({
804
+ pathParams: { workspace, dbName },
805
+ ...this.extraProps
806
+ });
807
+ }
808
+ getGitBranchesMapping(workspace, dbName) {
809
+ return operationsByTag.database.getGitBranchesMapping({
810
+ pathParams: { workspace, dbName },
811
+ ...this.extraProps
812
+ });
813
+ }
814
+ addGitBranchesEntry(workspace, dbName, body) {
815
+ return operationsByTag.database.addGitBranchesEntry({
816
+ pathParams: { workspace, dbName },
817
+ body,
818
+ ...this.extraProps
819
+ });
820
+ }
821
+ removeGitBranchesEntry(workspace, dbName, gitBranch) {
822
+ return operationsByTag.database.removeGitBranchesEntry({
823
+ pathParams: { workspace, dbName },
824
+ queryParams: { gitBranch },
825
+ ...this.extraProps
826
+ });
827
+ }
828
+ resolveBranch(workspace, dbName, gitBranch, fallbackBranch) {
829
+ return operationsByTag.database.resolveBranch({
830
+ pathParams: { workspace, dbName },
831
+ queryParams: { gitBranch, fallbackBranch },
832
+ ...this.extraProps
833
+ });
834
+ }
639
835
  }
640
836
  class BranchApi {
641
837
  constructor(extraProps) {
@@ -653,10 +849,10 @@ class BranchApi {
653
849
  ...this.extraProps
654
850
  });
655
851
  }
656
- createBranch(workspace, database, branch, from = "", options = {}) {
852
+ createBranch(workspace, database, branch, from, options = {}) {
657
853
  return operationsByTag.branch.createBranch({
658
854
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
659
- queryParams: { from },
855
+ queryParams: isString(from) ? { from } : void 0,
660
856
  body: options,
661
857
  ...this.extraProps
662
858
  });
@@ -781,9 +977,10 @@ class RecordsApi {
781
977
  constructor(extraProps) {
782
978
  this.extraProps = extraProps;
783
979
  }
784
- insertRecord(workspace, database, branch, tableName, record) {
980
+ insertRecord(workspace, database, branch, tableName, record, options = {}) {
785
981
  return operationsByTag.records.insertRecord({
786
982
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
983
+ queryParams: options,
787
984
  body: record,
788
985
  ...this.extraProps
789
986
  });
@@ -812,21 +1009,24 @@ class RecordsApi {
812
1009
  ...this.extraProps
813
1010
  });
814
1011
  }
815
- deleteRecord(workspace, database, branch, tableName, recordId) {
1012
+ deleteRecord(workspace, database, branch, tableName, recordId, options = {}) {
816
1013
  return operationsByTag.records.deleteRecord({
817
1014
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1015
+ queryParams: options,
818
1016
  ...this.extraProps
819
1017
  });
820
1018
  }
821
1019
  getRecord(workspace, database, branch, tableName, recordId, options = {}) {
822
1020
  return operationsByTag.records.getRecord({
823
1021
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName, recordId },
1022
+ queryParams: options,
824
1023
  ...this.extraProps
825
1024
  });
826
1025
  }
827
- bulkInsertTableRecords(workspace, database, branch, tableName, records) {
1026
+ bulkInsertTableRecords(workspace, database, branch, tableName, records, options = {}) {
828
1027
  return operationsByTag.records.bulkInsertTableRecords({
829
1028
  pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1029
+ queryParams: options,
830
1030
  body: { records },
831
1031
  ...this.extraProps
832
1032
  });
@@ -838,6 +1038,13 @@ class RecordsApi {
838
1038
  ...this.extraProps
839
1039
  });
840
1040
  }
1041
+ searchTable(workspace, database, branch, tableName, query) {
1042
+ return operationsByTag.records.searchTable({
1043
+ pathParams: { workspace, dbBranchName: `${database}:${branch}`, tableName },
1044
+ body: query,
1045
+ ...this.extraProps
1046
+ });
1047
+ }
841
1048
  searchBranch(workspace, database, branch, query) {
842
1049
  return operationsByTag.records.searchBranch({
843
1050
  pathParams: { workspace, dbBranchName: `${database}:${branch}` },
@@ -861,7 +1068,7 @@ var __accessCheck$6 = (obj, member, msg) => {
861
1068
  if (!member.has(obj))
862
1069
  throw TypeError("Cannot " + msg);
863
1070
  };
864
- var __privateGet$5 = (obj, member, getter) => {
1071
+ var __privateGet$6 = (obj, member, getter) => {
865
1072
  __accessCheck$6(obj, member, "read from private field");
866
1073
  return getter ? getter.call(obj) : member.get(obj);
867
1074
  };
@@ -870,30 +1077,30 @@ var __privateAdd$6 = (obj, member, value) => {
870
1077
  throw TypeError("Cannot add the same private member more than once");
871
1078
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
872
1079
  };
873
- var __privateSet$4 = (obj, member, value, setter) => {
1080
+ var __privateSet$6 = (obj, member, value, setter) => {
874
1081
  __accessCheck$6(obj, member, "write to private field");
875
1082
  setter ? setter.call(obj, value) : member.set(obj, value);
876
1083
  return value;
877
1084
  };
878
- var _query;
1085
+ var _query, _page;
879
1086
  class Page {
880
1087
  constructor(query, meta, records = []) {
881
1088
  __privateAdd$6(this, _query, void 0);
882
- __privateSet$4(this, _query, query);
1089
+ __privateSet$6(this, _query, query);
883
1090
  this.meta = meta;
884
- this.records = records;
1091
+ this.records = new RecordArray(this, records);
885
1092
  }
886
1093
  async nextPage(size, offset) {
887
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, after: this.meta.page.cursor } });
1094
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, after: this.meta.page.cursor } });
888
1095
  }
889
1096
  async previousPage(size, offset) {
890
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, before: this.meta.page.cursor } });
1097
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, before: this.meta.page.cursor } });
891
1098
  }
892
1099
  async firstPage(size, offset) {
893
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, first: this.meta.page.cursor } });
1100
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, first: this.meta.page.cursor } });
894
1101
  }
895
1102
  async lastPage(size, offset) {
896
- return __privateGet$5(this, _query).getPaginated({ page: { size, offset, last: this.meta.page.cursor } });
1103
+ return __privateGet$6(this, _query).getPaginated({ pagination: { size, offset, last: this.meta.page.cursor } });
897
1104
  }
898
1105
  hasNextPage() {
899
1106
  return this.meta.page.more;
@@ -901,15 +1108,62 @@ class Page {
901
1108
  }
902
1109
  _query = new WeakMap();
903
1110
  const PAGINATION_MAX_SIZE = 200;
904
- const PAGINATION_DEFAULT_SIZE = 200;
1111
+ const PAGINATION_DEFAULT_SIZE = 20;
905
1112
  const PAGINATION_MAX_OFFSET = 800;
906
1113
  const PAGINATION_DEFAULT_OFFSET = 0;
1114
+ function isCursorPaginationOptions(options) {
1115
+ return isDefined(options) && (isDefined(options.first) || isDefined(options.last) || isDefined(options.after) || isDefined(options.before));
1116
+ }
1117
+ const _RecordArray = class extends Array {
1118
+ constructor(...args) {
1119
+ super(..._RecordArray.parseConstructorParams(...args));
1120
+ __privateAdd$6(this, _page, void 0);
1121
+ __privateSet$6(this, _page, isObject(args[0]?.meta) ? args[0] : { meta: { page: { cursor: "", more: false } }, records: [] });
1122
+ }
1123
+ static parseConstructorParams(...args) {
1124
+ if (args.length === 1 && typeof args[0] === "number") {
1125
+ return new Array(args[0]);
1126
+ }
1127
+ if (args.length <= 2 && isObject(args[0]?.meta) && Array.isArray(args[1] ?? [])) {
1128
+ const result = args[1] ?? args[0].records ?? [];
1129
+ return new Array(...result);
1130
+ }
1131
+ return new Array(...args);
1132
+ }
1133
+ toArray() {
1134
+ return new Array(...this);
1135
+ }
1136
+ map(callbackfn, thisArg) {
1137
+ return this.toArray().map(callbackfn, thisArg);
1138
+ }
1139
+ async nextPage(size, offset) {
1140
+ const newPage = await __privateGet$6(this, _page).nextPage(size, offset);
1141
+ return new _RecordArray(newPage);
1142
+ }
1143
+ async previousPage(size, offset) {
1144
+ const newPage = await __privateGet$6(this, _page).previousPage(size, offset);
1145
+ return new _RecordArray(newPage);
1146
+ }
1147
+ async firstPage(size, offset) {
1148
+ const newPage = await __privateGet$6(this, _page).firstPage(size, offset);
1149
+ return new _RecordArray(newPage);
1150
+ }
1151
+ async lastPage(size, offset) {
1152
+ const newPage = await __privateGet$6(this, _page).lastPage(size, offset);
1153
+ return new _RecordArray(newPage);
1154
+ }
1155
+ hasNextPage() {
1156
+ return __privateGet$6(this, _page).meta.page.more;
1157
+ }
1158
+ };
1159
+ let RecordArray = _RecordArray;
1160
+ _page = new WeakMap();
907
1161
 
908
1162
  var __accessCheck$5 = (obj, member, msg) => {
909
1163
  if (!member.has(obj))
910
1164
  throw TypeError("Cannot " + msg);
911
1165
  };
912
- var __privateGet$4 = (obj, member, getter) => {
1166
+ var __privateGet$5 = (obj, member, getter) => {
913
1167
  __accessCheck$5(obj, member, "read from private field");
914
1168
  return getter ? getter.call(obj) : member.get(obj);
915
1169
  };
@@ -918,34 +1172,35 @@ var __privateAdd$5 = (obj, member, value) => {
918
1172
  throw TypeError("Cannot add the same private member more than once");
919
1173
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
920
1174
  };
921
- var __privateSet$3 = (obj, member, value, setter) => {
1175
+ var __privateSet$5 = (obj, member, value, setter) => {
922
1176
  __accessCheck$5(obj, member, "write to private field");
923
1177
  setter ? setter.call(obj, value) : member.set(obj, value);
924
1178
  return value;
925
1179
  };
926
1180
  var _table$1, _repository, _data;
927
1181
  const _Query = class {
928
- constructor(repository, table, data, parent) {
1182
+ constructor(repository, table, data, rawParent) {
929
1183
  __privateAdd$5(this, _table$1, void 0);
930
1184
  __privateAdd$5(this, _repository, void 0);
931
1185
  __privateAdd$5(this, _data, { filter: {} });
932
1186
  this.meta = { page: { cursor: "start", more: true } };
933
- this.records = [];
934
- __privateSet$3(this, _table$1, table);
1187
+ this.records = new RecordArray(this, []);
1188
+ __privateSet$5(this, _table$1, table);
935
1189
  if (repository) {
936
- __privateSet$3(this, _repository, repository);
1190
+ __privateSet$5(this, _repository, repository);
937
1191
  } else {
938
- __privateSet$3(this, _repository, this);
1192
+ __privateSet$5(this, _repository, this);
939
1193
  }
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;
1194
+ const parent = cleanParent(data, rawParent);
1195
+ __privateGet$5(this, _data).filter = data.filter ?? parent?.filter ?? {};
1196
+ __privateGet$5(this, _data).filter.$any = data.filter?.$any ?? parent?.filter?.$any;
1197
+ __privateGet$5(this, _data).filter.$all = data.filter?.$all ?? parent?.filter?.$all;
1198
+ __privateGet$5(this, _data).filter.$not = data.filter?.$not ?? parent?.filter?.$not;
1199
+ __privateGet$5(this, _data).filter.$none = data.filter?.$none ?? parent?.filter?.$none;
1200
+ __privateGet$5(this, _data).sort = data.sort ?? parent?.sort;
1201
+ __privateGet$5(this, _data).columns = data.columns ?? parent?.columns ?? ["*"];
1202
+ __privateGet$5(this, _data).pagination = data.pagination ?? parent?.pagination;
1203
+ __privateGet$5(this, _data).cache = data.cache ?? parent?.cache;
949
1204
  this.any = this.any.bind(this);
950
1205
  this.all = this.all.bind(this);
951
1206
  this.not = this.not.bind(this);
@@ -956,83 +1211,101 @@ const _Query = class {
956
1211
  Object.defineProperty(this, "repository", { enumerable: false });
957
1212
  }
958
1213
  getQueryOptions() {
959
- return __privateGet$4(this, _data);
1214
+ return __privateGet$5(this, _data);
960
1215
  }
961
1216
  key() {
962
- const { columns = [], filter = {}, sort = [], page = {} } = __privateGet$4(this, _data);
963
- const key = JSON.stringify({ columns, filter, sort, page });
1217
+ const { columns = [], filter = {}, sort = [], pagination = {} } = __privateGet$5(this, _data);
1218
+ const key = JSON.stringify({ columns, filter, sort, pagination });
964
1219
  return toBase64(key);
965
1220
  }
966
1221
  any(...queries) {
967
1222
  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));
1223
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $any } }, __privateGet$5(this, _data));
969
1224
  }
970
1225
  all(...queries) {
971
1226
  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));
1227
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
973
1228
  }
974
1229
  not(...queries) {
975
1230
  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));
1231
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $not } }, __privateGet$5(this, _data));
977
1232
  }
978
1233
  none(...queries) {
979
1234
  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));
1235
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $none } }, __privateGet$5(this, _data));
981
1236
  }
982
1237
  filter(a, b) {
983
1238
  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));
1239
+ const constraints = Object.entries(a ?? {}).map(([column, constraint]) => ({ [column]: constraint }));
1240
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1241
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
987
1242
  } 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));
1243
+ const constraints = isDefined(a) && isDefined(b) ? [{ [a]: this.defaultFilter(a, b) }] : void 0;
1244
+ const $all = compact([__privateGet$5(this, _data).filter?.$all].flat().concat(constraints));
1245
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { filter: { $all } }, __privateGet$5(this, _data));
990
1246
  }
991
1247
  }
992
- sort(column, direction) {
993
- const originalSort = [__privateGet$4(this, _data).sort ?? []].flat();
1248
+ defaultFilter(column, value) {
1249
+ const columnType = __privateGet$5(this, _table$1).schema?.columns.find(({ name }) => name === column)?.type;
1250
+ if (columnType === "multiple" && (isString(value) || isStringArray(value))) {
1251
+ return { $includes: value };
1252
+ }
1253
+ return value;
1254
+ }
1255
+ sort(column, direction = "asc") {
1256
+ const originalSort = [__privateGet$5(this, _data).sort ?? []].flat();
994
1257
  const sort = [...originalSort, { column, direction }];
995
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { sort }, __privateGet$4(this, _data));
1258
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { sort }, __privateGet$5(this, _data));
996
1259
  }
997
1260
  select(columns) {
998
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { columns }, __privateGet$4(this, _data));
1261
+ return new _Query(
1262
+ __privateGet$5(this, _repository),
1263
+ __privateGet$5(this, _table$1),
1264
+ { columns },
1265
+ __privateGet$5(this, _data)
1266
+ );
999
1267
  }
1000
1268
  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);
1269
+ const query = new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), options, __privateGet$5(this, _data));
1270
+ return __privateGet$5(this, _repository).query(query);
1003
1271
  }
1004
1272
  async *[Symbol.asyncIterator]() {
1005
- for await (const [record] of this.getIterator(1)) {
1273
+ for await (const [record] of this.getIterator({ batchSize: 1 })) {
1006
1274
  yield record;
1007
1275
  }
1008
1276
  }
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;
1277
+ async *getIterator(options = {}) {
1278
+ const { batchSize = 1 } = options;
1279
+ let page = await this.getPaginated({ ...options, pagination: { size: batchSize, offset: 0 } });
1280
+ let more = page.hasNextPage();
1281
+ yield page.records;
1282
+ while (more) {
1283
+ page = await page.nextPage();
1284
+ more = page.hasNextPage();
1285
+ yield page.records;
1017
1286
  }
1018
1287
  }
1019
1288
  async getMany(options = {}) {
1020
- const { records } = await this.getPaginated(options);
1021
- return records;
1289
+ const page = await this.getPaginated(options);
1290
+ if (page.hasNextPage() && options.pagination?.size === void 0) {
1291
+ console.trace("Calling getMany does not return all results. Paginate to get all results or call getAll.");
1292
+ }
1293
+ return page.records;
1022
1294
  }
1023
- async getAll(chunk = PAGINATION_MAX_SIZE, options = {}) {
1295
+ async getAll(options = {}) {
1296
+ const { batchSize = PAGINATION_MAX_SIZE, ...rest } = options;
1024
1297
  const results = [];
1025
- for await (const page of this.getIterator(chunk, options)) {
1298
+ for await (const page of this.getIterator({ ...rest, batchSize })) {
1026
1299
  results.push(...page);
1027
1300
  }
1028
1301
  return results;
1029
1302
  }
1030
1303
  async getFirst(options = {}) {
1031
- const records = await this.getMany({ ...options, page: { size: 1 } });
1032
- return records[0] || null;
1304
+ const records = await this.getMany({ ...options, pagination: { size: 1 } });
1305
+ return records[0] ?? null;
1033
1306
  }
1034
1307
  cache(ttl) {
1035
- return new _Query(__privateGet$4(this, _repository), __privateGet$4(this, _table$1), { cache: ttl }, __privateGet$4(this, _data));
1308
+ return new _Query(__privateGet$5(this, _repository), __privateGet$5(this, _table$1), { cache: ttl }, __privateGet$5(this, _data));
1036
1309
  }
1037
1310
  nextPage(size, offset) {
1038
1311
  return this.firstPage(size, offset);
@@ -1041,10 +1314,10 @@ const _Query = class {
1041
1314
  return this.firstPage(size, offset);
1042
1315
  }
1043
1316
  firstPage(size, offset) {
1044
- return this.getPaginated({ page: { size, offset } });
1317
+ return this.getPaginated({ pagination: { size, offset } });
1045
1318
  }
1046
1319
  lastPage(size, offset) {
1047
- return this.getPaginated({ page: { size, offset, before: "end" } });
1320
+ return this.getPaginated({ pagination: { size, offset, before: "end" } });
1048
1321
  }
1049
1322
  hasNextPage() {
1050
1323
  return this.meta.page.more;
@@ -1054,12 +1327,20 @@ let Query = _Query;
1054
1327
  _table$1 = new WeakMap();
1055
1328
  _repository = new WeakMap();
1056
1329
  _data = new WeakMap();
1330
+ function cleanParent(data, parent) {
1331
+ if (isCursorPaginationOptions(data.pagination)) {
1332
+ return { ...parent, sorting: void 0, filter: void 0 };
1333
+ }
1334
+ return parent;
1335
+ }
1057
1336
 
1058
1337
  function isIdentifiable(x) {
1059
1338
  return isObject(x) && isString(x?.id);
1060
1339
  }
1061
1340
  function isXataRecord(x) {
1062
- return isIdentifiable(x) && typeof x?.xata === "object" && typeof x?.xata?.version === "number";
1341
+ const record = x;
1342
+ const metadata = record?.getMetadata();
1343
+ return isIdentifiable(x) && isObject(metadata) && typeof metadata.version === "number";
1063
1344
  }
1064
1345
 
1065
1346
  function isSortFilterString(value) {
@@ -1089,7 +1370,7 @@ var __accessCheck$4 = (obj, member, msg) => {
1089
1370
  if (!member.has(obj))
1090
1371
  throw TypeError("Cannot " + msg);
1091
1372
  };
1092
- var __privateGet$3 = (obj, member, getter) => {
1373
+ var __privateGet$4 = (obj, member, getter) => {
1093
1374
  __accessCheck$4(obj, member, "read from private field");
1094
1375
  return getter ? getter.call(obj) : member.get(obj);
1095
1376
  };
@@ -1098,7 +1379,7 @@ var __privateAdd$4 = (obj, member, value) => {
1098
1379
  throw TypeError("Cannot add the same private member more than once");
1099
1380
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1100
1381
  };
1101
- var __privateSet$2 = (obj, member, value, setter) => {
1382
+ var __privateSet$4 = (obj, member, value, setter) => {
1102
1383
  __accessCheck$4(obj, member, "write to private field");
1103
1384
  setter ? setter.call(obj, value) : member.set(obj, value);
1104
1385
  return value;
@@ -1107,304 +1388,355 @@ var __privateMethod$2 = (obj, member, method) => {
1107
1388
  __accessCheck$4(obj, member, "access private method");
1108
1389
  return method;
1109
1390
  };
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;
1391
+ 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
1392
  class Repository extends Query {
1112
1393
  }
1113
1394
  class RestRepository extends Query {
1114
1395
  constructor(options) {
1115
- super(null, options.table, {});
1396
+ super(
1397
+ null,
1398
+ { name: options.table, schema: options.schemaTables?.find((table) => table.name === options.table) },
1399
+ {}
1400
+ );
1116
1401
  __privateAdd$4(this, _insertRecordWithoutId);
1117
1402
  __privateAdd$4(this, _insertRecordWithId);
1118
1403
  __privateAdd$4(this, _bulkInsertTableRecords);
1119
1404
  __privateAdd$4(this, _updateRecordWithID);
1120
1405
  __privateAdd$4(this, _upsertRecordWithID);
1121
1406
  __privateAdd$4(this, _deleteRecord);
1122
- __privateAdd$4(this, _invalidateCache);
1123
- __privateAdd$4(this, _setCacheRecord);
1124
- __privateAdd$4(this, _getCacheRecord);
1125
1407
  __privateAdd$4(this, _setCacheQuery);
1126
1408
  __privateAdd$4(this, _getCacheQuery);
1409
+ __privateAdd$4(this, _getSchemaTables$1);
1127
1410
  __privateAdd$4(this, _table, void 0);
1128
- __privateAdd$4(this, _links, void 0);
1129
1411
  __privateAdd$4(this, _getFetchProps, void 0);
1412
+ __privateAdd$4(this, _db, void 0);
1130
1413
  __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
1414
+ __privateAdd$4(this, _schemaTables$2, void 0);
1415
+ __privateAdd$4(this, _trace, void 0);
1416
+ __privateSet$4(this, _table, options.table);
1417
+ __privateSet$4(this, _getFetchProps, options.pluginOptions.getFetchProps);
1418
+ __privateSet$4(this, _db, options.db);
1419
+ __privateSet$4(this, _cache, options.pluginOptions.cache);
1420
+ __privateSet$4(this, _schemaTables$2, options.schemaTables);
1421
+ const trace = options.pluginOptions.trace ?? defaultTrace;
1422
+ __privateSet$4(this, _trace, async (name, fn, options2 = {}) => {
1423
+ return trace(name, fn, {
1424
+ ...options2,
1425
+ [TraceAttributes.TABLE]: __privateGet$4(this, _table),
1426
+ [TraceAttributes.KIND]: "sdk-operation",
1427
+ [TraceAttributes.VERSION]: VERSION
1173
1428
  });
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;
1429
+ });
1430
+ }
1431
+ async create(a, b, c) {
1432
+ return __privateGet$4(this, _trace).call(this, "create", async () => {
1433
+ if (Array.isArray(a)) {
1434
+ if (a.length === 0)
1435
+ return [];
1436
+ const columns = isStringArray(b) ? b : void 0;
1437
+ return __privateMethod$2(this, _bulkInsertTableRecords, bulkInsertTableRecords_fn).call(this, a, columns);
1178
1438
  }
1179
- throw e;
1180
- }
1439
+ if (isString(a) && isObject(b)) {
1440
+ if (a === "")
1441
+ throw new Error("The id can't be empty");
1442
+ const columns = isStringArray(c) ? c : void 0;
1443
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a, b, columns);
1444
+ }
1445
+ if (isObject(a) && isString(a.id)) {
1446
+ if (a.id === "")
1447
+ throw new Error("The id can't be empty");
1448
+ const columns = isStringArray(b) ? b : void 0;
1449
+ return __privateMethod$2(this, _insertRecordWithId, insertRecordWithId_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1450
+ }
1451
+ if (isObject(a)) {
1452
+ const columns = isStringArray(b) ? b : void 0;
1453
+ return __privateMethod$2(this, _insertRecordWithoutId, insertRecordWithoutId_fn).call(this, a, columns);
1454
+ }
1455
+ throw new Error("Invalid arguments for create method");
1456
+ });
1181
1457
  }
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");
1458
+ async read(a, b) {
1459
+ return __privateGet$4(this, _trace).call(this, "read", async () => {
1460
+ const columns = isStringArray(b) ? b : ["*"];
1461
+ if (Array.isArray(a)) {
1462
+ if (a.length === 0)
1463
+ return [];
1464
+ const ids = a.map((item) => extractId(item));
1465
+ const finalObjects = await this.getAll({ filter: { id: { $any: compact(ids) } }, columns });
1466
+ const dictionary = finalObjects.reduce((acc, object) => {
1467
+ acc[object.id] = object;
1468
+ return acc;
1469
+ }, {});
1470
+ return ids.map((id2) => dictionary[id2 ?? ""] ?? null);
1186
1471
  }
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");
1472
+ const id = extractId(a);
1473
+ if (id) {
1474
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1475
+ try {
1476
+ const response = await getRecord({
1477
+ pathParams: {
1478
+ workspace: "{workspaceId}",
1479
+ dbBranchName: "{dbBranch}",
1480
+ tableName: __privateGet$4(this, _table),
1481
+ recordId: id
1482
+ },
1483
+ queryParams: { columns },
1484
+ ...fetchProps
1485
+ });
1486
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1487
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1488
+ } catch (e) {
1489
+ if (isObject(e) && e.status === 404) {
1490
+ return null;
1491
+ }
1492
+ throw e;
1493
+ }
1494
+ }
1495
+ return null;
1496
+ });
1202
1497
  }
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");
1498
+ async update(a, b, c) {
1499
+ return __privateGet$4(this, _trace).call(this, "update", async () => {
1500
+ if (Array.isArray(a)) {
1501
+ if (a.length === 0)
1502
+ return [];
1503
+ if (a.length > 100) {
1504
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1505
+ }
1506
+ const columns = isStringArray(b) ? b : ["*"];
1507
+ return Promise.all(a.map((object) => this.update(object, columns)));
1207
1508
  }
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");
1509
+ if (isString(a) && isObject(b)) {
1510
+ const columns = isStringArray(c) ? c : void 0;
1511
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a, b, columns);
1512
+ }
1513
+ if (isObject(a) && isString(a.id)) {
1514
+ const columns = isStringArray(b) ? b : void 0;
1515
+ return __privateMethod$2(this, _updateRecordWithID, updateRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1516
+ }
1517
+ throw new Error("Invalid arguments for update method");
1518
+ });
1223
1519
  }
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");
1520
+ async createOrUpdate(a, b, c) {
1521
+ return __privateGet$4(this, _trace).call(this, "createOrUpdate", async () => {
1522
+ if (Array.isArray(a)) {
1523
+ if (a.length === 0)
1524
+ return [];
1525
+ if (a.length > 100) {
1526
+ console.warn("Bulk update operation is not optimized in the Xata API yet, this request might be slow");
1527
+ }
1528
+ const columns = isStringArray(b) ? b : ["*"];
1529
+ return Promise.all(a.map((object) => this.createOrUpdate(object, columns)));
1228
1530
  }
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");
1531
+ if (isString(a) && isObject(b)) {
1532
+ const columns = isStringArray(c) ? c : void 0;
1533
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a, b, columns);
1534
+ }
1535
+ if (isObject(a) && isString(a.id)) {
1536
+ const columns = isStringArray(c) ? c : void 0;
1537
+ return __privateMethod$2(this, _upsertRecordWithID, upsertRecordWithID_fn).call(this, a.id, { ...a, id: void 0 }, columns);
1538
+ }
1539
+ throw new Error("Invalid arguments for createOrUpdate method");
1540
+ });
1541
+ }
1542
+ async delete(a, b) {
1543
+ return __privateGet$4(this, _trace).call(this, "delete", async () => {
1544
+ if (Array.isArray(a)) {
1545
+ if (a.length === 0)
1546
+ return [];
1547
+ if (a.length > 100) {
1548
+ console.warn("Bulk delete operation is not optimized in the Xata API yet, this request might be slow");
1549
+ }
1550
+ return Promise.all(a.map((id) => this.delete(id, b)));
1551
+ }
1552
+ if (isString(a)) {
1553
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a, b);
1554
+ }
1555
+ if (isObject(a) && isString(a.id)) {
1556
+ return __privateMethod$2(this, _deleteRecord, deleteRecord_fn).call(this, a.id, b);
1557
+ }
1558
+ throw new Error("Invalid arguments for delete method");
1559
+ });
1243
1560
  }
1244
1561
  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
1562
+ return __privateGet$4(this, _trace).call(this, "search", async () => {
1563
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1564
+ const { records } = await searchTable({
1565
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1566
+ body: {
1567
+ query,
1568
+ fuzziness: options.fuzziness,
1569
+ prefix: options.prefix,
1570
+ highlight: options.highlight,
1571
+ filter: options.filter,
1572
+ boosters: options.boosters
1573
+ },
1574
+ ...fetchProps
1575
+ });
1576
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1577
+ return records.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1250
1578
  });
1251
- return records.map((item) => initObject(this.db, __privateGet$3(this, _links), __privateGet$3(this, _table), item));
1252
1579
  }
1253
1580
  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
1581
+ return __privateGet$4(this, _trace).call(this, "query", async () => {
1582
+ const cacheQuery = await __privateMethod$2(this, _getCacheQuery, getCacheQuery_fn).call(this, query);
1583
+ if (cacheQuery)
1584
+ return new Page(query, cacheQuery.meta, cacheQuery.records);
1585
+ const data = query.getQueryOptions();
1586
+ const body = {
1587
+ filter: cleanFilter(data.filter),
1588
+ sort: data.sort !== void 0 ? buildSortFilter(data.sort) : void 0,
1589
+ page: data.pagination,
1590
+ columns: data.columns
1591
+ };
1592
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1593
+ const { meta, records: objects } = await queryTable({
1594
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1595
+ body,
1596
+ ...fetchProps
1597
+ });
1598
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1599
+ const records = objects.map((record) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), record));
1600
+ await __privateMethod$2(this, _setCacheQuery, setCacheQuery_fn).call(this, query, meta, records);
1601
+ return new Page(query, meta, records);
1269
1602
  });
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
1603
  }
1274
1604
  }
1275
1605
  _table = new WeakMap();
1276
- _links = new WeakMap();
1277
1606
  _getFetchProps = new WeakMap();
1607
+ _db = new WeakMap();
1278
1608
  _cache = new WeakMap();
1609
+ _schemaTables$2 = new WeakMap();
1610
+ _trace = new WeakMap();
1279
1611
  _insertRecordWithoutId = new WeakSet();
1280
- insertRecordWithoutId_fn = async function(object) {
1281
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1612
+ insertRecordWithoutId_fn = async function(object, columns = ["*"]) {
1613
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1282
1614
  const record = transformObjectLinks(object);
1283
1615
  const response = await insertRecord({
1284
1616
  pathParams: {
1285
1617
  workspace: "{workspaceId}",
1286
1618
  dbBranchName: "{dbBranch}",
1287
- tableName: __privateGet$3(this, _table)
1619
+ tableName: __privateGet$4(this, _table)
1288
1620
  },
1621
+ queryParams: { columns },
1289
1622
  body: record,
1290
1623
  ...fetchProps
1291
1624
  });
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;
1625
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1626
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1297
1627
  };
1298
1628
  _insertRecordWithId = new WeakSet();
1299
- insertRecordWithId_fn = async function(recordId, object) {
1300
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1629
+ insertRecordWithId_fn = async function(recordId, object, columns = ["*"]) {
1630
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1301
1631
  const record = transformObjectLinks(object);
1302
1632
  const response = await insertRecordWithID({
1303
1633
  pathParams: {
1304
1634
  workspace: "{workspaceId}",
1305
1635
  dbBranchName: "{dbBranch}",
1306
- tableName: __privateGet$3(this, _table),
1636
+ tableName: __privateGet$4(this, _table),
1307
1637
  recordId
1308
1638
  },
1309
1639
  body: record,
1310
- queryParams: { createOnly: true },
1640
+ queryParams: { createOnly: true, columns },
1311
1641
  ...fetchProps
1312
1642
  });
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;
1643
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1644
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1318
1645
  };
1319
1646
  _bulkInsertTableRecords = new WeakSet();
1320
- bulkInsertTableRecords_fn = async function(objects) {
1321
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1647
+ bulkInsertTableRecords_fn = async function(objects, columns = ["*"]) {
1648
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1322
1649
  const records = objects.map((object) => transformObjectLinks(object));
1323
1650
  const response = await bulkInsertTableRecords({
1324
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table) },
1651
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table) },
1652
+ queryParams: { columns },
1325
1653
  body: { records },
1326
1654
  ...fetchProps
1327
1655
  });
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");
1656
+ if (!isResponseWithRecords(response)) {
1657
+ throw new Error("Request included columns but server didn't include them");
1331
1658
  }
1332
- return finalObjects;
1659
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1660
+ return response.records?.map((item) => initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), item));
1333
1661
  };
1334
1662
  _updateRecordWithID = new WeakSet();
1335
- updateRecordWithID_fn = async function(recordId, object) {
1336
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1663
+ updateRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1664
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1337
1665
  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;
1666
+ try {
1667
+ const response = await updateRecordWithID({
1668
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1669
+ queryParams: { columns },
1670
+ body: record,
1671
+ ...fetchProps
1672
+ });
1673
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1674
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1675
+ } catch (e) {
1676
+ if (isObject(e) && e.status === 404) {
1677
+ return null;
1678
+ }
1679
+ throw e;
1680
+ }
1347
1681
  };
1348
1682
  _upsertRecordWithID = new WeakSet();
1349
- upsertRecordWithID_fn = async function(recordId, object) {
1350
- const fetchProps = await __privateGet$3(this, _getFetchProps).call(this);
1683
+ upsertRecordWithID_fn = async function(recordId, object, columns = ["*"]) {
1684
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1351
1685
  const response = await upsertRecordWithID({
1352
- pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$3(this, _table), recordId },
1686
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1687
+ queryParams: { columns },
1353
1688
  body: object,
1354
1689
  ...fetchProps
1355
1690
  });
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;
1691
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1692
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1360
1693
  };
1361
1694
  _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);
1695
+ deleteRecord_fn = async function(recordId, columns = ["*"]) {
1696
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1697
+ try {
1698
+ const response = await deleteRecord({
1699
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}", tableName: __privateGet$4(this, _table), recordId },
1700
+ queryParams: { columns },
1701
+ ...fetchProps
1702
+ });
1703
+ const schemaTables = await __privateMethod$2(this, _getSchemaTables$1, getSchemaTables_fn$1).call(this);
1704
+ return initObject(__privateGet$4(this, _db), schemaTables, __privateGet$4(this, _table), response);
1705
+ } catch (e) {
1706
+ if (isObject(e) && e.status === 404) {
1707
+ return null;
1708
+ }
1709
+ throw e;
1378
1710
  }
1379
1711
  };
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
1712
  _setCacheQuery = new WeakSet();
1393
1713
  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 });
1714
+ await __privateGet$4(this, _cache).set(`query_${__privateGet$4(this, _table)}:${query.key()}`, { date: new Date(), meta, records });
1395
1715
  };
1396
1716
  _getCacheQuery = new WeakSet();
1397
1717
  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);
1718
+ const key = `query_${__privateGet$4(this, _table)}:${query.key()}`;
1719
+ const result = await __privateGet$4(this, _cache).get(key);
1400
1720
  if (!result)
1401
1721
  return null;
1402
- const { cache: ttl = __privateGet$3(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1403
- if (!ttl || ttl < 0)
1404
- return result;
1722
+ const { cache: ttl = __privateGet$4(this, _cache).defaultQueryTTL } = query.getQueryOptions();
1723
+ if (ttl < 0)
1724
+ return null;
1405
1725
  const hasExpired = result.date.getTime() + ttl < Date.now();
1406
1726
  return hasExpired ? null : result;
1407
1727
  };
1728
+ _getSchemaTables$1 = new WeakSet();
1729
+ getSchemaTables_fn$1 = async function() {
1730
+ if (__privateGet$4(this, _schemaTables$2))
1731
+ return __privateGet$4(this, _schemaTables$2);
1732
+ const fetchProps = await __privateGet$4(this, _getFetchProps).call(this);
1733
+ const { schema } = await getBranchDetails({
1734
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1735
+ ...fetchProps
1736
+ });
1737
+ __privateSet$4(this, _schemaTables$2, schema.tables);
1738
+ return schema.tables;
1739
+ };
1408
1740
  const transformObjectLinks = (object) => {
1409
1741
  return Object.entries(object).reduce((acc, [key, value]) => {
1410
1742
  if (key === "xata")
@@ -1412,47 +1744,76 @@ const transformObjectLinks = (object) => {
1412
1744
  return { ...acc, [key]: isIdentifiable(value) ? value.id : value };
1413
1745
  }, {});
1414
1746
  };
1415
- const initObject = (db, links, table, object) => {
1747
+ const initObject = (db, schemaTables, table, object) => {
1416
1748
  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);
1749
+ const { xata, ...rest } = object ?? {};
1750
+ Object.assign(result, rest);
1751
+ const { columns } = schemaTables.find(({ name }) => name === table) ?? {};
1752
+ if (!columns)
1753
+ console.error(`Table ${table} not found in schema`);
1754
+ for (const column of columns ?? []) {
1755
+ const value = result[column.name];
1756
+ switch (column.type) {
1757
+ case "datetime": {
1758
+ const date = value !== void 0 ? new Date(value) : void 0;
1759
+ if (date && isNaN(date.getTime())) {
1760
+ console.error(`Failed to parse date ${value} for field ${column.name}`);
1761
+ } else if (date) {
1762
+ result[column.name] = date;
1763
+ }
1764
+ break;
1765
+ }
1766
+ case "link": {
1767
+ const linkTable = column.link?.table;
1768
+ if (!linkTable) {
1769
+ console.error(`Failed to parse link for field ${column.name}`);
1770
+ } else if (isObject(value)) {
1771
+ result[column.name] = initObject(db, schemaTables, linkTable, value);
1772
+ }
1773
+ break;
1774
+ }
1424
1775
  }
1425
1776
  }
1426
- result.read = function() {
1427
- return db[table].read(result["id"]);
1777
+ result.read = function(columns2) {
1778
+ return db[table].read(result["id"], columns2);
1428
1779
  };
1429
- result.update = function(data) {
1430
- return db[table].update(result["id"], data);
1780
+ result.update = function(data, columns2) {
1781
+ return db[table].update(result["id"], data, columns2);
1431
1782
  };
1432
1783
  result.delete = function() {
1433
1784
  return db[table].delete(result["id"]);
1434
1785
  };
1435
- for (const prop of ["read", "update", "delete"]) {
1786
+ result.getMetadata = function() {
1787
+ return xata;
1788
+ };
1789
+ for (const prop of ["read", "update", "delete", "getMetadata"]) {
1436
1790
  Object.defineProperty(result, prop, { enumerable: false });
1437
1791
  }
1438
1792
  Object.freeze(result);
1439
1793
  return result;
1440
1794
  };
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;
1795
+ function isResponseWithRecords(value) {
1796
+ return isObject(value) && Array.isArray(value.records);
1797
+ }
1798
+ function extractId(value) {
1799
+ if (isString(value))
1800
+ return value;
1801
+ if (isObject(value) && isString(value.id))
1802
+ return value.id;
1803
+ return void 0;
1804
+ }
1805
+ function cleanFilter(filter) {
1806
+ if (!filter)
1807
+ return void 0;
1808
+ const values = Object.values(filter).filter(Boolean).filter((value) => Array.isArray(value) ? value.length > 0 : true);
1809
+ return values.length > 0 ? filter : void 0;
1449
1810
  }
1450
1811
 
1451
1812
  var __accessCheck$3 = (obj, member, msg) => {
1452
1813
  if (!member.has(obj))
1453
1814
  throw TypeError("Cannot " + msg);
1454
1815
  };
1455
- var __privateGet$2 = (obj, member, getter) => {
1816
+ var __privateGet$3 = (obj, member, getter) => {
1456
1817
  __accessCheck$3(obj, member, "read from private field");
1457
1818
  return getter ? getter.call(obj) : member.get(obj);
1458
1819
  };
@@ -1461,7 +1822,7 @@ var __privateAdd$3 = (obj, member, value) => {
1461
1822
  throw TypeError("Cannot add the same private member more than once");
1462
1823
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1463
1824
  };
1464
- var __privateSet$1 = (obj, member, value, setter) => {
1825
+ var __privateSet$3 = (obj, member, value, setter) => {
1465
1826
  __accessCheck$3(obj, member, "write to private field");
1466
1827
  setter ? setter.call(obj, value) : member.set(obj, value);
1467
1828
  return value;
@@ -1470,46 +1831,52 @@ var _map;
1470
1831
  class SimpleCache {
1471
1832
  constructor(options = {}) {
1472
1833
  __privateAdd$3(this, _map, void 0);
1473
- __privateSet$1(this, _map, /* @__PURE__ */ new Map());
1834
+ __privateSet$3(this, _map, /* @__PURE__ */ new Map());
1474
1835
  this.capacity = options.max ?? 500;
1475
- this.cacheRecords = options.cacheRecords ?? true;
1476
1836
  this.defaultQueryTTL = options.defaultQueryTTL ?? 60 * 1e3;
1477
1837
  }
1478
1838
  async getAll() {
1479
- return Object.fromEntries(__privateGet$2(this, _map));
1839
+ return Object.fromEntries(__privateGet$3(this, _map));
1480
1840
  }
1481
1841
  async get(key) {
1482
- return __privateGet$2(this, _map).get(key) ?? null;
1842
+ return __privateGet$3(this, _map).get(key) ?? null;
1483
1843
  }
1484
1844
  async set(key, value) {
1485
1845
  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;
1846
+ __privateGet$3(this, _map).set(key, value);
1847
+ if (__privateGet$3(this, _map).size > this.capacity) {
1848
+ const leastRecentlyUsed = __privateGet$3(this, _map).keys().next().value;
1489
1849
  await this.delete(leastRecentlyUsed);
1490
1850
  }
1491
1851
  }
1492
1852
  async delete(key) {
1493
- __privateGet$2(this, _map).delete(key);
1853
+ __privateGet$3(this, _map).delete(key);
1494
1854
  }
1495
1855
  async clear() {
1496
- return __privateGet$2(this, _map).clear();
1856
+ return __privateGet$3(this, _map).clear();
1497
1857
  }
1498
1858
  }
1499
1859
  _map = new WeakMap();
1500
1860
 
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 });
1861
+ const greaterThan = (value) => ({ $gt: value });
1862
+ const gt = greaterThan;
1863
+ const greaterThanEquals = (value) => ({ $ge: value });
1864
+ const greaterEquals = greaterThanEquals;
1865
+ const gte = greaterThanEquals;
1866
+ const ge = greaterThanEquals;
1867
+ const lessThan = (value) => ({ $lt: value });
1868
+ const lt = lessThan;
1869
+ const lessThanEquals = (value) => ({ $le: value });
1870
+ const lessEquals = lessThanEquals;
1871
+ const lte = lessThanEquals;
1872
+ const le = lessThanEquals;
1507
1873
  const exists = (column) => ({ $exists: column });
1508
1874
  const notExists = (column) => ({ $notExists: column });
1509
1875
  const startsWith = (value) => ({ $startsWith: value });
1510
1876
  const endsWith = (value) => ({ $endsWith: value });
1511
1877
  const pattern = (value) => ({ $pattern: value });
1512
1878
  const is = (value) => ({ $is: value });
1879
+ const equals = is;
1513
1880
  const isNot = (value) => ({ $isNot: value });
1514
1881
  const contains = (value) => ({ $contains: value });
1515
1882
  const includes = (value) => ({ $includes: value });
@@ -1521,7 +1888,7 @@ var __accessCheck$2 = (obj, member, msg) => {
1521
1888
  if (!member.has(obj))
1522
1889
  throw TypeError("Cannot " + msg);
1523
1890
  };
1524
- var __privateGet$1 = (obj, member, getter) => {
1891
+ var __privateGet$2 = (obj, member, getter) => {
1525
1892
  __accessCheck$2(obj, member, "read from private field");
1526
1893
  return getter ? getter.call(obj) : member.get(obj);
1527
1894
  };
@@ -1530,130 +1897,178 @@ var __privateAdd$2 = (obj, member, value) => {
1530
1897
  throw TypeError("Cannot add the same private member more than once");
1531
1898
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1532
1899
  };
1533
- var _tables;
1900
+ var __privateSet$2 = (obj, member, value, setter) => {
1901
+ __accessCheck$2(obj, member, "write to private field");
1902
+ setter ? setter.call(obj, value) : member.set(obj, value);
1903
+ return value;
1904
+ };
1905
+ var _tables, _schemaTables$1;
1534
1906
  class SchemaPlugin extends XataPlugin {
1535
- constructor(links, tableNames) {
1907
+ constructor(schemaTables) {
1536
1908
  super();
1537
- this.links = links;
1538
- this.tableNames = tableNames;
1539
1909
  __privateAdd$2(this, _tables, {});
1910
+ __privateAdd$2(this, _schemaTables$1, void 0);
1911
+ __privateSet$2(this, _schemaTables$1, schemaTables);
1540
1912
  }
1541
1913
  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 });
1914
+ const db = new Proxy(
1915
+ {},
1916
+ {
1917
+ get: (_target, table) => {
1918
+ if (!isString(table))
1919
+ throw new Error("Invalid table name");
1920
+ if (__privateGet$2(this, _tables)[table] === void 0) {
1921
+ __privateGet$2(this, _tables)[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1922
+ }
1923
+ return __privateGet$2(this, _tables)[table];
1549
1924
  }
1550
- return __privateGet$1(this, _tables)[table];
1551
1925
  }
1552
- });
1553
- for (const table of this.tableNames ?? []) {
1554
- db[table] = new RestRepository({ db, pluginOptions, table, links });
1926
+ );
1927
+ const tableNames = __privateGet$2(this, _schemaTables$1)?.map(({ name }) => name) ?? [];
1928
+ for (const table of tableNames) {
1929
+ db[table] = new RestRepository({ db, pluginOptions, table, schemaTables: __privateGet$2(this, _schemaTables$1) });
1555
1930
  }
1556
1931
  return db;
1557
1932
  }
1558
1933
  }
1559
1934
  _tables = new WeakMap();
1935
+ _schemaTables$1 = new WeakMap();
1560
1936
 
1561
1937
  var __accessCheck$1 = (obj, member, msg) => {
1562
1938
  if (!member.has(obj))
1563
1939
  throw TypeError("Cannot " + msg);
1564
1940
  };
1941
+ var __privateGet$1 = (obj, member, getter) => {
1942
+ __accessCheck$1(obj, member, "read from private field");
1943
+ return getter ? getter.call(obj) : member.get(obj);
1944
+ };
1565
1945
  var __privateAdd$1 = (obj, member, value) => {
1566
1946
  if (member.has(obj))
1567
1947
  throw TypeError("Cannot add the same private member more than once");
1568
1948
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1569
1949
  };
1950
+ var __privateSet$1 = (obj, member, value, setter) => {
1951
+ __accessCheck$1(obj, member, "write to private field");
1952
+ setter ? setter.call(obj, value) : member.set(obj, value);
1953
+ return value;
1954
+ };
1570
1955
  var __privateMethod$1 = (obj, member, method) => {
1571
1956
  __accessCheck$1(obj, member, "access private method");
1572
1957
  return method;
1573
1958
  };
1574
- var _search, search_fn;
1959
+ var _schemaTables, _search, search_fn, _getSchemaTables, getSchemaTables_fn;
1575
1960
  class SearchPlugin extends XataPlugin {
1576
- constructor(db, links) {
1961
+ constructor(db, schemaTables) {
1577
1962
  super();
1578
1963
  this.db = db;
1579
- this.links = links;
1580
1964
  __privateAdd$1(this, _search);
1965
+ __privateAdd$1(this, _getSchemaTables);
1966
+ __privateAdd$1(this, _schemaTables, void 0);
1967
+ __privateSet$1(this, _schemaTables, schemaTables);
1581
1968
  }
1582
1969
  build({ getFetchProps }) {
1583
1970
  return {
1584
1971
  all: async (query, options = {}) => {
1585
1972
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1973
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1586
1974
  return records.map((record) => {
1587
1975
  const { table = "orphan" } = record.xata;
1588
- return { table, record: initObject(this.db, this.links, table, record) };
1976
+ return { table, record: initObject(this.db, schemaTables, table, record) };
1589
1977
  });
1590
1978
  },
1591
1979
  byTable: async (query, options = {}) => {
1592
1980
  const records = await __privateMethod$1(this, _search, search_fn).call(this, query, options, getFetchProps);
1981
+ const schemaTables = await __privateMethod$1(this, _getSchemaTables, getSchemaTables_fn).call(this, getFetchProps);
1593
1982
  return records.reduce((acc, record) => {
1594
1983
  const { table = "orphan" } = record.xata;
1595
1984
  const items = acc[table] ?? [];
1596
- const item = initObject(this.db, this.links, table, record);
1985
+ const item = initObject(this.db, schemaTables, table, record);
1597
1986
  return { ...acc, [table]: [...items, item] };
1598
1987
  }, {});
1599
1988
  }
1600
1989
  };
1601
1990
  }
1602
1991
  }
1992
+ _schemaTables = new WeakMap();
1603
1993
  _search = new WeakSet();
1604
1994
  search_fn = async function(query, options, getFetchProps) {
1605
1995
  const fetchProps = await getFetchProps();
1606
- const { tables, fuzziness } = options ?? {};
1996
+ const { tables, fuzziness, highlight, prefix } = options ?? {};
1607
1997
  const { records } = await searchBranch({
1608
1998
  pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
1609
- body: { tables, query, fuzziness },
1999
+ body: { tables, query, fuzziness, prefix, highlight },
1610
2000
  ...fetchProps
1611
2001
  });
1612
2002
  return records;
1613
2003
  };
2004
+ _getSchemaTables = new WeakSet();
2005
+ getSchemaTables_fn = async function(getFetchProps) {
2006
+ if (__privateGet$1(this, _schemaTables))
2007
+ return __privateGet$1(this, _schemaTables);
2008
+ const fetchProps = await getFetchProps();
2009
+ const { schema } = await getBranchDetails({
2010
+ pathParams: { workspace: "{workspaceId}", dbBranchName: "{dbBranch}" },
2011
+ ...fetchProps
2012
+ });
2013
+ __privateSet$1(this, _schemaTables, schema.tables);
2014
+ return schema.tables;
2015
+ };
1614
2016
 
1615
2017
  const isBranchStrategyBuilder = (strategy) => {
1616
2018
  return typeof strategy === "function";
1617
2019
  };
1618
2020
 
1619
- const envBranchNames = [
1620
- "XATA_BRANCH",
1621
- "VERCEL_GIT_COMMIT_REF",
1622
- "CF_PAGES_BRANCH",
1623
- "BRANCH"
1624
- ];
1625
- const defaultBranch = "main";
1626
2021
  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;
2022
+ const { branch, envBranch } = getEnvironment();
2023
+ if (branch) {
2024
+ const details = await getDatabaseBranch(branch, options);
2025
+ if (details)
2026
+ return branch;
2027
+ console.warn(`Branch ${branch} not found in Xata. Ignoring...`);
2028
+ }
2029
+ const gitBranch = envBranch || await getGitBranch();
2030
+ return resolveXataBranch(gitBranch, options);
1637
2031
  }
1638
2032
  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);
2033
+ const branch = await getCurrentBranchName(options);
2034
+ return getDatabaseBranch(branch, options);
2035
+ }
2036
+ async function resolveXataBranch(gitBranch, options) {
2037
+ const databaseURL = options?.databaseURL || getDatabaseURL();
2038
+ const apiKey = options?.apiKey || getAPIKey();
2039
+ if (!databaseURL)
2040
+ throw new Error(
2041
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2042
+ );
2043
+ if (!apiKey)
2044
+ throw new Error(
2045
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2046
+ );
2047
+ const [protocol, , host, , dbName] = databaseURL.split("/");
2048
+ const [workspace] = host.split(".");
2049
+ const { fallbackBranch } = getEnvironment();
2050
+ const { branch } = await resolveBranch({
2051
+ apiKey,
2052
+ apiUrl: databaseURL,
2053
+ fetchImpl: getFetchImplementation(options?.fetchImpl),
2054
+ workspacesApiUrl: `${protocol}//${host}`,
2055
+ pathParams: { dbName, workspace },
2056
+ queryParams: { gitBranch, fallbackBranch },
2057
+ trace: defaultTrace
2058
+ });
2059
+ return branch;
1649
2060
  }
1650
2061
  async function getDatabaseBranch(branch, options) {
1651
2062
  const databaseURL = options?.databaseURL || getDatabaseURL();
1652
2063
  const apiKey = options?.apiKey || getAPIKey();
1653
2064
  if (!databaseURL)
1654
- throw new Error("A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely");
2065
+ throw new Error(
2066
+ "A databaseURL was not defined. Either set the XATA_DATABASE_URL env variable or pass the argument explicitely"
2067
+ );
1655
2068
  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");
2069
+ throw new Error(
2070
+ "An API key was not defined. Either set the XATA_API_KEY env variable or pass the argument explicitely"
2071
+ );
1657
2072
  const [protocol, , host, , database] = databaseURL.split("/");
1658
2073
  const [workspace] = host.split(".");
1659
2074
  const dbBranchName = `${database}:${branch}`;
@@ -1663,10 +2078,8 @@ async function getDatabaseBranch(branch, options) {
1663
2078
  apiUrl: databaseURL,
1664
2079
  fetchImpl: getFetchImplementation(options?.fetchImpl),
1665
2080
  workspacesApiUrl: `${protocol}//${host}`,
1666
- pathParams: {
1667
- dbBranchName,
1668
- workspace
1669
- }
2081
+ pathParams: { dbBranchName, workspace },
2082
+ trace: defaultTrace
1670
2083
  });
1671
2084
  } catch (err) {
1672
2085
  if (isObject(err) && err.status === 404)
@@ -1674,21 +2087,10 @@ async function getDatabaseBranch(branch, options) {
1674
2087
  throw err;
1675
2088
  }
1676
2089
  }
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
2090
  function getDatabaseURL() {
1690
2091
  try {
1691
- return getEnvVariable("XATA_DATABASE_URL") ?? XATA_DATABASE_URL;
2092
+ const { databaseURL } = getEnvironment();
2093
+ return databaseURL;
1692
2094
  } catch (err) {
1693
2095
  return void 0;
1694
2096
  }
@@ -1717,24 +2119,27 @@ var __privateMethod = (obj, member, method) => {
1717
2119
  return method;
1718
2120
  };
1719
2121
  const buildClient = (plugins) => {
1720
- var _branch, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
2122
+ var _branch, _options, _parseOptions, parseOptions_fn, _getFetchProps, getFetchProps_fn, _evaluateBranch, evaluateBranch_fn, _a;
1721
2123
  return _a = class {
1722
- constructor(options = {}, links, tables) {
2124
+ constructor(options = {}, schemaTables) {
1723
2125
  __privateAdd(this, _parseOptions);
1724
2126
  __privateAdd(this, _getFetchProps);
1725
2127
  __privateAdd(this, _evaluateBranch);
1726
2128
  __privateAdd(this, _branch, void 0);
2129
+ __privateAdd(this, _options, void 0);
1727
2130
  const safeOptions = __privateMethod(this, _parseOptions, parseOptions_fn).call(this, options);
2131
+ __privateSet(this, _options, safeOptions);
1728
2132
  const pluginOptions = {
1729
2133
  getFetchProps: () => __privateMethod(this, _getFetchProps, getFetchProps_fn).call(this, safeOptions),
1730
- cache: safeOptions.cache
2134
+ cache: safeOptions.cache,
2135
+ trace: safeOptions.trace
1731
2136
  };
1732
- const db = new SchemaPlugin(links, tables).build(pluginOptions);
1733
- const search = new SearchPlugin(db, links ?? {}).build(pluginOptions);
2137
+ const db = new SchemaPlugin(schemaTables).build(pluginOptions);
2138
+ const search = new SearchPlugin(db, schemaTables).build(pluginOptions);
1734
2139
  this.db = db;
1735
2140
  this.search = search;
1736
2141
  for (const [key, namespace] of Object.entries(plugins ?? {})) {
1737
- if (!namespace)
2142
+ if (namespace === void 0)
1738
2143
  continue;
1739
2144
  const result = namespace.build(pluginOptions);
1740
2145
  if (result instanceof Promise) {
@@ -1746,22 +2151,26 @@ const buildClient = (plugins) => {
1746
2151
  }
1747
2152
  }
1748
2153
  }
1749
- }, _branch = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
2154
+ async getConfig() {
2155
+ const databaseURL = __privateGet(this, _options).databaseURL;
2156
+ const branch = await __privateGet(this, _options).branch();
2157
+ return { databaseURL, branch };
2158
+ }
2159
+ }, _branch = new WeakMap(), _options = new WeakMap(), _parseOptions = new WeakSet(), parseOptions_fn = function(options) {
1750
2160
  const fetch = getFetchImplementation(options?.fetch);
1751
2161
  const databaseURL = options?.databaseURL || getDatabaseURL();
1752
2162
  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");
2163
+ const cache = options?.cache ?? new SimpleCache({ defaultQueryTTL: 0 });
2164
+ const trace = options?.trace ?? defaultTrace;
2165
+ const branch = async () => options?.branch !== void 0 ? await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, options.branch) : await getCurrentBranchName({ apiKey, databaseURL, fetchImpl: options?.fetch });
2166
+ if (!apiKey) {
2167
+ throw new Error("Option apiKey is required");
1757
2168
  }
1758
- return { fetch, databaseURL, apiKey, branch, cache };
1759
- }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({
1760
- fetch,
1761
- apiKey,
1762
- databaseURL,
1763
- branch
1764
- }) {
2169
+ if (!databaseURL) {
2170
+ throw new Error("Option databaseURL is required");
2171
+ }
2172
+ return { fetch, databaseURL, apiKey, branch, cache, trace };
2173
+ }, _getFetchProps = new WeakSet(), getFetchProps_fn = async function({ fetch, apiKey, databaseURL, branch, trace }) {
1765
2174
  const branchValue = await __privateMethod(this, _evaluateBranch, evaluateBranch_fn).call(this, branch);
1766
2175
  if (!branchValue)
1767
2176
  throw new Error("Unable to resolve branch value");
@@ -1773,12 +2182,13 @@ const buildClient = (plugins) => {
1773
2182
  const hasBranch = params.dbBranchName ?? params.branch;
1774
2183
  const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branchValue}` : "");
1775
2184
  return databaseURL + newPath;
1776
- }
2185
+ },
2186
+ trace
1777
2187
  };
1778
2188
  }, _evaluateBranch = new WeakSet(), evaluateBranch_fn = async function(param) {
1779
2189
  if (__privateGet(this, _branch))
1780
2190
  return __privateGet(this, _branch);
1781
- if (!param)
2191
+ if (param === void 0)
1782
2192
  return void 0;
1783
2193
  const strategies = Array.isArray(param) ? [...param] : [param];
1784
2194
  const evaluateBranch = async (strategy) => {
@@ -1796,6 +2206,88 @@ const buildClient = (plugins) => {
1796
2206
  class BaseClient extends buildClient() {
1797
2207
  }
1798
2208
 
2209
+ const META = "__";
2210
+ const VALUE = "___";
2211
+ class Serializer {
2212
+ constructor() {
2213
+ this.classes = {};
2214
+ }
2215
+ add(clazz) {
2216
+ this.classes[clazz.name] = clazz;
2217
+ }
2218
+ toJSON(data) {
2219
+ function visit(obj) {
2220
+ if (Array.isArray(obj))
2221
+ return obj.map(visit);
2222
+ const type = typeof obj;
2223
+ if (type === "undefined")
2224
+ return { [META]: "undefined" };
2225
+ if (type === "bigint")
2226
+ return { [META]: "bigint", [VALUE]: obj.toString() };
2227
+ if (obj === null || type !== "object")
2228
+ return obj;
2229
+ const constructor = obj.constructor;
2230
+ const o = { [META]: constructor.name };
2231
+ for (const [key, value] of Object.entries(obj)) {
2232
+ o[key] = visit(value);
2233
+ }
2234
+ if (constructor === Date)
2235
+ o[VALUE] = obj.toISOString();
2236
+ if (constructor === Map)
2237
+ o[VALUE] = Object.fromEntries(obj);
2238
+ if (constructor === Set)
2239
+ o[VALUE] = [...obj];
2240
+ return o;
2241
+ }
2242
+ return JSON.stringify(visit(data));
2243
+ }
2244
+ fromJSON(json) {
2245
+ return JSON.parse(json, (key, value) => {
2246
+ if (value && typeof value === "object" && !Array.isArray(value)) {
2247
+ const { [META]: clazz, [VALUE]: val, ...rest } = value;
2248
+ const constructor = this.classes[clazz];
2249
+ if (constructor) {
2250
+ return Object.assign(Object.create(constructor.prototype), rest);
2251
+ }
2252
+ if (clazz === "Date")
2253
+ return new Date(val);
2254
+ if (clazz === "Set")
2255
+ return new Set(val);
2256
+ if (clazz === "Map")
2257
+ return new Map(Object.entries(val));
2258
+ if (clazz === "bigint")
2259
+ return BigInt(val);
2260
+ if (clazz === "undefined")
2261
+ return void 0;
2262
+ return rest;
2263
+ }
2264
+ return value;
2265
+ });
2266
+ }
2267
+ }
2268
+ const defaultSerializer = new Serializer();
2269
+ const serialize = (data) => {
2270
+ return defaultSerializer.toJSON(data);
2271
+ };
2272
+ const deserialize = (json) => {
2273
+ return defaultSerializer.fromJSON(json);
2274
+ };
2275
+
2276
+ function buildWorkerRunner(config) {
2277
+ return function xataWorker(name, _worker) {
2278
+ return async (...args) => {
2279
+ const url = process.env.NODE_ENV === "development" ? `http://localhost:64749/${name}` : `https://dispatcher.xata.workers.dev/${config.workspace}/${config.worker}/${name}`;
2280
+ const result = await fetch(url, {
2281
+ method: "POST",
2282
+ headers: { "Content-Type": "application/json" },
2283
+ body: serialize({ args })
2284
+ });
2285
+ const text = await result.text();
2286
+ return deserialize(text);
2287
+ };
2288
+ };
2289
+ }
2290
+
1799
2291
  class XataError extends Error {
1800
2292
  constructor(message, status) {
1801
2293
  super(message);
@@ -1803,5 +2295,5 @@ class XataError extends Error {
1803
2295
  }
1804
2296
  }
1805
2297
 
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 };
2298
+ export { BaseClient, operationsByTag as Operations, PAGINATION_DEFAULT_OFFSET, PAGINATION_DEFAULT_SIZE, PAGINATION_MAX_OFFSET, PAGINATION_MAX_SIZE, Page, Query, RecordArray, Repository, RestRepository, SchemaPlugin, SearchPlugin, Serializer, SimpleCache, XataApiClient, XataApiPlugin, XataError, XataPlugin, acceptWorkspaceMemberInvite, addGitBranchesEntry, addTableColumn, buildClient, buildWorkerRunner, bulkInsertTableRecords, cancelWorkspaceMemberInvite, contains, createBranch, createDatabase, createTable, createUserAPIKey, createWorkspace, deleteBranch, deleteColumn, deleteDatabase, deleteRecord, deleteTable, deleteUser, deleteUserAPIKey, deleteWorkspace, deserialize, endsWith, equals, executeBranchMigrationPlan, exists, ge, getAPIKey, getBranchDetails, getBranchList, getBranchMetadata, getBranchMigrationHistory, getBranchMigrationPlan, getBranchStats, getColumn, getCurrentBranchDetails, getCurrentBranchName, getDatabaseList, getDatabaseMetadata, getDatabaseURL, getGitBranchesMapping, getRecord, getTableColumns, getTableSchema, getUser, getUserAPIKeys, getWorkspace, getWorkspaceMembersList, getWorkspacesList, greaterEquals, greaterThan, greaterThanEquals, gt, gte, includes, includesAll, includesAny, includesNone, insertRecord, insertRecordWithID, inviteWorkspaceMember, is, isCursorPaginationOptions, isIdentifiable, isNot, isXataRecord, le, lessEquals, lessThan, lessThanEquals, lt, lte, notExists, operationsByTag, pattern, queryTable, removeGitBranchesEntry, removeWorkspaceMember, resendWorkspaceMemberInvite, resolveBranch, searchBranch, searchTable, serialize, setTableSchema, startsWith, updateBranchMetadata, updateColumn, updateRecordWithID, updateTable, updateUser, updateWorkspace, updateWorkspaceMemberInvite, updateWorkspaceMemberRole, upsertRecordWithID };
1807
2299
  //# sourceMappingURL=index.mjs.map