@rebasepro/client 0.0.1-canary.4d4fb3e → 0.0.1-canary.ca2cb6e

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.umd.js CHANGED
@@ -1,7 +1,44 @@
1
1
  (function(global, factory) {
2
- typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global["Rebase Client"] = {}));
3
- })(this, function(exports2) {
2
+ typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require("@rebasepro/types"), require("@rebasepro/utils")) : typeof define === "function" && define.amd ? define(["exports", "@rebasepro/types", "@rebasepro/utils"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global["Rebase Client"] = {}, global.types, global.utils));
3
+ })(this, function(exports2, types, utils) {
4
4
  "use strict";
5
+ function rebaseReviver(_key, value) {
6
+ if (value && typeof value === "object" && "__type" in value) {
7
+ const record = value;
8
+ switch (record.__type) {
9
+ case "date":
10
+ case "Date": {
11
+ if (typeof record.value !== "string") {
12
+ return value;
13
+ }
14
+ const date = new Date(record.value);
15
+ return isNaN(date.getTime()) ? null : date;
16
+ }
17
+ case "reference":
18
+ case "EntityReference":
19
+ return new types.EntityReference({
20
+ id: String(record.id),
21
+ path: record.path,
22
+ driver: record.driver,
23
+ databaseId: record.databaseId
24
+ });
25
+ case "relation":
26
+ case "EntityRelation":
27
+ return new types.EntityRelation(
28
+ record.id,
29
+ record.path,
30
+ record.data
31
+ );
32
+ case "GeoPoint":
33
+ return new types.GeoPoint(record.latitude, record.longitude);
34
+ case "Vector":
35
+ return new types.Vector(record.value);
36
+ default:
37
+ return value;
38
+ }
39
+ }
40
+ return value;
41
+ }
5
42
  class RebaseApiError extends Error {
6
43
  status;
7
44
  code;
@@ -14,6 +51,30 @@
14
51
  this.details = details;
15
52
  }
16
53
  }
54
+ const OP_MAP = {
55
+ "==": "eq",
56
+ "!=": "neq",
57
+ ">": "gt",
58
+ ">=": "gte",
59
+ "<": "lt",
60
+ "<=": "lte",
61
+ "not-in": "nin",
62
+ "array-contains": "cs",
63
+ "array-contains-any": "csa"
64
+ };
65
+ function normalizeWhereValue(value) {
66
+ if (value === null) return "eq.null";
67
+ if (typeof value === "boolean") return `eq.${value}`;
68
+ if (typeof value === "number") return String(value);
69
+ if (Array.isArray(value) && value.length === 2) {
70
+ const [rawOp, val] = value;
71
+ const op = OP_MAP[rawOp] ?? rawOp;
72
+ if (val === null) return `${op}.null`;
73
+ if (Array.isArray(val)) return `${op}.(${val.join(",")})`;
74
+ return `${op}.${val}`;
75
+ }
76
+ return String(value);
77
+ }
17
78
  function buildQueryString(params) {
18
79
  if (!params) return "";
19
80
  const parts = [];
@@ -23,12 +84,16 @@
23
84
  if (params.orderBy) {
24
85
  parts.push(`orderBy=${encodeURIComponent(params.orderBy)}`);
25
86
  }
87
+ if (params.searchString) {
88
+ parts.push(`searchString=${encodeURIComponent(params.searchString)}`);
89
+ }
26
90
  if (params.include && params.include.length > 0) {
27
91
  parts.push(`include=${encodeURIComponent(params.include.join(","))}`);
28
92
  }
29
93
  if (params.where) {
30
94
  for (const [field, value] of Object.entries(params.where)) {
31
- parts.push(`${encodeURIComponent(field)}=${encodeURIComponent(String(value))}`);
95
+ const normalized = normalizeWhereValue(value);
96
+ parts.push(`${encodeURIComponent(field)}=${encodeURIComponent(normalized)}`);
32
97
  }
33
98
  }
34
99
  return parts.length > 0 ? "?" + parts.join("&") : "";
@@ -47,7 +112,8 @@
47
112
  };
48
113
  }
49
114
  async function request(path, init) {
50
- const url = config.baseUrl.replace(/\/$/, "") + apiPath + path;
115
+ const base = config.baseUrl ? config.baseUrl.replace(/\/$/, "") : "";
116
+ const url = base + apiPath + path;
51
117
  let activeToken = token;
52
118
  if (tokenGetter) {
53
119
  try {
@@ -62,9 +128,19 @@
62
128
  if (init?.body instanceof FormData) {
63
129
  delete headers["Content-Type"];
64
130
  }
65
- const res = await fetchFn(url, { ...init, headers });
131
+ const res = await fetchFn(url, {
132
+ ...init,
133
+ headers
134
+ });
66
135
  if (res.status === 204) return void 0;
67
- const body = await res.json().catch(() => ({}));
136
+ const text = await res.text().catch(() => "");
137
+ let body = {};
138
+ if (text) {
139
+ try {
140
+ body = JSON.parse(text, rebaseReviver);
141
+ } catch (e) {
142
+ }
143
+ }
68
144
  if (res.status === 401 && onUnauthorizedHandler) {
69
145
  const retried = await onUnauthorizedHandler();
70
146
  if (retried) {
@@ -79,13 +155,28 @@
79
155
  }
80
156
  }
81
157
  const retryHeaders = getHeaders(retryToken, init);
82
- const retryRes = await fetchFn(url, { ...init, headers: retryHeaders });
158
+ const retryRes = await fetchFn(url, {
159
+ ...init,
160
+ headers: retryHeaders
161
+ });
83
162
  if (retryRes.status === 204) return void 0;
84
- const retryBody = await retryRes.json().catch(() => ({}));
163
+ const retryText = await retryRes.text().catch(() => "");
164
+ let retryBody = {};
165
+ if (retryText) {
166
+ try {
167
+ retryBody = JSON.parse(retryText, rebaseReviver);
168
+ } catch (e) {
169
+ }
170
+ }
85
171
  if (!retryRes.ok) {
172
+ let fallbackMessage = retryRes.statusText;
173
+ if (retryRes.status === 404 && !fallbackMessage) {
174
+ const method = init?.method || "GET";
175
+ fallbackMessage = `Endpoint not found (${method} ${path}). This usually means the collection is not registered on the backend, or the frontend API URL configuration (e.g. VITE_API_URL) is missing or pointing to the wrong host.`;
176
+ }
86
177
  throw new RebaseApiError(
87
178
  retryRes.status,
88
- retryBody?.error?.message || retryBody?.message || retryRes.statusText,
179
+ retryBody?.error?.message || retryBody?.message || fallbackMessage || `Request failed with status ${retryRes.status}`,
89
180
  retryBody?.error?.code || retryBody?.code,
90
181
  retryBody?.error?.details || retryBody?.details
91
182
  );
@@ -94,9 +185,14 @@
94
185
  }
95
186
  }
96
187
  if (!res.ok) {
188
+ let fallbackMessage = res.statusText;
189
+ if (res.status === 404 && !fallbackMessage) {
190
+ const method = init?.method || "GET";
191
+ fallbackMessage = `Endpoint not found (${method} ${path}). This usually means the collection is not registered on the backend, or the frontend API URL configuration (e.g. VITE_API_URL) is missing or pointing to the wrong host.`;
192
+ }
97
193
  throw new RebaseApiError(
98
194
  res.status,
99
- body?.error?.message || body?.message || res.statusText,
195
+ body?.error?.message || body?.message || fallbackMessage || `Request failed with status ${res.status}`,
100
196
  body?.error?.code || body?.code,
101
197
  body?.error?.details || body?.details
102
198
  );
@@ -115,7 +211,7 @@
115
211
  onUnauthorizedHandler = handler;
116
212
  },
117
213
  get baseUrl() {
118
- return config.baseUrl.replace(/\/$/, "");
214
+ return config.baseUrl ? config.baseUrl.replace(/\/$/, "") : "";
119
215
  },
120
216
  get apiPath() {
121
217
  return apiPath;
@@ -252,16 +348,26 @@
252
348
  const res = await fetchFn(authUrl("/login"), {
253
349
  method: "POST",
254
350
  headers: { "Content-Type": "application/json" },
255
- body: JSON.stringify({ email, password })
351
+ body: JSON.stringify({
352
+ email,
353
+ password
354
+ })
256
355
  });
257
356
  const body = await res.json().catch(() => ({}));
258
357
  if (!res.ok) throwApiError(res.status, body, res.statusText);
259
358
  const session = handleAuthResponse(body, "SIGNED_IN");
260
- return { user: session.user, accessToken: session.accessToken, refreshToken: session.refreshToken };
359
+ return {
360
+ user: session.user,
361
+ accessToken: session.accessToken,
362
+ refreshToken: session.refreshToken
363
+ };
261
364
  }
262
365
  async function signUp(email, password, displayName) {
263
366
  const fetchFn = getFetch();
264
- const payload = { email, password };
367
+ const payload = {
368
+ email,
369
+ password
370
+ };
265
371
  if (displayName !== void 0) payload.displayName = displayName;
266
372
  const res = await fetchFn(authUrl("/register"), {
267
373
  method: "POST",
@@ -271,7 +377,11 @@
271
377
  const body = await res.json().catch(() => ({}));
272
378
  if (!res.ok) throwApiError(res.status, body, res.statusText);
273
379
  const session = handleAuthResponse(body, "SIGNED_IN");
274
- return { user: session.user, accessToken: session.accessToken, refreshToken: session.refreshToken };
380
+ return {
381
+ user: session.user,
382
+ accessToken: session.accessToken,
383
+ refreshToken: session.refreshToken
384
+ };
275
385
  }
276
386
  async function signInWithGoogle(idToken) {
277
387
  const fetchFn = getFetch();
@@ -283,7 +393,108 @@
283
393
  const body = await res.json().catch(() => ({}));
284
394
  if (!res.ok) throwApiError(res.status, body, res.statusText);
285
395
  const session = handleAuthResponse(body, "SIGNED_IN");
286
- return { user: session.user, accessToken: session.accessToken, refreshToken: session.refreshToken };
396
+ return {
397
+ user: session.user,
398
+ accessToken: session.accessToken,
399
+ refreshToken: session.refreshToken
400
+ };
401
+ }
402
+ async function signInWithLinkedin(code, redirectUri) {
403
+ const fetchFn = getFetch();
404
+ const res = await fetchFn(authUrl("/linkedin"), {
405
+ method: "POST",
406
+ headers: { "Content-Type": "application/json" },
407
+ body: JSON.stringify({
408
+ code,
409
+ redirectUri
410
+ })
411
+ });
412
+ const body = await res.json().catch(() => ({}));
413
+ if (!res.ok) throwApiError(res.status, body, res.statusText);
414
+ const session = handleAuthResponse(body, "SIGNED_IN");
415
+ return {
416
+ user: session.user,
417
+ accessToken: session.accessToken,
418
+ refreshToken: session.refreshToken
419
+ };
420
+ }
421
+ async function signInWithOAuth(providerId, payload) {
422
+ const fetchFn = getFetch();
423
+ const res = await fetchFn(authUrl(`/${providerId}`), {
424
+ method: "POST",
425
+ headers: { "Content-Type": "application/json" },
426
+ body: JSON.stringify(payload)
427
+ });
428
+ const body = await res.json().catch(() => ({}));
429
+ if (!res.ok) throwApiError(res.status, body, res.statusText);
430
+ const session = handleAuthResponse(body, "SIGNED_IN");
431
+ return {
432
+ user: session.user,
433
+ accessToken: session.accessToken,
434
+ refreshToken: session.refreshToken
435
+ };
436
+ }
437
+ async function signInWithGitHub(code, redirectUri) {
438
+ return signInWithOAuth("github", {
439
+ code,
440
+ redirectUri
441
+ });
442
+ }
443
+ async function signInWithMicrosoft(code, redirectUri) {
444
+ return signInWithOAuth("microsoft", {
445
+ code,
446
+ redirectUri
447
+ });
448
+ }
449
+ async function signInWithApple(code, redirectUri, user) {
450
+ return signInWithOAuth("apple", {
451
+ code,
452
+ redirectUri,
453
+ user
454
+ });
455
+ }
456
+ async function signInWithFacebook(code, redirectUri) {
457
+ return signInWithOAuth("facebook", {
458
+ code,
459
+ redirectUri
460
+ });
461
+ }
462
+ async function signInWithTwitter(code, redirectUri, codeVerifier) {
463
+ return signInWithOAuth("twitter", {
464
+ code,
465
+ redirectUri,
466
+ codeVerifier
467
+ });
468
+ }
469
+ async function signInWithDiscord(code, redirectUri) {
470
+ return signInWithOAuth("discord", {
471
+ code,
472
+ redirectUri
473
+ });
474
+ }
475
+ async function signInWithGitLab(code, redirectUri) {
476
+ return signInWithOAuth("gitlab", {
477
+ code,
478
+ redirectUri
479
+ });
480
+ }
481
+ async function signInWithBitbucket(code, redirectUri) {
482
+ return signInWithOAuth("bitbucket", {
483
+ code,
484
+ redirectUri
485
+ });
486
+ }
487
+ async function signInWithSlack(code, redirectUri) {
488
+ return signInWithOAuth("slack", {
489
+ code,
490
+ redirectUri
491
+ });
492
+ }
493
+ async function signInWithSpotify(code, redirectUri) {
494
+ return signInWithOAuth("spotify", {
495
+ code,
496
+ redirectUri
497
+ });
287
498
  }
288
499
  async function signOut() {
289
500
  const fetchFn = getFetch();
@@ -341,7 +552,10 @@
341
552
  body: JSON.stringify(updates)
342
553
  });
343
554
  if (currentSession) {
344
- currentSession = { ...currentSession, user: data.user };
555
+ currentSession = {
556
+ ...currentSession,
557
+ user: data.user
558
+ };
345
559
  saveSession(currentSession);
346
560
  emit("USER_UPDATED", currentSession);
347
561
  }
@@ -363,7 +577,10 @@
363
577
  const res = await fetchFn(authUrl("/reset-password"), {
364
578
  method: "POST",
365
579
  headers: { "Content-Type": "application/json" },
366
- body: JSON.stringify({ token, password })
580
+ body: JSON.stringify({
581
+ token,
582
+ password
583
+ })
367
584
  });
368
585
  const body = await res.json().catch(() => ({}));
369
586
  if (!res.ok) throwApiError(res.status, body, res.statusText);
@@ -372,7 +589,10 @@
372
589
  async function changePassword(oldPassword, newPassword) {
373
590
  return transport.request(authPath + "/change-password", {
374
591
  method: "POST",
375
- body: JSON.stringify({ oldPassword, newPassword })
592
+ body: JSON.stringify({
593
+ oldPassword,
594
+ newPassword
595
+ })
376
596
  });
377
597
  }
378
598
  async function sendVerificationEmail() {
@@ -451,6 +671,18 @@
451
671
  signInWithEmail,
452
672
  signUp,
453
673
  signInWithGoogle,
674
+ signInWithLinkedin,
675
+ signInWithOAuth,
676
+ signInWithGitHub,
677
+ signInWithMicrosoft,
678
+ signInWithApple,
679
+ signInWithFacebook,
680
+ signInWithTwitter,
681
+ signInWithDiscord,
682
+ signInWithGitLab,
683
+ signInWithBitbucket,
684
+ signInWithSlack,
685
+ signInWithSpotify,
454
686
  signOut,
455
687
  refreshSession,
456
688
  getUser,
@@ -550,6 +782,49 @@
550
782
  bootstrap
551
783
  };
552
784
  }
785
+ function createCron(transport, options) {
786
+ const cronPath = options?.cronPath || "/cron";
787
+ async function listJobs() {
788
+ return transport.request(cronPath, { method: "GET" });
789
+ }
790
+ async function getJob(jobId) {
791
+ return transport.request(
792
+ cronPath + "/" + encodeURIComponent(jobId),
793
+ { method: "GET" }
794
+ );
795
+ }
796
+ async function triggerJob(jobId) {
797
+ return transport.request(
798
+ cronPath + "/" + encodeURIComponent(jobId) + "/trigger",
799
+ { method: "POST" }
800
+ );
801
+ }
802
+ async function getJobLogs(jobId, options2) {
803
+ const params = new URLSearchParams();
804
+ if (options2?.limit !== void 0) params.set("limit", String(options2.limit));
805
+ const qs = params.toString();
806
+ return transport.request(
807
+ cronPath + "/" + encodeURIComponent(jobId) + "/logs" + (qs ? "?" + qs : ""),
808
+ { method: "GET" }
809
+ );
810
+ }
811
+ async function toggleJob(jobId, enabled) {
812
+ return transport.request(
813
+ cronPath + "/" + encodeURIComponent(jobId),
814
+ {
815
+ method: "PUT",
816
+ body: JSON.stringify({ enabled })
817
+ }
818
+ );
819
+ }
820
+ return {
821
+ listJobs,
822
+ getJob,
823
+ triggerJob,
824
+ getJobLogs,
825
+ toggleJob
826
+ };
827
+ }
553
828
  function mapOperator(op) {
554
829
  switch (op) {
555
830
  case "==":
@@ -581,7 +856,7 @@
581
856
  params = { where: {} };
582
857
  /**
583
858
  * Add a filter condition to your query.
584
- * @example
859
+ * @example
585
860
  * client.collection('users').where('age', '>=', 18).find()
586
861
  */
587
862
  where(column, operator, value) {
@@ -600,7 +875,7 @@
600
875
  }
601
876
  /**
602
877
  * Order the results by a specific column.
603
- * @example
878
+ * @example
604
879
  * client.collection('users').orderBy('createdAt', 'desc').find()
605
880
  */
606
881
  orderBy(column, ascending = "asc") {
@@ -663,7 +938,46 @@
663
938
  function parseWhereFilter(where) {
664
939
  if (!where) return void 0;
665
940
  const filters = {};
666
- for (const [key, value] of Object.entries(where)) {
941
+ for (const [key, rawValue] of Object.entries(where)) {
942
+ if (rawValue === null) {
943
+ filters[key] = ["==", null];
944
+ continue;
945
+ }
946
+ if (typeof rawValue === "boolean") {
947
+ filters[key] = ["==", rawValue];
948
+ continue;
949
+ }
950
+ if (typeof rawValue === "number") {
951
+ filters[key] = ["==", rawValue];
952
+ continue;
953
+ }
954
+ if (Array.isArray(rawValue) && rawValue.length === 2) {
955
+ const [rawOp, val] = rawValue;
956
+ const OP_TO_FILTER = {
957
+ "eq": "==",
958
+ "neq": "!=",
959
+ "gt": ">",
960
+ "gte": ">=",
961
+ "lt": "<",
962
+ "lte": "<=",
963
+ "==": "==",
964
+ "!=": "!=",
965
+ ">": ">",
966
+ ">=": ">=",
967
+ "<": "<",
968
+ "<=": "<=",
969
+ "in": "in",
970
+ "nin": "not-in",
971
+ "not-in": "not-in",
972
+ "cs": "array-contains",
973
+ "csa": "array-contains-any",
974
+ "array-contains": "array-contains",
975
+ "array-contains-any": "array-contains-any"
976
+ };
977
+ filters[key] = [OP_TO_FILTER[rawOp] ?? "==", val];
978
+ continue;
979
+ }
980
+ const value = String(rawValue);
667
981
  const dotIndex = value.indexOf(".");
668
982
  if (dotIndex > 0) {
669
983
  const opStr = value.substring(0, dotIndex);
@@ -711,7 +1025,7 @@
711
1025
  if (val === "true") val = true;
712
1026
  else if (val === "false") val = false;
713
1027
  else if (val === "null") val = null;
714
- else if (typeof val === "string" && /^[0-9]+(\.[0-9]+)?$/.test(val)) val = Number(val);
1028
+ else if (typeof val === "string" && /^[0-9]+(\.[0-9]+)?$/.test(val) && key !== "id" && !key.endsWith("_id")) val = Number(val);
715
1029
  filters[key] = [op, val];
716
1030
  } else {
717
1031
  filters[key] = ["==", value];
@@ -728,7 +1042,7 @@
728
1042
  }
729
1043
  function createCollectionClient(transport, slug, ws) {
730
1044
  const basePath = `/data/${slug}`;
731
- return {
1045
+ const client = {
732
1046
  async find(params) {
733
1047
  const qs = buildQueryString(params);
734
1048
  const raw = await transport.request(basePath + qs, { method: "GET" });
@@ -765,74 +1079,84 @@
765
1079
  method: "DELETE"
766
1080
  });
767
1081
  },
768
- ...ws && {
769
- listen(params, onUpdate, onError) {
770
- return ws.listenCollection(
771
- {
772
- path: slug,
773
- filter: parseWhereFilter(params?.where),
774
- limit: params?.limit,
775
- startAfter: params?.offset ? String(params.offset) : void 0,
776
- orderBy: params?.orderBy?.split(":")[0],
777
- order: params?.orderBy?.split(":")[1],
778
- searchString: params?.searchString
779
- },
780
- (entities) => {
781
- const requestedLimit = params?.limit || 20;
782
- onUpdate({
783
- data: entities,
784
- meta: {
785
- total: entities.length,
786
- limit: requestedLimit,
787
- offset: params?.offset || 0,
788
- hasMore: entities.length >= requestedLimit
789
- }
790
- });
791
- },
792
- onError
793
- );
794
- },
795
- listenById(id, onUpdate, onError) {
796
- return ws.listenEntity(
797
- { path: slug, entityId: String(id) },
798
- (entity) => {
799
- if (entity) {
800
- onUpdate(entity);
801
- } else {
802
- onUpdate(void 0);
803
- }
804
- },
805
- onError
806
- );
807
- }
808
- },
809
1082
  // Fluent builder instantiation
810
1083
  where(column, operator, value) {
811
- return new QueryBuilder(this).where(column, operator, value);
1084
+ return new QueryBuilder(client).where(column, operator, value);
812
1085
  },
813
1086
  orderBy(column, ascending) {
814
- return new QueryBuilder(this).orderBy(column, ascending);
1087
+ return new QueryBuilder(client).orderBy(column, ascending);
815
1088
  },
816
1089
  limit(count) {
817
- return new QueryBuilder(this).limit(count);
1090
+ return new QueryBuilder(client).limit(count);
818
1091
  },
819
1092
  offset(count) {
820
- return new QueryBuilder(this).offset(count);
1093
+ return new QueryBuilder(client).offset(count);
821
1094
  },
822
1095
  search(searchString) {
823
- return new QueryBuilder(this).search(searchString);
1096
+ return new QueryBuilder(client).search(searchString);
824
1097
  },
825
1098
  include(...relations) {
826
- return new QueryBuilder(this).include(...relations);
1099
+ return new QueryBuilder(client).include(...relations);
827
1100
  }
828
1101
  };
1102
+ if (ws) {
1103
+ client.listen = (params, onUpdate, onError) => {
1104
+ return ws.listenCollection(
1105
+ {
1106
+ path: slug,
1107
+ filter: parseWhereFilter(params?.where),
1108
+ limit: params?.limit,
1109
+ startAfter: params?.offset ? String(params.offset) : void 0,
1110
+ orderBy: params?.orderBy?.split(":")[0],
1111
+ order: params?.orderBy?.split(":")[1],
1112
+ searchString: params?.searchString
1113
+ },
1114
+ (entities) => {
1115
+ const requestedLimit = params?.limit || 20;
1116
+ onUpdate({
1117
+ data: entities,
1118
+ meta: {
1119
+ total: entities.length,
1120
+ limit: requestedLimit,
1121
+ offset: params?.offset || 0,
1122
+ hasMore: entities.length >= requestedLimit
1123
+ }
1124
+ });
1125
+ },
1126
+ onError
1127
+ );
1128
+ };
1129
+ client.listenById = (id, onUpdate, onError) => {
1130
+ return ws.listenEntity(
1131
+ {
1132
+ path: slug,
1133
+ entityId: String(id)
1134
+ },
1135
+ (entity) => {
1136
+ if (entity) {
1137
+ onUpdate(entity);
1138
+ } else {
1139
+ onUpdate(void 0);
1140
+ }
1141
+ },
1142
+ onError
1143
+ );
1144
+ };
1145
+ }
1146
+ return client;
1147
+ }
1148
+ function rehydrateEntity(entity) {
1149
+ return entity;
829
1150
  }
830
1151
  function extractMessageError(message) {
831
1152
  const payload = message.payload;
832
1153
  const errPayload = payload?.error;
833
1154
  const errorMessage = typeof errPayload === "object" ? errPayload.message : payload?.message || (typeof errPayload === "string" ? errPayload : void 0) || message.error || "Unknown error";
834
1155
  const errorCode = typeof errPayload === "object" ? errPayload.code : payload?.code;
835
- return { errorMessage, errorCode };
1156
+ return {
1157
+ errorMessage,
1158
+ errorCode
1159
+ };
836
1160
  }
837
1161
  class ApiError extends Error {
838
1162
  code;
@@ -873,6 +1197,7 @@
873
1197
  maxReconnectAttempts = 5;
874
1198
  isConnected = false;
875
1199
  messageQueue = [];
1200
+ reconnectTimeout = null;
876
1201
  isAuthenticated = false;
877
1202
  authPromise = null;
878
1203
  WebSocketConstructor;
@@ -928,18 +1253,29 @@
928
1253
  if (this.isConnected && !this.isAuthenticated && !this.authPromise) {
929
1254
  console.log("WebSocket auto-authenticating after token getter set");
930
1255
  this.getAuthToken().then((token) => {
1256
+ if (!this.ws) return;
931
1257
  if (token) {
932
- this.authenticate(token).catch((e) => console.warn("WebSocket auto-auth failed:", e));
1258
+ this.authenticate(token).catch((e) => {
1259
+ if (this.ws) console.warn("WebSocket auto-auth failed:", e);
1260
+ });
933
1261
  }
934
1262
  }).catch((e) => {
935
- console.warn("WebSocket auto-auth failed:", e);
1263
+ if (this.ws) console.warn("WebSocket auto-auth failed:", e);
936
1264
  });
937
1265
  }
938
1266
  }
939
1267
  disconnect() {
940
1268
  this.isAuthenticated = false;
941
1269
  this.authPromise = null;
1270
+ if (this.reconnectTimeout) {
1271
+ clearTimeout(this.reconnectTimeout);
1272
+ this.reconnectTimeout = null;
1273
+ }
942
1274
  if (this.ws) {
1275
+ this.ws.onclose = null;
1276
+ this.ws.onerror = null;
1277
+ this.ws.onopen = null;
1278
+ this.ws.onmessage = null;
943
1279
  this.ws.close();
944
1280
  this.ws = null;
945
1281
  }
@@ -974,7 +1310,7 @@
974
1310
  };
975
1311
  this.ws.onmessage = (event) => {
976
1312
  try {
977
- const message = JSON.parse(event.data);
1313
+ const message = JSON.parse(event.data, rebaseReviver);
978
1314
  this.handleWebSocketMessage(message);
979
1315
  } catch (error) {
980
1316
  console.error("Error parsing WebSocket message:", error);
@@ -1024,7 +1360,11 @@
1024
1360
  this.reconnectAttempts++;
1025
1361
  const delay = Math.min(1e3 * Math.pow(2, this.reconnectAttempts), 3e4);
1026
1362
  console.log(`Attempting to reconnect in ${delay}ms (attempt ${this.reconnectAttempts})`);
1027
- setTimeout(() => {
1363
+ if (this.reconnectTimeout) {
1364
+ clearTimeout(this.reconnectTimeout);
1365
+ }
1366
+ this.reconnectTimeout = setTimeout(() => {
1367
+ this.reconnectTimeout = null;
1028
1368
  this.initWebSocket();
1029
1369
  }, delay);
1030
1370
  }
@@ -1053,7 +1393,7 @@
1053
1393
  if (subscriptionKey) {
1054
1394
  const collectionSub = this.collectionSubscriptions.get(subscriptionKey);
1055
1395
  if (collectionSub) {
1056
- const incomingEntities = message.entities || [];
1396
+ const incomingEntities = (message.entities || []).map((e) => rehydrateEntity(e));
1057
1397
  const entities = this.mergeEntities(collectionSub.latestData, incomingEntities);
1058
1398
  collectionSub.latestData = entities;
1059
1399
  collectionSub.lastUpdated = Date.now();
@@ -1077,7 +1417,7 @@
1077
1417
  if (subscriptionKey) {
1078
1418
  const collectionSub = this.collectionSubscriptions.get(subscriptionKey);
1079
1419
  if (collectionSub && collectionSub.isInitialDataReceived && collectionSub.latestData) {
1080
- const patchEntity = message.entity;
1420
+ const patchEntity = message.entity ? rehydrateEntity(message.entity) : message.entity;
1081
1421
  const patchEntityId = message.entityId;
1082
1422
  let updated;
1083
1423
  if (patchEntity === null || patchEntity === void 0) {
@@ -1112,7 +1452,7 @@
1112
1452
  if (subscriptionKey) {
1113
1453
  const entitySub = this.entitySubscriptions.get(subscriptionKey);
1114
1454
  if (entitySub) {
1115
- const entity = message.entity ?? null;
1455
+ const entity = message.entity ? rehydrateEntity(message.entity) : null;
1116
1456
  entitySub.latestData = entity;
1117
1457
  entitySub.lastUpdated = Date.now();
1118
1458
  entitySub.isInitialDataReceived = true;
@@ -1280,21 +1620,21 @@
1280
1620
  type: "FETCH_COLLECTION",
1281
1621
  payload: props
1282
1622
  });
1283
- return response.entities || [];
1623
+ return (response.entities || []).map((e) => rehydrateEntity(e));
1284
1624
  }
1285
1625
  async fetchEntity(props) {
1286
1626
  const response = await this.sendMessage({
1287
1627
  type: "FETCH_ENTITY",
1288
1628
  payload: props
1289
1629
  });
1290
- return response.entity;
1630
+ return response.entity ? rehydrateEntity(response.entity) : void 0;
1291
1631
  }
1292
1632
  async saveEntity(props) {
1293
1633
  const response = await this.sendMessage({
1294
1634
  type: "SAVE_ENTITY",
1295
1635
  payload: props
1296
1636
  });
1297
- return response.entity;
1637
+ return rehydrateEntity(response.entity);
1298
1638
  }
1299
1639
  async deleteEntity(props) {
1300
1640
  await this.sendMessage({
@@ -1305,7 +1645,10 @@
1305
1645
  async executeSql(sql, options) {
1306
1646
  const response = await this.sendMessage({
1307
1647
  type: "EXECUTE_SQL",
1308
- payload: { sql, options }
1648
+ payload: {
1649
+ sql,
1650
+ options
1651
+ }
1309
1652
  });
1310
1653
  return response.result || [];
1311
1654
  }
@@ -1360,7 +1703,35 @@
1360
1703
  type: "FETCH_TABLE_METADATA",
1361
1704
  payload: { tableName }
1362
1705
  });
1363
- return response.metadata || { columns: [], foreignKeys: [], junctions: [], policies: [] };
1706
+ return response.metadata || {
1707
+ columns: [],
1708
+ foreignKeys: [],
1709
+ junctions: [],
1710
+ policies: []
1711
+ };
1712
+ }
1713
+ async createBranch(name, options) {
1714
+ const response = await this.sendMessage({
1715
+ type: "CREATE_BRANCH",
1716
+ payload: {
1717
+ name,
1718
+ options
1719
+ }
1720
+ });
1721
+ return response.branch;
1722
+ }
1723
+ async deleteBranch(name) {
1724
+ await this.sendMessage({
1725
+ type: "DELETE_BRANCH",
1726
+ payload: { name }
1727
+ });
1728
+ }
1729
+ async listBranches() {
1730
+ const response = await this.sendMessage({
1731
+ type: "LIST_BRANCHES",
1732
+ payload: {}
1733
+ });
1734
+ return response.branches || [];
1364
1735
  }
1365
1736
  /**
1366
1737
  * Recursively compare two values for structural equality.
@@ -1446,7 +1817,10 @@
1446
1817
  const allKeys = /* @__PURE__ */ new Set([...Object.keys(normCached), ...Object.keys(normIncoming)]);
1447
1818
  for (const key of allKeys) {
1448
1819
  if (!this.deepEqual(normCached[key], normIncoming[key])) {
1449
- mismatches[key] = { cached: normCached[key], incoming: normIncoming[key] };
1820
+ mismatches[key] = {
1821
+ cached: normCached[key],
1822
+ incoming: normIncoming[key]
1823
+ };
1450
1824
  }
1451
1825
  }
1452
1826
  console.log(`[RebaseWS] Row ${incomingEntity.id} refetch mismatch:
@@ -1463,7 +1837,10 @@
1463
1837
  const existingSubscription = this.collectionSubscriptions.get(subscriptionKey);
1464
1838
  if (existingSubscription) {
1465
1839
  const callbackMap2 = existingSubscription.callbacks;
1466
- callbackMap2.set(callbackId, { onUpdate, onError });
1840
+ callbackMap2.set(callbackId, {
1841
+ onUpdate,
1842
+ onError
1843
+ });
1467
1844
  if (existingSubscription.latestData !== void 0 && existingSubscription.isInitialDataReceived) {
1468
1845
  try {
1469
1846
  onUpdate(existingSubscription.latestData);
@@ -1490,7 +1867,10 @@
1490
1867
  }
1491
1868
  const backendSubscriptionId = `collection_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
1492
1869
  const callbackMap = /* @__PURE__ */ new Map();
1493
- callbackMap.set(callbackId, { onUpdate, onError });
1870
+ callbackMap.set(callbackId, {
1871
+ onUpdate,
1872
+ onError
1873
+ });
1494
1874
  this.collectionSubscriptions.set(subscriptionKey, {
1495
1875
  backendSubscriptionId,
1496
1876
  callbacks: callbackMap,
@@ -1530,7 +1910,10 @@
1530
1910
  const existingSubscription = this.entitySubscriptions.get(subscriptionKey);
1531
1911
  if (existingSubscription) {
1532
1912
  const callbackMap2 = existingSubscription.callbacks;
1533
- callbackMap2.set(callbackId, { onUpdate, onError });
1913
+ callbackMap2.set(callbackId, {
1914
+ onUpdate,
1915
+ onError
1916
+ });
1534
1917
  if (existingSubscription.latestData !== void 0 && existingSubscription.isInitialDataReceived) {
1535
1918
  try {
1536
1919
  onUpdate(existingSubscription.latestData);
@@ -1557,7 +1940,10 @@
1557
1940
  }
1558
1941
  const backendSubscriptionId = `entity_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
1559
1942
  const callbackMap = /* @__PURE__ */ new Map();
1560
- callbackMap.set(callbackId, { onUpdate, onError });
1943
+ callbackMap.set(callbackId, {
1944
+ onUpdate,
1945
+ onError
1946
+ });
1561
1947
  this.entitySubscriptions.set(subscriptionKey, {
1562
1948
  backendSubscriptionId,
1563
1949
  callbacks: callbackMap,
@@ -1658,23 +2044,21 @@
1658
2044
  }
1659
2045
  function createStorage(transport) {
1660
2046
  const urlsCache = /* @__PURE__ */ new Map();
1661
- async function uploadFile({
2047
+ async function putObject({
1662
2048
  file,
1663
- fileName,
1664
- path,
2049
+ key,
1665
2050
  metadata,
1666
2051
  bucket
1667
2052
  }) {
1668
2053
  const formData = new FormData();
1669
2054
  formData.append("file", file);
1670
- if (fileName) formData.append("fileName", fileName);
1671
- if (path) formData.append("path", path);
2055
+ if (key) formData.append("key", key);
1672
2056
  if (bucket) formData.append("bucket", bucket);
1673
2057
  if (metadata) {
1674
- for (const [key, value] of Object.entries(metadata)) {
2058
+ for (const [key2, value] of Object.entries(metadata)) {
1675
2059
  if (value !== void 0 && value !== null) {
1676
2060
  formData.append(
1677
- `metadata_${key}`,
2061
+ `metadata_${key2}`,
1678
2062
  typeof value === "string" ? value : JSON.stringify(value)
1679
2063
  );
1680
2064
  }
@@ -1684,18 +2068,18 @@
1684
2068
  method: "POST",
1685
2069
  body: formData,
1686
2070
  headers: {
1687
- // transport.request merges headers, so to prevent it setting application/json we can delete it
2071
+ // transport.request merges headers, so to prevent it setting application/json we can delete it
1688
2072
  // in transport if body is FormData, or we can explicitly set it to an empty string.
1689
2073
  // Let's rely on standard behaviour for now and adjust transport if it fails.
1690
2074
  }
1691
2075
  });
1692
2076
  return result.data;
1693
2077
  }
1694
- async function getDownloadURL(pathOrUrl, bucket) {
1695
- const cacheKey = bucket ? `${bucket}/${pathOrUrl}` : pathOrUrl;
2078
+ async function getSignedUrl(keyOrUrl, bucket) {
2079
+ const cacheKey = bucket ? `${bucket}/${keyOrUrl}` : keyOrUrl;
1696
2080
  const cached = urlsCache.get(cacheKey);
1697
2081
  if (cached) return cached;
1698
- let filePath = pathOrUrl;
2082
+ let filePath = keyOrUrl;
1699
2083
  if (filePath && (filePath.startsWith("local://") || filePath.startsWith("s3://"))) {
1700
2084
  filePath = filePath.substring(filePath.indexOf("://") + 3);
1701
2085
  }
@@ -1703,7 +2087,10 @@
1703
2087
  filePath = `${bucket}/${filePath}`;
1704
2088
  }
1705
2089
  if (!filePath || filePath.trim() === "" || filePath === "/") {
1706
- return { url: null, fileNotFound: true };
2090
+ return {
2091
+ url: null,
2092
+ fileNotFound: true
2093
+ };
1707
2094
  }
1708
2095
  try {
1709
2096
  const result = await transport.request(`/storage/metadata/${filePath}`);
@@ -1717,13 +2104,16 @@
1717
2104
  return downloadConfig;
1718
2105
  } catch (e) {
1719
2106
  if (e instanceof Error && "status" in e && e.status === 404) {
1720
- return { url: null, fileNotFound: true };
2107
+ return {
2108
+ url: null,
2109
+ fileNotFound: true
2110
+ };
1721
2111
  }
1722
2112
  throw e;
1723
2113
  }
1724
2114
  }
1725
- async function getFile(path, bucket) {
1726
- let filePath = path;
2115
+ async function getObject(key, bucket) {
2116
+ let filePath = key;
1727
2117
  if (filePath && (filePath.startsWith("local://") || filePath.startsWith("s3://"))) {
1728
2118
  filePath = filePath.substring(filePath.indexOf("://") + 3);
1729
2119
  }
@@ -1743,8 +2133,8 @@
1743
2133
  const fileName = filePath.split("/").pop() || "file";
1744
2134
  return new File([blob], fileName, { type: blob.type });
1745
2135
  }
1746
- async function deleteFile(path, bucket) {
1747
- let filePath = path;
2136
+ async function deleteObject(key, bucket) {
2137
+ let filePath = key;
1748
2138
  if (filePath && (filePath.startsWith("local://") || filePath.startsWith("s3://"))) {
1749
2139
  filePath = filePath.substring(filePath.indexOf("://") + 3);
1750
2140
  }
@@ -1759,11 +2149,11 @@
1759
2149
  } catch (e) {
1760
2150
  if (!(e instanceof Error && "status" in e && e.status === 404)) throw e;
1761
2151
  }
1762
- urlsCache.delete(bucket ? `${bucket}/${path}` : path);
2152
+ urlsCache.delete(bucket ? `${bucket}/${key}` : key);
1763
2153
  }
1764
- async function list(path, options) {
2154
+ async function listObjects(prefix, options) {
1765
2155
  const params = new URLSearchParams();
1766
- if (path) params.set("path", path);
2156
+ if (prefix) params.set("prefix", prefix);
1767
2157
  if (options?.bucket) params.set("bucket", options.bucket);
1768
2158
  if (options?.maxResults) params.set("maxResults", String(options.maxResults));
1769
2159
  if (options?.pageToken) params.set("pageToken", options.pageToken);
@@ -1771,20 +2161,28 @@
1771
2161
  return result.data;
1772
2162
  }
1773
2163
  return {
1774
- uploadFile,
1775
- getDownloadURL,
1776
- getFile,
1777
- deleteFile,
1778
- list
2164
+ putObject,
2165
+ getSignedUrl,
2166
+ getObject,
2167
+ deleteObject,
2168
+ listObjects
1779
2169
  };
1780
2170
  }
1781
2171
  function deriveWebSocketUrl(baseUrl) {
2172
+ if (!baseUrl) {
2173
+ if (typeof window !== "undefined") {
2174
+ const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
2175
+ return `${protocol}//${window.location.host}`;
2176
+ }
2177
+ return "";
2178
+ }
1782
2179
  return baseUrl.replace(/^https:\/\//, "wss://").replace(/^http:\/\//, "ws://").replace(/\/$/, "");
1783
2180
  }
1784
2181
  function createRebaseClient(options) {
1785
2182
  const transport = createTransport(options);
1786
2183
  const auth = createAuth(transport, options.auth);
1787
2184
  const admin = createAdmin(transport, options.admin);
2185
+ const cron = createCron(transport, options.cron);
1788
2186
  const storage = createStorage(transport);
1789
2187
  const resolvedWsUrl = options.websocketUrl ?? deriveWebSocketUrl(options.baseUrl);
1790
2188
  let ws;
@@ -1808,14 +2206,14 @@
1808
2206
  });
1809
2207
  }
1810
2208
  if (!options.onUnauthorized) {
1811
- options.onUnauthorized = async () => {
2209
+ transport.setOnUnauthorized(async () => {
1812
2210
  try {
1813
2211
  await auth.refreshSession();
1814
2212
  return true;
1815
2213
  } catch (e) {
1816
2214
  return false;
1817
2215
  }
1818
- };
2216
+ });
1819
2217
  }
1820
2218
  const collectionClients = /* @__PURE__ */ new Map();
1821
2219
  function collection(slug) {
@@ -1832,7 +2230,8 @@
1832
2230
  }
1833
2231
  if (typeof prop === "symbol") return void 0;
1834
2232
  if (typeof prop === "string" && prop !== "then" && prop !== "toJSON" && prop !== "$$typeof") {
1835
- return collection(prop);
2233
+ const slug = utils.toSnakeCase(prop);
2234
+ return collection(slug);
1836
2235
  }
1837
2236
  return void 0;
1838
2237
  }
@@ -1840,6 +2239,7 @@
1840
2239
  const target = {
1841
2240
  auth,
1842
2241
  admin,
2242
+ cron,
1843
2243
  storage,
1844
2244
  ws,
1845
2245
  setToken: transport.setToken,
@@ -1856,19 +2256,10 @@
1856
2256
  });
1857
2257
  return res.data ?? res;
1858
2258
  },
1859
- data: dataProxy
2259
+ data: dataProxy,
2260
+ email: void 0
1860
2261
  };
1861
- return new Proxy(target, {
1862
- get(obj, prop) {
1863
- if (prop in obj) {
1864
- return obj[prop];
1865
- }
1866
- if (typeof prop === "string" && prop !== "then") {
1867
- return collection(prop);
1868
- }
1869
- return void 0;
1870
- }
1871
- });
2262
+ return target;
1872
2263
  }
1873
2264
  exports2.ApiError = ApiError;
1874
2265
  exports2.RebaseApiError = RebaseApiError;
@@ -1877,10 +2268,12 @@
1877
2268
  exports2.createAdmin = createAdmin;
1878
2269
  exports2.createAuth = createAuth;
1879
2270
  exports2.createCollectionClient = createCollectionClient;
2271
+ exports2.createCron = createCron;
1880
2272
  exports2.createMemoryStorage = createMemoryStorage;
1881
2273
  exports2.createRebaseClient = createRebaseClient;
1882
2274
  exports2.createStorage = createStorage;
1883
2275
  exports2.createTransport = createTransport;
2276
+ exports2.rebaseReviver = rebaseReviver;
1884
2277
  Object.defineProperty(exports2, Symbol.toStringTag, { value: "Module" });
1885
2278
  });
1886
2279
  //# sourceMappingURL=index.umd.js.map