@rebasepro/client 0.8.0 → 0.9.1-canary.09aaf62

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 DELETED
@@ -1,2215 +0,0 @@
1
- (function(global, factory) {
2
- typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require("@rebasepro/common"), require("@rebasepro/types"), require("@rebasepro/utils")) : typeof define === "function" && define.amd ? define([
3
- "exports",
4
- "@rebasepro/common",
5
- "@rebasepro/types",
6
- "@rebasepro/utils"
7
- ], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global["Rebase Client"] = {}, global._rebasepro_common, global._rebasepro_types, global._rebasepro_utils));
8
- })(this, function(exports, _rebasepro_common, _rebasepro_types, _rebasepro_utils) {
9
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
10
- //#region src/reviver.ts
11
- function rebaseReviver(_key, value) {
12
- if (value && typeof value === "object" && "__type" in value) {
13
- const record = value;
14
- switch (record.__type) {
15
- case "date":
16
- case "Date": {
17
- if (typeof record.value !== "string") return value;
18
- const date = new Date(record.value);
19
- return isNaN(date.getTime()) ? null : date;
20
- }
21
- case "reference":
22
- case "EntityReference": return new _rebasepro_types.EntityReference({
23
- id: String(record.id),
24
- path: record.path,
25
- driver: record.driver,
26
- databaseId: record.databaseId
27
- });
28
- case "relation":
29
- case "EntityRelation": return new _rebasepro_types.EntityRelation(record.id, record.path, record.data);
30
- case "GeoPoint": return new _rebasepro_types.GeoPoint(record.latitude, record.longitude);
31
- case "Vector": return new _rebasepro_types.Vector(record.value);
32
- default: return value;
33
- }
34
- }
35
- return value;
36
- }
37
- //#endregion
38
- //#region src/transport.ts
39
- var RebaseApiError = class extends Error {
40
- status;
41
- code;
42
- details;
43
- constructor(status, message, code, details) {
44
- super(message);
45
- this.name = "RebaseApiError";
46
- this.status = status;
47
- this.code = code;
48
- this.details = details;
49
- }
50
- };
51
- function buildQueryString(params) {
52
- if (!params) return "";
53
- const parts = [];
54
- if (params.limit != null) parts.push(`limit=${params.limit}`);
55
- if (params.offset != null) parts.push(`offset=${params.offset}`);
56
- if (params.page != null) parts.push(`page=${params.page}`);
57
- if (params.orderBy) parts.push(`orderBy=${encodeURIComponent(params.orderBy)}`);
58
- if (params.searchString) parts.push(`searchString=${encodeURIComponent(params.searchString)}`);
59
- if (params.include && params.include.length > 0) parts.push(`include=${encodeURIComponent(params.include.join(","))}`);
60
- if (params.logical) {
61
- const root = params.logical;
62
- const serialized = (root.conditions ?? []).map(_rebasepro_common.serializeLogicalCondition).join(",");
63
- parts.push(`${root.type}=${encodeURIComponent(`(${serialized})`)}`);
64
- }
65
- if (params.where) {
66
- const serialized = (0, _rebasepro_common.serializeFilter)(params.where);
67
- for (const [field, value] of Object.entries(serialized)) if (Array.isArray(value)) for (const v of value) parts.push(`${encodeURIComponent(field)}=${encodeURIComponent(v)}`);
68
- else parts.push(`${encodeURIComponent(field)}=${encodeURIComponent(value)}`);
69
- }
70
- return parts.length > 0 ? "?" + parts.join("&") : "";
71
- }
72
- function createTransport(config) {
73
- const fetchFn = config.fetch || globalThis.fetch;
74
- const apiPath = config.apiPath || "/api";
75
- let token = config.token;
76
- let tokenGetter;
77
- let onUnauthorizedHandler = config.onUnauthorized;
78
- function getHeaders(activeToken, init) {
79
- return {
80
- "Content-Type": "application/json",
81
- ...activeToken ? { Authorization: `Bearer ${activeToken}` } : {},
82
- ...init?.headers || {}
83
- };
84
- }
85
- async function request(path, init) {
86
- const url = (config.baseUrl ? config.baseUrl.replace(/\/$/, "") : "") + apiPath + path;
87
- let activeToken = token;
88
- if (tokenGetter) try {
89
- const fetched = await tokenGetter();
90
- if (fetched !== null && fetched !== void 0) activeToken = fetched;
91
- } catch (e) {}
92
- const headers = getHeaders(activeToken, init);
93
- if (init?.body instanceof FormData) delete headers["Content-Type"];
94
- const res = await fetchFn(url, {
95
- ...init,
96
- headers
97
- });
98
- if (res.status === 204) return void 0;
99
- const text = await res.text().catch(() => "");
100
- let body = {};
101
- if (text) try {
102
- body = JSON.parse(text, rebaseReviver);
103
- } catch (e) {}
104
- const getErrorField = (obj, field) => {
105
- const err = obj?.error;
106
- if (err && typeof err === "object" && err !== null && field in err) return err[field];
107
- return obj?.[field];
108
- };
109
- if (res.status === 401 && onUnauthorizedHandler) {
110
- if (await onUnauthorizedHandler()) {
111
- let retryToken = token;
112
- if (tokenGetter) try {
113
- const fetched = await tokenGetter();
114
- if (fetched !== null && fetched !== void 0) retryToken = fetched;
115
- } catch (e) {}
116
- const retryHeaders = getHeaders(retryToken, init);
117
- const retryRes = await fetchFn(url, {
118
- ...init,
119
- headers: retryHeaders
120
- });
121
- if (retryRes.status === 204) return void 0;
122
- const retryText = await retryRes.text().catch(() => "");
123
- let retryBody = {};
124
- if (retryText) try {
125
- retryBody = JSON.parse(retryText, rebaseReviver);
126
- } catch (e) {}
127
- if (!retryRes.ok) {
128
- let fallbackMessage = retryRes.statusText;
129
- if (retryRes.status === 404 && !fallbackMessage) fallbackMessage = `Endpoint not found (${init?.method || "GET"} ${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.`;
130
- throw new RebaseApiError(retryRes.status, String(getErrorField(retryBody, "message") || fallbackMessage || `Request failed with status ${retryRes.status}`), getErrorField(retryBody, "code"), getErrorField(retryBody, "details"));
131
- }
132
- return retryBody;
133
- }
134
- }
135
- if (!res.ok) {
136
- let fallbackMessage = res.statusText;
137
- if (res.status === 404 && !fallbackMessage) fallbackMessage = `Endpoint not found (${init?.method || "GET"} ${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.`;
138
- throw new RebaseApiError(res.status, String(getErrorField(body, "message") || fallbackMessage || `Request failed with status ${res.status}`), getErrorField(body, "code"), getErrorField(body, "details"));
139
- }
140
- return body;
141
- }
142
- return {
143
- request,
144
- setToken(newToken) {
145
- token = newToken || void 0;
146
- },
147
- setAuthTokenGetter(getter) {
148
- tokenGetter = getter;
149
- },
150
- setOnUnauthorized(handler) {
151
- onUnauthorizedHandler = handler;
152
- },
153
- get baseUrl() {
154
- return config.baseUrl ? config.baseUrl.replace(/\/$/, "") : "";
155
- },
156
- get apiPath() {
157
- return apiPath;
158
- },
159
- get fetchFn() {
160
- return fetchFn;
161
- },
162
- getHeaders: (init) => getHeaders(token, init),
163
- resolveToken: async () => {
164
- if (tokenGetter) try {
165
- const fetched = await tokenGetter();
166
- if (fetched !== null && fetched !== void 0) return fetched;
167
- } catch (e) {}
168
- return token || null;
169
- }
170
- };
171
- }
172
- //#endregion
173
- //#region src/auth.ts
174
- function createMemoryStorage() {
175
- const store = {};
176
- return {
177
- getItem(key) {
178
- return store[key] ?? null;
179
- },
180
- setItem(key, value) {
181
- store[key] = value;
182
- },
183
- removeItem(key) {
184
- delete store[key];
185
- }
186
- };
187
- }
188
- function detectStorage() {
189
- try {
190
- if (typeof localStorage !== "undefined") {
191
- localStorage.setItem("__rebase_test__", "1");
192
- localStorage.removeItem("__rebase_test__");
193
- return localStorage;
194
- }
195
- } catch (e) {}
196
- return createMemoryStorage();
197
- }
198
- function createAuth(transport, options) {
199
- const opts = options || {};
200
- const storage = opts.storage || detectStorage();
201
- const authPath = opts.authPath || "/auth";
202
- const autoRefresh = opts.autoRefresh !== false;
203
- const persistSession = opts.persistSession !== false;
204
- const STORAGE_KEY = "rebase_auth";
205
- const REFRESH_BUFFER_MS = 12e4;
206
- let currentSession = null;
207
- const listeners = /* @__PURE__ */ new Set();
208
- let refreshTimeout = null;
209
- function authUrl(endpoint) {
210
- return transport.baseUrl + transport.apiPath + authPath + endpoint;
211
- }
212
- function getFetch() {
213
- return transport.fetchFn || globalThis.fetch;
214
- }
215
- function throwApiError(status, body, statusText) {
216
- throw new RebaseApiError(status, body?.error?.message || body?.message || statusText, body?.error?.code || body?.code, body?.error?.details || body?.details);
217
- }
218
- function emit(event, session) {
219
- for (const fn of listeners) try {
220
- fn(event, session);
221
- } catch (e) {}
222
- }
223
- function saveSession(session) {
224
- if (!persistSession) return;
225
- try {
226
- storage.setItem(STORAGE_KEY, JSON.stringify(session));
227
- } catch (e) {}
228
- }
229
- function clearStoredSession() {
230
- try {
231
- storage.removeItem(STORAGE_KEY);
232
- } catch (e) {}
233
- }
234
- function loadStoredSession() {
235
- try {
236
- const raw = storage.getItem(STORAGE_KEY);
237
- if (raw) return JSON.parse(raw);
238
- } catch (e) {}
239
- return null;
240
- }
241
- function scheduleRefresh(expiresAt) {
242
- if (refreshTimeout) clearTimeout(refreshTimeout);
243
- if (!autoRefresh) return;
244
- const delay = expiresAt - REFRESH_BUFFER_MS - Date.now();
245
- if (delay <= 0) {
246
- refreshSession().catch(() => signOut());
247
- return;
248
- }
249
- refreshTimeout = setTimeout(async () => {
250
- try {
251
- await refreshSession();
252
- } catch (e) {
253
- signOut();
254
- }
255
- }, delay);
256
- }
257
- function handleAuthResponse(data, event) {
258
- const session = {
259
- accessToken: data.tokens.accessToken,
260
- refreshToken: data.tokens.refreshToken,
261
- expiresAt: data.tokens.accessTokenExpiresAt,
262
- user: data.user
263
- };
264
- currentSession = session;
265
- saveSession(session);
266
- transport.setToken(session.accessToken);
267
- scheduleRefresh(session.expiresAt);
268
- emit(event || "SIGNED_IN", session);
269
- return session;
270
- }
271
- async function signInWithEmail(email, password) {
272
- const res = await getFetch()(authUrl("/login"), {
273
- method: "POST",
274
- headers: { "Content-Type": "application/json" },
275
- body: JSON.stringify({
276
- email,
277
- password
278
- })
279
- });
280
- const body = await res.json().catch(() => ({}));
281
- if (!res.ok) throwApiError(res.status, body, res.statusText);
282
- const session = handleAuthResponse(body, "SIGNED_IN");
283
- return {
284
- user: session.user,
285
- accessToken: session.accessToken,
286
- refreshToken: session.refreshToken
287
- };
288
- }
289
- async function signUp(email, password, displayName) {
290
- const fetchFn = getFetch();
291
- const payload = {
292
- email,
293
- password
294
- };
295
- if (displayName !== void 0) payload.displayName = displayName;
296
- const res = await fetchFn(authUrl("/register"), {
297
- method: "POST",
298
- headers: { "Content-Type": "application/json" },
299
- body: JSON.stringify(payload)
300
- });
301
- const body = await res.json().catch(() => ({}));
302
- if (!res.ok) throwApiError(res.status, body, res.statusText);
303
- const session = handleAuthResponse(body, "SIGNED_IN");
304
- return {
305
- user: session.user,
306
- accessToken: session.accessToken,
307
- refreshToken: session.refreshToken
308
- };
309
- }
310
- /**
311
- * Sign in with Google.
312
- *
313
- * Supports three invocation styles:
314
- * - `signInWithGoogle({ idToken })` — ID-token flow (One Tap / Sign In button)
315
- * - `signInWithGoogle({ accessToken })` — Access-token flow (popup)
316
- * - `signInWithGoogle({ code, redirectUri })` — Authorization code flow (most secure)
317
- */
318
- async function signInWithGoogle(payload) {
319
- const res = await getFetch()(authUrl("/google"), {
320
- method: "POST",
321
- headers: { "Content-Type": "application/json" },
322
- body: JSON.stringify(payload)
323
- });
324
- const responseBody = await res.json().catch(() => ({}));
325
- if (!res.ok) throwApiError(res.status, responseBody, res.statusText);
326
- const session = handleAuthResponse(responseBody, "SIGNED_IN");
327
- return {
328
- user: session.user,
329
- accessToken: session.accessToken,
330
- refreshToken: session.refreshToken
331
- };
332
- }
333
- async function signInWithLinkedin(code, redirectUri) {
334
- const res = await getFetch()(authUrl("/linkedin"), {
335
- method: "POST",
336
- headers: { "Content-Type": "application/json" },
337
- body: JSON.stringify({
338
- code,
339
- redirectUri
340
- })
341
- });
342
- const body = await res.json().catch(() => ({}));
343
- if (!res.ok) throwApiError(res.status, body, res.statusText);
344
- const session = handleAuthResponse(body, "SIGNED_IN");
345
- return {
346
- user: session.user,
347
- accessToken: session.accessToken,
348
- refreshToken: session.refreshToken
349
- };
350
- }
351
- /**
352
- * Generic OAuth sign-in. Posts the given payload to `/auth/{providerId}`.
353
- * Use this for any provider registered on the backend.
354
- */
355
- async function signInWithOAuth(providerId, payload) {
356
- const res = await getFetch()(authUrl(`/${providerId}`), {
357
- method: "POST",
358
- headers: { "Content-Type": "application/json" },
359
- body: JSON.stringify(payload)
360
- });
361
- const body = await res.json().catch(() => ({}));
362
- if (!res.ok) throwApiError(res.status, body, res.statusText);
363
- const session = handleAuthResponse(body, "SIGNED_IN");
364
- return {
365
- user: session.user,
366
- accessToken: session.accessToken,
367
- refreshToken: session.refreshToken
368
- };
369
- }
370
- async function signInWithGitHub(code, redirectUri) {
371
- return signInWithOAuth("github", {
372
- code,
373
- redirectUri
374
- });
375
- }
376
- async function signInWithMicrosoft(code, redirectUri) {
377
- return signInWithOAuth("microsoft", {
378
- code,
379
- redirectUri
380
- });
381
- }
382
- async function signInWithApple(code, redirectUri, user) {
383
- return signInWithOAuth("apple", {
384
- code,
385
- redirectUri,
386
- user
387
- });
388
- }
389
- async function signInWithFacebook(code, redirectUri) {
390
- return signInWithOAuth("facebook", {
391
- code,
392
- redirectUri
393
- });
394
- }
395
- async function signInWithTwitter(code, redirectUri, codeVerifier) {
396
- return signInWithOAuth("twitter", {
397
- code,
398
- redirectUri,
399
- codeVerifier
400
- });
401
- }
402
- async function signInWithDiscord(code, redirectUri) {
403
- return signInWithOAuth("discord", {
404
- code,
405
- redirectUri
406
- });
407
- }
408
- async function signInWithGitLab(code, redirectUri) {
409
- return signInWithOAuth("gitlab", {
410
- code,
411
- redirectUri
412
- });
413
- }
414
- async function signInWithBitbucket(code, redirectUri) {
415
- return signInWithOAuth("bitbucket", {
416
- code,
417
- redirectUri
418
- });
419
- }
420
- async function signInWithSlack(code, redirectUri) {
421
- return signInWithOAuth("slack", {
422
- code,
423
- redirectUri
424
- });
425
- }
426
- async function signInWithSpotify(code, redirectUri) {
427
- return signInWithOAuth("spotify", {
428
- code,
429
- redirectUri
430
- });
431
- }
432
- async function signOut() {
433
- const fetchFn = getFetch();
434
- try {
435
- if (currentSession?.refreshToken) await fetchFn(authUrl("/logout"), {
436
- method: "POST",
437
- headers: { "Content-Type": "application/json" },
438
- body: JSON.stringify({ refreshToken: currentSession.refreshToken })
439
- });
440
- } catch (e) {}
441
- currentSession = null;
442
- clearStoredSession();
443
- if (refreshTimeout) {
444
- clearTimeout(refreshTimeout);
445
- refreshTimeout = null;
446
- }
447
- transport.setToken(null);
448
- emit("SIGNED_OUT", null);
449
- }
450
- async function refreshSession() {
451
- if (!currentSession?.refreshToken) throw new Error("No active session to refresh");
452
- const res = await getFetch()(authUrl("/refresh"), {
453
- method: "POST",
454
- headers: { "Content-Type": "application/json" },
455
- body: JSON.stringify({ refreshToken: currentSession.refreshToken })
456
- });
457
- const body = await res.json().catch(() => ({}));
458
- if (!res.ok) throwApiError(res.status, body, res.statusText);
459
- const session = {
460
- accessToken: body.tokens.accessToken,
461
- refreshToken: body.tokens.refreshToken,
462
- expiresAt: body.tokens.accessTokenExpiresAt,
463
- user: currentSession.user
464
- };
465
- currentSession = session;
466
- saveSession(session);
467
- transport.setToken(session.accessToken);
468
- scheduleRefresh(session.expiresAt);
469
- emit("TOKEN_REFRESHED", session);
470
- return session;
471
- }
472
- async function getUser() {
473
- return (await transport.request(authPath + "/me", { method: "GET" })).user;
474
- }
475
- async function updateUser(updates) {
476
- const data = await transport.request(authPath + "/me", {
477
- method: "PATCH",
478
- body: JSON.stringify(updates)
479
- });
480
- if (currentSession) {
481
- currentSession = {
482
- ...currentSession,
483
- user: data.user
484
- };
485
- saveSession(currentSession);
486
- emit("USER_UPDATED", currentSession);
487
- }
488
- return data.user;
489
- }
490
- async function resetPasswordForEmail(email) {
491
- const res = await getFetch()(authUrl("/forgot-password"), {
492
- method: "POST",
493
- headers: { "Content-Type": "application/json" },
494
- body: JSON.stringify({ email })
495
- });
496
- const body = await res.json().catch(() => ({}));
497
- if (!res.ok) throwApiError(res.status, body, res.statusText);
498
- return body;
499
- }
500
- async function resetPassword(token, password) {
501
- const res = await getFetch()(authUrl("/reset-password"), {
502
- method: "POST",
503
- headers: { "Content-Type": "application/json" },
504
- body: JSON.stringify({
505
- token,
506
- password
507
- })
508
- });
509
- const body = await res.json().catch(() => ({}));
510
- if (!res.ok) throwApiError(res.status, body, res.statusText);
511
- return body;
512
- }
513
- async function changePassword(oldPassword, newPassword) {
514
- return transport.request(authPath + "/change-password", {
515
- method: "POST",
516
- body: JSON.stringify({
517
- oldPassword,
518
- newPassword
519
- })
520
- });
521
- }
522
- async function sendVerificationEmail() {
523
- return transport.request(authPath + "/send-verification", { method: "POST" });
524
- }
525
- async function verifyEmail(token) {
526
- const res = await getFetch()(authUrl("/verify-email?token=" + encodeURIComponent(token)), {
527
- method: "GET",
528
- headers: { "Content-Type": "application/json" }
529
- });
530
- const body = await res.json().catch(() => ({}));
531
- if (!res.ok) throwApiError(res.status, body, res.statusText);
532
- return body;
533
- }
534
- async function sendMagicLink(email) {
535
- const res = await getFetch()(authUrl("/magic-link"), {
536
- method: "POST",
537
- headers: { "Content-Type": "application/json" },
538
- body: JSON.stringify({ email })
539
- });
540
- const body = await res.json().catch(() => ({}));
541
- if (!res.ok) throwApiError(res.status, body, res.statusText);
542
- return body;
543
- }
544
- async function verifyMagicLink(token) {
545
- const res = await getFetch()(authUrl("/magic-link/verify"), {
546
- method: "POST",
547
- headers: { "Content-Type": "application/json" },
548
- body: JSON.stringify({ token })
549
- });
550
- const body = await res.json().catch(() => ({}));
551
- if (!res.ok) throwApiError(res.status, body, res.statusText);
552
- const session = handleAuthResponse(body, "SIGNED_IN");
553
- return {
554
- user: session.user,
555
- accessToken: session.accessToken,
556
- refreshToken: session.refreshToken
557
- };
558
- }
559
- async function getSessions() {
560
- return (await transport.request(authPath + "/sessions", { method: "GET" })).sessions;
561
- }
562
- async function revokeSession(sessionId) {
563
- return transport.request(authPath + "/sessions/" + encodeURIComponent(sessionId), { method: "DELETE" });
564
- }
565
- async function revokeAllSessions() {
566
- const result = await transport.request(authPath + "/sessions", { method: "DELETE" });
567
- currentSession = null;
568
- clearStoredSession();
569
- if (refreshTimeout) {
570
- clearTimeout(refreshTimeout);
571
- refreshTimeout = null;
572
- }
573
- transport.setToken(null);
574
- emit("SIGNED_OUT", null);
575
- return result;
576
- }
577
- async function getAuthConfig() {
578
- const res = await getFetch()(authUrl("/config"), {
579
- method: "GET",
580
- headers: { "Content-Type": "application/json" }
581
- });
582
- const body = await res.json().catch(() => ({}));
583
- if (!res.ok) throwApiError(res.status, body, res.statusText);
584
- return body;
585
- }
586
- function getSession() {
587
- return currentSession;
588
- }
589
- function onAuthStateChange(callback) {
590
- listeners.add(callback);
591
- return () => listeners.delete(callback);
592
- }
593
- if (persistSession) {
594
- const stored = loadStoredSession();
595
- if (stored && stored.accessToken && stored.refreshToken) {
596
- if (stored.expiresAt > Date.now()) {
597
- currentSession = stored;
598
- transport.setToken(stored.accessToken);
599
- scheduleRefresh(stored.expiresAt);
600
- } else if (stored.refreshToken) {
601
- currentSession = stored;
602
- refreshSession().catch(() => {
603
- currentSession = null;
604
- clearStoredSession();
605
- transport.setToken(null);
606
- });
607
- }
608
- }
609
- }
610
- return {
611
- signInWithEmail,
612
- signUp,
613
- signInWithGoogle,
614
- signInWithLinkedin,
615
- signInWithOAuth,
616
- signInWithGitHub,
617
- signInWithMicrosoft,
618
- signInWithApple,
619
- signInWithFacebook,
620
- signInWithTwitter,
621
- signInWithDiscord,
622
- signInWithGitLab,
623
- signInWithBitbucket,
624
- signInWithSlack,
625
- signInWithSpotify,
626
- signOut,
627
- refreshSession,
628
- getUser,
629
- updateUser,
630
- resetPasswordForEmail,
631
- resetPassword,
632
- changePassword,
633
- sendVerificationEmail,
634
- verifyEmail,
635
- sendMagicLink,
636
- verifyMagicLink,
637
- getSessions,
638
- revokeSession,
639
- revokeAllSessions,
640
- getAuthConfig,
641
- getSession,
642
- onAuthStateChange
643
- };
644
- }
645
- function createCookieStorage(options = {}) {
646
- const defaultOptions = {
647
- path: "/",
648
- sameSite: "Lax",
649
- ...options
650
- };
651
- return {
652
- getItem(key) {
653
- if (typeof document === "undefined") return null;
654
- const nameEQ = encodeURIComponent(key) + "=";
655
- const ca = document.cookie.split(";");
656
- for (let i = 0; i < ca.length; i++) {
657
- let c = ca[i];
658
- while (c.charAt(0) === " ") c = c.substring(1, c.length);
659
- if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length));
660
- }
661
- return null;
662
- },
663
- setItem(key, value) {
664
- if (typeof document === "undefined") return;
665
- let cookieStr = `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
666
- if (defaultOptions.path) cookieStr += `; path=${defaultOptions.path}`;
667
- if (defaultOptions.domain) cookieStr += `; domain=${defaultOptions.domain}`;
668
- if (defaultOptions.maxAge !== void 0) cookieStr += `; max-age=${defaultOptions.maxAge}`;
669
- else cookieStr += `; max-age=${365 * 24 * 60 * 60}`;
670
- if (defaultOptions.secure) cookieStr += "; secure";
671
- if (defaultOptions.sameSite) cookieStr += `; samesite=${defaultOptions.sameSite}`;
672
- document.cookie = cookieStr;
673
- },
674
- removeItem(key) {
675
- if (typeof document === "undefined") return;
676
- let cookieStr = `${encodeURIComponent(key)}=; path=${defaultOptions.path || "/"}; max-age=-1`;
677
- if (defaultOptions.domain) cookieStr += `; domain=${defaultOptions.domain}`;
678
- document.cookie = cookieStr;
679
- }
680
- };
681
- }
682
- //#endregion
683
- //#region src/admin.ts
684
- function createAdmin(transport, options) {
685
- const adminPath = (options || {}).adminPath || "/admin";
686
- async function listUsers() {
687
- return transport.request(adminPath + "/users", { method: "GET" });
688
- }
689
- async function listUsersPaginated(options) {
690
- const params = new URLSearchParams();
691
- if (options?.limit !== void 0) params.set("limit", String(options.limit));
692
- if (options?.offset !== void 0) params.set("offset", String(options.offset));
693
- if (options?.search) params.set("search", options.search);
694
- if (options?.orderBy) params.set("orderBy", options.orderBy);
695
- if (options?.orderDir) params.set("orderDir", options.orderDir);
696
- const qs = params.toString();
697
- return transport.request(adminPath + "/users" + (qs ? "?" + qs : ""), { method: "GET" });
698
- }
699
- async function getUser(userId) {
700
- return transport.request(adminPath + "/users/" + encodeURIComponent(userId), { method: "GET" });
701
- }
702
- async function createUser(data) {
703
- return transport.request(adminPath + "/users", {
704
- method: "POST",
705
- body: JSON.stringify(data)
706
- });
707
- }
708
- async function updateUser(userId, data) {
709
- return transport.request(adminPath + "/users/" + encodeURIComponent(userId), {
710
- method: "PUT",
711
- body: JSON.stringify(data)
712
- });
713
- }
714
- async function deleteUser(userId) {
715
- return transport.request(adminPath + "/users/" + encodeURIComponent(userId), { method: "DELETE" });
716
- }
717
- async function resetPassword(userId, options) {
718
- return transport.request(adminPath + "/users/" + encodeURIComponent(userId) + "/reset-password", {
719
- method: "POST",
720
- ...options?.password ? { body: JSON.stringify({ password: options.password }) } : {}
721
- });
722
- }
723
- async function listRoles() {
724
- return transport.request(adminPath + "/roles", { method: "GET" });
725
- }
726
- async function bootstrap() {
727
- return transport.request(adminPath + "/bootstrap", { method: "POST" });
728
- }
729
- return {
730
- listUsers,
731
- listUsersPaginated,
732
- getUser,
733
- createUser,
734
- updateUser,
735
- deleteUser,
736
- resetPassword,
737
- listRoles,
738
- bootstrap
739
- };
740
- }
741
- //#endregion
742
- //#region src/cron.ts
743
- function createCron(transport, options) {
744
- const cronPath = options?.cronPath || "/cron";
745
- async function listJobs() {
746
- return transport.request(cronPath, { method: "GET" });
747
- }
748
- async function getJob(jobId) {
749
- return transport.request(cronPath + "/" + encodeURIComponent(jobId), { method: "GET" });
750
- }
751
- async function triggerJob(jobId) {
752
- return transport.request(cronPath + "/" + encodeURIComponent(jobId) + "/trigger", { method: "POST" });
753
- }
754
- async function getJobLogs(jobId, options) {
755
- const params = new URLSearchParams();
756
- if (options?.limit !== void 0) params.set("limit", String(options.limit));
757
- const qs = params.toString();
758
- return transport.request(cronPath + "/" + encodeURIComponent(jobId) + "/logs" + (qs ? "?" + qs : ""), { method: "GET" });
759
- }
760
- async function toggleJob(jobId, enabled) {
761
- return transport.request(cronPath + "/" + encodeURIComponent(jobId), {
762
- method: "PUT",
763
- body: JSON.stringify({ enabled })
764
- });
765
- }
766
- return {
767
- listJobs,
768
- getJob,
769
- triggerJob,
770
- getJobLogs,
771
- toggleJob
772
- };
773
- }
774
- //#endregion
775
- //#region src/api-keys.ts
776
- /**
777
- * Creates a client for managing API keys via the admin routes.
778
- *
779
- * @param transport - The shared HTTP transport created by `createTransport`.
780
- * @param options - Optional overrides (e.g. a custom base path).
781
- */
782
- function createApiKeys(transport, options) {
783
- const apiKeysPath = options?.apiKeysPath || "/admin/api-keys";
784
- /** List all API keys (masked). */
785
- async function listKeys() {
786
- return transport.request(apiKeysPath, { method: "GET" });
787
- }
788
- /** Get a single API key by ID (masked). */
789
- async function getKey(id) {
790
- return transport.request(apiKeysPath + "/" + encodeURIComponent(id), { method: "GET" });
791
- }
792
- /** Create a new API key. The full secret is included in the response. */
793
- async function createKey(data) {
794
- return transport.request(apiKeysPath, {
795
- method: "POST",
796
- body: JSON.stringify(data)
797
- });
798
- }
799
- /** Update an existing API key. */
800
- async function updateKey(id, data) {
801
- return transport.request(apiKeysPath + "/" + encodeURIComponent(id), {
802
- method: "PUT",
803
- body: JSON.stringify(data)
804
- });
805
- }
806
- /** Revoke (soft-delete) an API key. */
807
- async function revokeKey(id) {
808
- return transport.request(apiKeysPath + "/" + encodeURIComponent(id), { method: "DELETE" });
809
- }
810
- return {
811
- listKeys,
812
- getKey,
813
- createKey,
814
- updateKey,
815
- revokeKey
816
- };
817
- }
818
- //#endregion
819
- //#region src/collection.ts
820
- /**
821
- * Wrap a flat row (returned by the REST API as `{ id, ...fields }`) into
822
- * a proper `Entity<M>` structure expected by the core framework.
823
- * The `id` is kept inside `values` as well, since collection properties
824
- * may define an `isId` field that the form binds to `formex.values`.
825
- */
826
- function rowToEntity(row, slug) {
827
- return {
828
- id: row.id,
829
- path: slug,
830
- values: row
831
- };
832
- }
833
- function createCollectionClient(transport, slug, ws) {
834
- const basePath = `/data/${slug}`;
835
- const client = {
836
- async find(params) {
837
- const qs = buildQueryString(params);
838
- const raw = await transport.request(basePath + qs, { method: "GET" });
839
- return {
840
- data: (raw.data || []).map((row) => rowToEntity(row, slug)),
841
- meta: raw.meta
842
- };
843
- },
844
- async findById(id) {
845
- try {
846
- const raw = await transport.request(`${basePath}/${encodeURIComponent(String(id))}`, { method: "GET" });
847
- if (!raw) return void 0;
848
- return rowToEntity(raw, slug);
849
- } catch (err) {
850
- if (err instanceof RebaseApiError && err.status === 404) return;
851
- throw err;
852
- }
853
- },
854
- async create(data, id) {
855
- const body = { ...data };
856
- if (id !== void 0) body.id = id;
857
- return rowToEntity(await transport.request(basePath, {
858
- method: "POST",
859
- body: JSON.stringify(body)
860
- }), slug);
861
- },
862
- async update(id, data) {
863
- return rowToEntity(await transport.request(`${basePath}/${encodeURIComponent(String(id))}`, {
864
- method: "PUT",
865
- body: JSON.stringify(data)
866
- }), slug);
867
- },
868
- async delete(id) {
869
- return transport.request(`${basePath}/${encodeURIComponent(String(id))}`, { method: "DELETE" });
870
- },
871
- async count(params) {
872
- const qs = buildQueryString({
873
- ...params,
874
- limit: void 0,
875
- offset: void 0
876
- });
877
- return (await transport.request(basePath + "/count" + qs, { method: "GET" })).count ?? 0;
878
- },
879
- where(columnOrCondition, operator, value) {
880
- const builder = new _rebasepro_common.QueryBuilder(client);
881
- if (typeof columnOrCondition === "object") return builder.where(columnOrCondition);
882
- return builder.where(columnOrCondition, operator, value);
883
- },
884
- orderBy(column, direction) {
885
- return new _rebasepro_common.QueryBuilder(client).orderBy(column, direction);
886
- },
887
- limit(count) {
888
- return new _rebasepro_common.QueryBuilder(client).limit(count);
889
- },
890
- offset(count) {
891
- return new _rebasepro_common.QueryBuilder(client).offset(count);
892
- },
893
- search(searchString) {
894
- return new _rebasepro_common.QueryBuilder(client).search(searchString);
895
- },
896
- include(...relations) {
897
- return new _rebasepro_common.QueryBuilder(client).include(...relations);
898
- }
899
- };
900
- if (ws) {
901
- client.listen = (params, onUpdate, onError) => {
902
- let active = true;
903
- let lastUpdateId = 0;
904
- const unsub = ws.listenCollection({
905
- path: slug,
906
- filter: params?.where,
907
- limit: params?.limit,
908
- startAfter: params?.offset ? String(params.offset) : void 0,
909
- orderBy: params?.orderBy?.split(":")[0],
910
- order: params?.orderBy?.split(":")[1],
911
- searchString: params?.searchString
912
- }, (entities) => {
913
- const currentUpdateId = ++lastUpdateId;
914
- const requestedLimit = params?.limit || 20;
915
- const offset = params?.offset || 0;
916
- onUpdate({
917
- data: entities,
918
- meta: {
919
- total: entities.length,
920
- limit: requestedLimit,
921
- offset,
922
- hasMore: entities.length >= requestedLimit
923
- }
924
- });
925
- if (client.count) client.count(params).then((total) => {
926
- if (active && currentUpdateId === lastUpdateId) onUpdate({
927
- data: entities,
928
- meta: {
929
- total,
930
- limit: requestedLimit,
931
- offset,
932
- hasMore: offset + entities.length < total
933
- }
934
- });
935
- }).catch(() => {});
936
- }, onError);
937
- return () => {
938
- active = false;
939
- unsub();
940
- };
941
- };
942
- client.listenById = (id, onUpdate, onError) => {
943
- return ws.listenEntity({
944
- path: slug,
945
- entityId: String(id)
946
- }, (entity) => {
947
- if (entity) onUpdate(entity);
948
- else onUpdate(void 0);
949
- }, onError);
950
- };
951
- }
952
- return client;
953
- }
954
- //#endregion
955
- //#region src/functions.ts
956
- /**
957
- * Create a `FunctionsClient` backed by the given transport.
958
- *
959
- * The transport already handles:
960
- * - Base URL resolution
961
- * - JWT injection via `Authorization: Bearer`
962
- * - 401 retry / `onUnauthorized` flow
963
- * - Consistent error throwing via `RebaseApiError`
964
- *
965
- * @internal
966
- */
967
- function createFunctionsClient(transport) {
968
- return { async invoke(name, payload, options) {
969
- const method = options?.method ?? "POST";
970
- const subPath = options?.path ? `/${options.path.replace(/^\//, "")}` : "";
971
- const routePath = `/functions/${encodeURIComponent(name)}${subPath}`;
972
- const init = { method };
973
- if (payload !== void 0 && method !== "GET") init.body = JSON.stringify(payload);
974
- if (options?.headers) init.headers = options.headers;
975
- return transport.request(routePath, init);
976
- } };
977
- }
978
- //#endregion
979
- //#region src/storage.ts
980
- /**
981
- * Create a StorageSource that talks to the Rebase backend REST API.
982
- *
983
- * @param transport - HTTP transport instance
984
- * @param storageId - Optional storage-source key for multi-backend routing.
985
- * When set, it is forwarded to the server so the correct
986
- * `StorageController` is resolved from the registry.
987
- */
988
- function createStorage(transport, storageId) {
989
- const urlsCache = /* @__PURE__ */ new Map();
990
- /** Append ?storageId=... to a path when multi-backend routing is active. */
991
- const withStorageId = (path) => {
992
- if (!storageId) return path;
993
- return `${path}${path.includes("?") ? "&" : "?"}storageId=${encodeURIComponent(storageId)}`;
994
- };
995
- async function putObject({ file, key, metadata, bucket }) {
996
- const formData = new FormData();
997
- formData.append("file", file);
998
- if (key) formData.append("key", key);
999
- if (bucket) formData.append("bucket", bucket);
1000
- if (storageId) formData.append("storageId", storageId);
1001
- if (metadata) {
1002
- for (const [key, value] of Object.entries(metadata)) if (value !== void 0 && value !== null) formData.append(`metadata_${key}`, typeof value === "string" ? value : JSON.stringify(value));
1003
- }
1004
- return (await transport.request(withStorageId("/storage/upload"), {
1005
- method: "POST",
1006
- body: formData,
1007
- headers: {}
1008
- })).data;
1009
- }
1010
- async function getSignedUrl(keyOrUrl, bucket) {
1011
- const cacheKey = bucket ? `${bucket}/${keyOrUrl}` : keyOrUrl;
1012
- const cached = urlsCache.get(cacheKey);
1013
- if (cached) return cached;
1014
- let filePath = keyOrUrl;
1015
- if (filePath && (filePath.startsWith("local://") || filePath.startsWith("s3://") || filePath.startsWith("gs://"))) filePath = filePath.substring(filePath.indexOf("://") + 3);
1016
- if (bucket && filePath && !filePath.startsWith(bucket)) filePath = `${bucket}/${filePath}`;
1017
- if (!filePath || filePath.trim() === "" || filePath === "/") return {
1018
- url: null,
1019
- fileNotFound: true
1020
- };
1021
- try {
1022
- const result = await transport.request(withStorageId(`/storage/metadata/${filePath}`));
1023
- const activeToken = await transport.resolveToken();
1024
- const tokenQuery = activeToken ? `?token=${activeToken}` : "";
1025
- const downloadConfig = {
1026
- url: withStorageId(`${transport.baseUrl}${transport.apiPath}/storage/file/${filePath}${tokenQuery}`),
1027
- metadata: result.data
1028
- };
1029
- urlsCache.set(cacheKey, downloadConfig);
1030
- return downloadConfig;
1031
- } catch (e) {
1032
- if (e instanceof Error && "status" in e && e.status === 404) return {
1033
- url: null,
1034
- fileNotFound: true
1035
- };
1036
- throw e;
1037
- }
1038
- }
1039
- async function getObject(key, bucket) {
1040
- let filePath = key;
1041
- if (filePath && (filePath.startsWith("local://") || filePath.startsWith("s3://") || filePath.startsWith("gs://"))) filePath = filePath.substring(filePath.indexOf("://") + 3);
1042
- if (bucket && filePath && !filePath.startsWith(bucket)) filePath = `${bucket}/${filePath}`;
1043
- if (!filePath || filePath.trim() === "" || filePath === "/") return null;
1044
- const url = withStorageId(`${transport.baseUrl}${transport.apiPath}/storage/file/${filePath}`);
1045
- const response = await transport.fetchFn(url, { headers: transport.getHeaders ? transport.getHeaders() : {} });
1046
- if (response.status === 404) return null;
1047
- if (!response.ok) throw new Error("Failed to get file");
1048
- const blob = await response.blob();
1049
- const fileName = filePath.split("/").pop() || "file";
1050
- return new File([blob], fileName, { type: blob.type });
1051
- }
1052
- async function deleteObject(key, bucket) {
1053
- let filePath = key;
1054
- if (filePath && (filePath.startsWith("local://") || filePath.startsWith("s3://") || filePath.startsWith("gs://"))) filePath = filePath.substring(filePath.indexOf("://") + 3);
1055
- if (bucket && filePath && !filePath.startsWith(bucket)) filePath = `${bucket}/${filePath}`;
1056
- if (!filePath || filePath.trim() === "" || filePath === "/") return;
1057
- try {
1058
- await transport.request(withStorageId(`/storage/file/${filePath}`), { method: "DELETE" });
1059
- } catch (e) {
1060
- if (!(e instanceof Error && "status" in e && e.status === 404)) throw e;
1061
- }
1062
- urlsCache.delete(bucket ? `${bucket}/${key}` : key);
1063
- }
1064
- async function listObjects(prefix, options) {
1065
- const params = new URLSearchParams();
1066
- if (prefix) params.set("prefix", prefix);
1067
- if (options?.bucket) params.set("bucket", options.bucket);
1068
- if (options?.maxResults) params.set("maxResults", String(options.maxResults));
1069
- if (options?.pageToken) params.set("pageToken", options.pageToken);
1070
- if (storageId) params.set("storageId", storageId);
1071
- return (await transport.request(`/storage/list?${params.toString()}`)).data;
1072
- }
1073
- return {
1074
- putObject,
1075
- getSignedUrl,
1076
- getObject,
1077
- deleteObject,
1078
- listObjects
1079
- };
1080
- }
1081
- //#endregion
1082
- //#region src/storage-registry.ts
1083
- /**
1084
- * Default implementation of the client-side `StorageSourceRegistry`.
1085
- */
1086
- var ClientStorageSourceRegistry = class ClientStorageSourceRegistry {
1087
- sources = /* @__PURE__ */ new Map();
1088
- /**
1089
- * Register a storage source.
1090
- * @param key - Unique key matching a `StorageSourceDefinition.key`
1091
- * @param source - The `StorageSource` instance
1092
- */
1093
- register(key, source) {
1094
- this.sources.set(key, source);
1095
- }
1096
- getDefault() {
1097
- const source = this.sources.get(_rebasepro_types.DEFAULT_STORAGE_SOURCE_KEY);
1098
- if (!source) throw new Error(`[StorageSourceRegistry] No default storage source registered. Register one with key "${_rebasepro_types.DEFAULT_STORAGE_SOURCE_KEY}".`);
1099
- return source;
1100
- }
1101
- get(key) {
1102
- if (key === void 0 || key === null) return this.sources.get(_rebasepro_types.DEFAULT_STORAGE_SOURCE_KEY);
1103
- return this.sources.get(key);
1104
- }
1105
- getOrDefault(key) {
1106
- if (key === void 0 || key === null) return this.getDefault();
1107
- const source = this.sources.get(key);
1108
- if (source) return source;
1109
- console.warn(`[StorageSourceRegistry] Storage source "${key}" not found, falling back to "${_rebasepro_types.DEFAULT_STORAGE_SOURCE_KEY}".`);
1110
- return this.getDefault();
1111
- }
1112
- has(key) {
1113
- return this.sources.has(key);
1114
- }
1115
- list() {
1116
- return Array.from(this.sources.keys());
1117
- }
1118
- /**
1119
- * Build a registry from `StorageSourceDefinition[]` and an HTTP transport.
1120
- *
1121
- * - Sources with `transport: "server"` are auto-wired via `createStorage(transport, key)`.
1122
- * - Sources with `transport: "direct"` are **not** auto-wired — they must
1123
- * be registered manually after this call (e.g. via a Firebase hook).
1124
- *
1125
- * @param definitions - Array of storage source definitions
1126
- * @param transport - HTTP transport for server-backed sources
1127
- */
1128
- static fromDefinitions(definitions, transport) {
1129
- const registry = new ClientStorageSourceRegistry();
1130
- for (const def of definitions) if (def.transport === "server") {
1131
- const source = createStorage(transport, def.key === _rebasepro_types.DEFAULT_STORAGE_SOURCE_KEY ? void 0 : def.key);
1132
- registry.register(def.key, source);
1133
- }
1134
- return registry;
1135
- }
1136
- };
1137
- //#endregion
1138
- //#region src/websocket.ts
1139
- /**
1140
- * Extract error message and code from a WebSocket message payload.
1141
- * Handles both `{ error: string }` and `{ error: { message, code } }` shapes.
1142
- */
1143
- function extractMessageError(message) {
1144
- const payload = message.payload;
1145
- const errPayload = payload?.error;
1146
- return {
1147
- errorMessage: typeof errPayload === "object" ? errPayload.message : payload?.message || (typeof errPayload === "string" ? errPayload : void 0) || message.error || "Unknown error",
1148
- errorCode: typeof errPayload === "object" ? errPayload.code : payload?.code
1149
- };
1150
- }
1151
- var ApiError = class extends Error {
1152
- code;
1153
- error;
1154
- constructor(message, error, code) {
1155
- super(message);
1156
- this.name = "ApiError";
1157
- this.code = code;
1158
- this.error = error;
1159
- }
1160
- };
1161
- var RebaseWebSocketClient = class {
1162
- websocketUrl;
1163
- ws = null;
1164
- getAuthToken;
1165
- subscriptions = /* @__PURE__ */ new Map();
1166
- listeners = /* @__PURE__ */ new Map();
1167
- on(event, cb) {
1168
- if (!this.listeners.has(event)) this.listeners.set(event, /* @__PURE__ */ new Set());
1169
- this.listeners.get(event).add(cb);
1170
- return () => this.listeners.get(event).delete(cb);
1171
- }
1172
- emit(event, ...args) {
1173
- if (this.listeners.has(event)) this.listeners.get(event).forEach((cb) => cb(...args));
1174
- }
1175
- collectionSubscriptions = /* @__PURE__ */ new Map();
1176
- entitySubscriptions = /* @__PURE__ */ new Map();
1177
- backendToCollectionKey = /* @__PURE__ */ new Map();
1178
- backendToEntityKey = /* @__PURE__ */ new Map();
1179
- pendingRequests = /* @__PURE__ */ new Map();
1180
- reconnectAttempts = 0;
1181
- maxReconnectAttempts = 5;
1182
- isConnected = false;
1183
- messageQueue = [];
1184
- requestTimeoutMs = 3e4;
1185
- reconnectTimeout = null;
1186
- isAuthenticated = false;
1187
- authPromise = null;
1188
- WebSocketConstructor;
1189
- onUnauthorized;
1190
- refreshInProgress = null;
1191
- constructor(config) {
1192
- this.websocketUrl = config.websocketUrl;
1193
- this.getAuthToken = config.getAuthToken;
1194
- this.onUnauthorized = config.onUnauthorized;
1195
- this.WebSocketConstructor = config.WebSocket || (typeof WebSocket !== "undefined" ? WebSocket : void 0);
1196
- if (!this.WebSocketConstructor) console.warn("WebSocket is not defined in this environment. Realtime subscriptions will not work unless you provide a WebSocket implementation in the config.");
1197
- else this.initWebSocket();
1198
- }
1199
- /**
1200
- * Authenticate the WebSocket connection
1201
- */
1202
- async authenticate(token) {
1203
- return new Promise((resolve, reject) => {
1204
- const requestId = `auth_${Date.now()}`;
1205
- const timeout = setTimeout(() => {
1206
- this.pendingRequests.delete(requestId);
1207
- this.authPromise = null;
1208
- reject(/* @__PURE__ */ new Error("Authentication timeout"));
1209
- }, 3e4);
1210
- this.pendingRequests.set(requestId, {
1211
- resolve: () => {
1212
- clearTimeout(timeout);
1213
- this.isAuthenticated = true;
1214
- resolve();
1215
- },
1216
- reject: (error) => {
1217
- clearTimeout(timeout);
1218
- reject(error);
1219
- }
1220
- });
1221
- const message = {
1222
- type: "AUTHENTICATE",
1223
- requestId,
1224
- payload: { token }
1225
- };
1226
- if (!this.isConnected || !this.ws) this.messageQueue.unshift(message);
1227
- else this.ws.send(JSON.stringify(message));
1228
- });
1229
- }
1230
- /**
1231
- * Set the auth token getter function
1232
- */
1233
- setAuthTokenGetter(getAuthToken) {
1234
- this.getAuthToken = getAuthToken;
1235
- if (this.isConnected && !this.isAuthenticated && !this.authPromise) {
1236
- console.debug("WebSocket auto-authenticating after token getter set");
1237
- this.getAuthToken().then((token) => {
1238
- if (!this.ws) return;
1239
- if (token) this.authenticate(token).catch((e) => {
1240
- if (this.ws) console.debug("WebSocket auto-auth skipped:", e?.message || e);
1241
- });
1242
- }).catch((e) => {
1243
- if (this.ws) console.debug("WebSocket auto-auth skipped:", e?.message || e);
1244
- });
1245
- }
1246
- }
1247
- disconnect() {
1248
- this.isAuthenticated = false;
1249
- this.authPromise = null;
1250
- if (this.reconnectTimeout) {
1251
- clearTimeout(this.reconnectTimeout);
1252
- this.reconnectTimeout = null;
1253
- }
1254
- if (this.ws) {
1255
- this.ws.onclose = null;
1256
- this.ws.onerror = null;
1257
- this.ws.onopen = null;
1258
- this.ws.onmessage = null;
1259
- this.ws.close();
1260
- this.ws = null;
1261
- }
1262
- }
1263
- initWebSocket() {
1264
- if (!this.WebSocketConstructor) return;
1265
- if (this.ws?.readyState === this.WebSocketConstructor.OPEN) return;
1266
- if (this.ws) {
1267
- this.ws.onclose = null;
1268
- this.ws.close();
1269
- this.ws = null;
1270
- }
1271
- try {
1272
- this.ws = new this.WebSocketConstructor(this.websocketUrl);
1273
- this.ws.onopen = async () => {
1274
- console.debug("Connected to PostgreSQL backend");
1275
- const wasReconnect = this.reconnectAttempts > 0;
1276
- this.isConnected = true;
1277
- this.reconnectAttempts = 0;
1278
- if (this.getAuthToken && !this.isAuthenticated) try {
1279
- const token = await this.getAuthToken();
1280
- if (token) {
1281
- await this.authenticate(token);
1282
- console.debug("WebSocket auto-authenticated");
1283
- }
1284
- } catch (error) {
1285
- console.debug("WebSocket connected without auth:", error?.message || error);
1286
- }
1287
- this.emit(wasReconnect ? "reconnect" : "connect");
1288
- this.processMessageQueue();
1289
- if (wasReconnect) this.resubscribeAll();
1290
- };
1291
- this.ws.onmessage = (event) => {
1292
- try {
1293
- const message = JSON.parse(event.data, rebaseReviver);
1294
- this.handleWebSocketMessage(message);
1295
- } catch (error) {
1296
- console.error("Error parsing WebSocket message:", error);
1297
- }
1298
- };
1299
- this.ws.onclose = () => {
1300
- console.debug("Disconnected from PostgreSQL backend");
1301
- this.isConnected = false;
1302
- this.isAuthenticated = false;
1303
- this.authPromise = null;
1304
- this.emit("disconnect");
1305
- for (const [reqId, request] of this.pendingRequests.entries()) {
1306
- if (reqId.startsWith("auth_")) request.reject(/* @__PURE__ */ new Error("Connection closed during authentication"));
1307
- else if (request.message) {
1308
- request.message._queuedResolve = request.resolve;
1309
- request.message._queuedReject = request.reject;
1310
- this.messageQueue.push(request.message);
1311
- } else request.reject(new ApiError("Connection closed", "Connection closed"));
1312
- this.pendingRequests.delete(reqId);
1313
- }
1314
- this.attemptReconnect();
1315
- };
1316
- this.ws.onerror = (error) => {
1317
- console.error("WebSocket error:", error);
1318
- this.isConnected = false;
1319
- this.emit("error", error);
1320
- };
1321
- } catch (error) {
1322
- console.error("Failed to initialize WebSocket:", error);
1323
- this.attemptReconnect();
1324
- }
1325
- }
1326
- processMessageQueue() {
1327
- while (this.messageQueue.length > 0 && this.isConnected) {
1328
- const message = this.messageQueue.shift();
1329
- if (message) this.sendMessage(message);
1330
- }
1331
- }
1332
- attemptReconnect() {
1333
- if (this.reconnectAttempts >= this.maxReconnectAttempts) {
1334
- console.error("Max reconnection attempts reached");
1335
- return;
1336
- }
1337
- this.reconnectAttempts++;
1338
- const delay = Math.min(1e3 * Math.pow(2, this.reconnectAttempts), 3e4);
1339
- console.debug(`Attempting to reconnect in ${delay}ms (attempt ${this.reconnectAttempts})`);
1340
- if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout);
1341
- this.reconnectTimeout = setTimeout(() => {
1342
- this.reconnectTimeout = null;
1343
- this.initWebSocket();
1344
- }, delay);
1345
- }
1346
- isAuthError(message) {
1347
- if (message.type === "AUTH_ERROR") return true;
1348
- const { errorMessage, errorCode } = extractMessageError(message);
1349
- if (errorCode === "UNAUTHORIZED" || errorCode === "JWT_EXPIRED" || errorCode === "AUTH_ERROR") return true;
1350
- const lowerMessage = errorMessage.toLowerCase();
1351
- return lowerMessage.includes("unauthorized") || lowerMessage.includes("token expired") || lowerMessage.includes("token is expired") || lowerMessage.includes("invalid token") || lowerMessage.includes("session expired") || lowerMessage.includes("auth error");
1352
- }
1353
- async handleAuthFailure() {
1354
- if (this.refreshInProgress) return this.refreshInProgress;
1355
- this.refreshInProgress = (async () => {
1356
- this.isAuthenticated = false;
1357
- this.authPromise = null;
1358
- if (this.onUnauthorized) try {
1359
- if (await this.onUnauthorized() && this.getAuthToken) {
1360
- const token = await this.getAuthToken();
1361
- if (token) {
1362
- await this.authenticate(token);
1363
- return true;
1364
- }
1365
- }
1366
- } catch (error) {
1367
- console.error("WebSocket auth refresh failed:", error);
1368
- }
1369
- return false;
1370
- })();
1371
- try {
1372
- return await this.refreshInProgress;
1373
- } finally {
1374
- this.refreshInProgress = null;
1375
- }
1376
- }
1377
- /**
1378
- * Shared logic for re-subscribing a collection or entity subscription
1379
- * after an auth error is resolved by refreshing credentials.
1380
- */
1381
- resubscribeAfterAuthRefresh(message, subscription, subscriptionKey, idPrefix, backendKeyMap, messageType) {
1382
- this.handleAuthFailure().then((refreshed) => {
1383
- if (refreshed) {
1384
- const oldBackendId = subscription.backendSubscriptionId;
1385
- const newBackendId = `${idPrefix}_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
1386
- subscription.backendSubscriptionId = newBackendId;
1387
- backendKeyMap.delete(oldBackendId);
1388
- backendKeyMap.set(newBackendId, subscriptionKey);
1389
- this.sendMessage({
1390
- type: messageType,
1391
- payload: {
1392
- ...subscription.props,
1393
- subscriptionId: newBackendId
1394
- }
1395
- }).catch((error) => {
1396
- console.error(`[WS] Failed to re-subscribe ${idPrefix} after auth refresh:`, subscriptionKey, error);
1397
- subscription.callbacks.forEach((callback) => {
1398
- if (callback.onError) callback.onError(error);
1399
- });
1400
- });
1401
- } else {
1402
- const { errorMessage, errorCode } = extractMessageError(message);
1403
- const error = new ApiError(errorMessage, errorMessage, errorCode);
1404
- subscription.callbacks.forEach((callback) => {
1405
- if (callback.onError) callback.onError(error);
1406
- });
1407
- }
1408
- }).catch((err) => {
1409
- subscription.callbacks.forEach((callback) => {
1410
- if (callback.onError) callback.onError(err);
1411
- });
1412
- });
1413
- }
1414
- handleWebSocketMessage(message) {
1415
- const { type, requestId, subscriptionId } = message;
1416
- if (requestId && this.pendingRequests.has(requestId)) {
1417
- const pendingReq = this.pendingRequests.get(requestId);
1418
- if (type === "ERROR" || type === "AUTH_ERROR" || message.error) if (this.isAuthError(message)) {
1419
- this.pendingRequests.delete(requestId);
1420
- this.handleAuthFailure().then((refreshed) => {
1421
- if (refreshed && pendingReq.message) this.doSendMessage(pendingReq.message, pendingReq.resolve, pendingReq.reject).catch(pendingReq.reject);
1422
- else {
1423
- const { errorMessage, errorCode } = extractMessageError(message);
1424
- pendingReq.reject(new ApiError(errorMessage, errorMessage, errorCode));
1425
- }
1426
- }).catch((err) => {
1427
- pendingReq.reject(err);
1428
- });
1429
- } else {
1430
- this.pendingRequests.delete(requestId);
1431
- const { errorMessage, errorCode } = extractMessageError(message);
1432
- pendingReq.reject(new ApiError(errorMessage, errorMessage, errorCode));
1433
- }
1434
- else {
1435
- this.pendingRequests.delete(requestId);
1436
- pendingReq.resolve(message.payload || message);
1437
- }
1438
- return;
1439
- }
1440
- if (subscriptionId && type === "collection_update") {
1441
- const subscriptionKey = this.backendToCollectionKey.get(subscriptionId);
1442
- if (subscriptionKey) {
1443
- const collectionSub = this.collectionSubscriptions.get(subscriptionKey);
1444
- if (collectionSub) {
1445
- const incomingEntities = message.entities || [];
1446
- const entities = this.mergeEntities(collectionSub.latestData, incomingEntities);
1447
- collectionSub.latestData = entities;
1448
- collectionSub.lastUpdated = Date.now();
1449
- collectionSub.isInitialDataReceived = true;
1450
- collectionSub.callbacks.forEach((callback) => {
1451
- try {
1452
- callback.onUpdate(entities);
1453
- } catch (error) {
1454
- console.error("Error in collection subscription callback:", error);
1455
- if (callback.onError) callback.onError(error instanceof Error ? error : new Error(String(error)));
1456
- }
1457
- });
1458
- return;
1459
- }
1460
- }
1461
- }
1462
- if (subscriptionId && type === "collection_entity_patch") {
1463
- const subscriptionKey = this.backendToCollectionKey.get(subscriptionId);
1464
- if (subscriptionKey) {
1465
- const collectionSub = this.collectionSubscriptions.get(subscriptionKey);
1466
- if (collectionSub && collectionSub.isInitialDataReceived && collectionSub.latestData) {
1467
- const patchEntity = message.entity ?? null;
1468
- const patchEntityId = message.entityId;
1469
- let updated;
1470
- if (patchEntity === null || patchEntity === void 0) updated = collectionSub.latestData.filter((e) => String(e.id) !== String(patchEntityId));
1471
- else {
1472
- const idx = collectionSub.latestData.findIndex((e) => String(e.id) === String(patchEntity.id));
1473
- if (idx >= 0) {
1474
- updated = [...collectionSub.latestData];
1475
- updated[idx] = patchEntity;
1476
- } else updated = [patchEntity, ...collectionSub.latestData];
1477
- }
1478
- collectionSub.latestData = updated;
1479
- collectionSub.lastUpdated = Date.now();
1480
- collectionSub.callbacks.forEach((callback) => {
1481
- try {
1482
- callback.onUpdate(updated);
1483
- } catch (error) {
1484
- console.error("Error in collection patch callback:", error);
1485
- if (callback.onError) callback.onError(error instanceof Error ? error : new Error(String(error)));
1486
- }
1487
- });
1488
- return;
1489
- }
1490
- }
1491
- }
1492
- if (subscriptionId && type === "entity_update") {
1493
- const subscriptionKey = this.backendToEntityKey.get(subscriptionId);
1494
- if (subscriptionKey) {
1495
- const entitySub = this.entitySubscriptions.get(subscriptionKey);
1496
- if (entitySub) {
1497
- const entity = message.entity ?? null;
1498
- entitySub.latestData = entity;
1499
- entitySub.lastUpdated = Date.now();
1500
- entitySub.isInitialDataReceived = true;
1501
- entitySub.callbacks.forEach((callback) => {
1502
- try {
1503
- callback.onUpdate(entity);
1504
- } catch (error) {
1505
- console.error("Error in entity subscription callback:", error);
1506
- if (callback.onError) callback.onError(error instanceof Error ? error : new Error(String(error)));
1507
- }
1508
- });
1509
- return;
1510
- }
1511
- }
1512
- }
1513
- if (subscriptionId && (type === "ERROR" || message.error)) {
1514
- const collectionKey = this.backendToCollectionKey.get(subscriptionId);
1515
- if (collectionKey) {
1516
- const collectionSub = this.collectionSubscriptions.get(collectionKey);
1517
- if (collectionSub) {
1518
- if (this.isAuthError(message)) {
1519
- this.resubscribeAfterAuthRefresh(message, collectionSub, collectionKey, "collection", this.backendToCollectionKey, "subscribe_collection");
1520
- return;
1521
- }
1522
- const { errorMessage, errorCode } = extractMessageError(message);
1523
- const error = new ApiError(errorMessage, errorMessage, errorCode);
1524
- collectionSub.callbacks.forEach((callback) => {
1525
- if (callback.onError) callback.onError(error);
1526
- });
1527
- return;
1528
- }
1529
- }
1530
- const entityKey = this.backendToEntityKey.get(subscriptionId);
1531
- if (entityKey) {
1532
- const entitySub = this.entitySubscriptions.get(entityKey);
1533
- if (entitySub) {
1534
- if (this.isAuthError(message)) {
1535
- this.resubscribeAfterAuthRefresh(message, entitySub, entityKey, "entity", this.backendToEntityKey, "subscribe_entity");
1536
- return;
1537
- }
1538
- const { errorMessage, errorCode } = extractMessageError(message);
1539
- const error = new ApiError(errorMessage, errorMessage, errorCode);
1540
- entitySub.callbacks.forEach((callback) => {
1541
- if (callback.onError) callback.onError(error);
1542
- });
1543
- return;
1544
- }
1545
- }
1546
- }
1547
- if (subscriptionId && this.subscriptions.has(subscriptionId)) {
1548
- const callback = this.subscriptions.get(subscriptionId);
1549
- if (!callback) throw new Error(`Subscription callback not found for subscriptionId: ${subscriptionId}`);
1550
- if (message.type === "ERROR" || message.error) {
1551
- if (callback.onError) {
1552
- const { errorMessage, errorCode } = extractMessageError(message);
1553
- callback.onError(new ApiError(errorMessage, errorMessage, errorCode));
1554
- }
1555
- } else callback.onUpdate(message);
1556
- }
1557
- }
1558
- async ensureAuthenticated(retryCount = 3) {
1559
- if (this.isAuthenticated || !this.getAuthToken) return;
1560
- if (this.authPromise) {
1561
- await this.authPromise;
1562
- return;
1563
- }
1564
- let lastError = null;
1565
- for (let attempt = 0; attempt < retryCount; attempt++) try {
1566
- const token = await this.getAuthToken();
1567
- if (!token) throw new Error("user not logged in");
1568
- this.authPromise = this.authenticate(token);
1569
- await this.authPromise;
1570
- this.authPromise = null;
1571
- console.debug("WebSocket authenticated on demand");
1572
- return;
1573
- } catch (error) {
1574
- this.authPromise = null;
1575
- lastError = error;
1576
- const errMsg = error instanceof Error ? error.message : String(error);
1577
- if (errMsg.includes("not logged in") || errMsg.includes("Session expired")) {
1578
- console.warn("WebSocket auth failed: user not logged in");
1579
- throw error;
1580
- }
1581
- if (errMsg.includes("still loading")) {
1582
- if (attempt < retryCount - 1) {
1583
- const delay = Math.min(500 * (attempt + 1), 2e3);
1584
- await new Promise((resolve) => setTimeout(resolve, delay));
1585
- continue;
1586
- }
1587
- }
1588
- if (attempt < retryCount - 1) {
1589
- const delay = Math.min(1e3 * (attempt + 1), 3e3);
1590
- console.debug(`WebSocket auth attempt ${attempt + 1} failed, retrying in ${delay}ms...`);
1591
- await new Promise((resolve) => setTimeout(resolve, delay));
1592
- }
1593
- }
1594
- console.warn("WebSocket on-demand auth failed after retries:", lastError);
1595
- throw lastError;
1596
- }
1597
- async reauthenticate() {
1598
- if (!this.getAuthToken) return;
1599
- this.isAuthenticated = false;
1600
- try {
1601
- const token = await this.getAuthToken();
1602
- if (!token) throw new Error("user not logged in");
1603
- await this.authenticate(token);
1604
- console.debug("WebSocket reauthenticated successfully");
1605
- } catch (error) {
1606
- console.error("WebSocket reauthentication failed:", error);
1607
- throw error;
1608
- }
1609
- }
1610
- sendMessage(message) {
1611
- const queuedMsg = message;
1612
- if (queuedMsg._queuedResolve && queuedMsg._queuedReject) return this.doSendMessage(message, queuedMsg._queuedResolve, queuedMsg._queuedReject);
1613
- if (!this.isConnected || !this.ws) return new Promise((resolve, reject) => {
1614
- const queueable = message;
1615
- queueable._queuedResolve = resolve;
1616
- queueable._queuedReject = reject;
1617
- this.messageQueue.push(message);
1618
- });
1619
- return new Promise((resolve, reject) => {
1620
- this.doSendMessage(message, resolve, reject);
1621
- });
1622
- }
1623
- async doSendMessage(message, resolve, reject) {
1624
- if (message.type !== "AUTHENTICATE" && this.getAuthToken && !this.isAuthenticated) try {
1625
- await this.ensureAuthenticated();
1626
- } catch (error) {
1627
- const errorMessage = error instanceof Error ? error.message : "Authentication required";
1628
- reject(new ApiError(errorMessage, errorMessage));
1629
- return;
1630
- }
1631
- const requestId = message.requestId || `req_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
1632
- message.requestId = requestId;
1633
- const expectsResponse = ![
1634
- "subscribe_collection",
1635
- "subscribe_entity",
1636
- "unsubscribe",
1637
- "join_channel",
1638
- "leave_channel",
1639
- "broadcast",
1640
- "presence_track",
1641
- "presence_untrack",
1642
- "presence_state"
1643
- ].includes(message.type);
1644
- if (expectsResponse && !this.pendingRequests.has(requestId)) {
1645
- const timeoutHandle = setTimeout(() => {
1646
- if (this.pendingRequests.has(requestId)) {
1647
- this.pendingRequests.delete(requestId);
1648
- reject(new ApiError("Request timed out", "Request timed out"));
1649
- }
1650
- }, this.requestTimeoutMs);
1651
- this.pendingRequests.set(requestId, {
1652
- resolve: (value) => {
1653
- clearTimeout(timeoutHandle);
1654
- resolve(value);
1655
- },
1656
- reject: (error) => {
1657
- clearTimeout(timeoutHandle);
1658
- reject(error);
1659
- },
1660
- message
1661
- });
1662
- }
1663
- try {
1664
- this.ws.send(JSON.stringify(message));
1665
- if (!expectsResponse) resolve(void 0);
1666
- } catch (error) {
1667
- if (expectsResponse) this.pendingRequests.delete(requestId);
1668
- reject(new ApiError("Failed to send message", error instanceof Error ? error.message : "Unknown error"));
1669
- }
1670
- }
1671
- async fetchCollection(props) {
1672
- return (await this.sendMessage({
1673
- type: "FETCH_COLLECTION",
1674
- payload: props
1675
- })).entities || [];
1676
- }
1677
- async fetchEntity(props) {
1678
- return (await this.sendMessage({
1679
- type: "FETCH_ENTITY",
1680
- payload: props
1681
- })).entity ?? void 0;
1682
- }
1683
- async saveEntity(props) {
1684
- return (await this.sendMessage({
1685
- type: "SAVE_ENTITY",
1686
- payload: props
1687
- })).entity;
1688
- }
1689
- async deleteEntity(props) {
1690
- await this.sendMessage({
1691
- type: "DELETE_ENTITY",
1692
- payload: props
1693
- });
1694
- }
1695
- async executeSql(sql, options) {
1696
- return (await this.sendMessage({
1697
- type: "EXECUTE_SQL",
1698
- payload: {
1699
- sql,
1700
- options
1701
- }
1702
- })).result || [];
1703
- }
1704
- async fetchAvailableDatabases() {
1705
- return (await this.sendMessage({
1706
- type: "FETCH_DATABASES",
1707
- payload: {}
1708
- })).databases || [];
1709
- }
1710
- async fetchAvailableRoles() {
1711
- return (await this.sendMessage({ type: "FETCH_ROLES" })).roles || [];
1712
- }
1713
- async fetchCurrentDatabase() {
1714
- return (await this.sendMessage({ type: "FETCH_CURRENT_DATABASE" })).database;
1715
- }
1716
- async checkUniqueField(path, name, value, entityId, collection) {
1717
- return (await this.sendMessage({
1718
- type: "CHECK_UNIQUE_FIELD",
1719
- payload: {
1720
- path,
1721
- name,
1722
- value,
1723
- entityId,
1724
- collection
1725
- }
1726
- })).isUnique;
1727
- }
1728
- async countEntities(props) {
1729
- return (await this.sendMessage({
1730
- type: "COUNT_ENTITIES",
1731
- payload: props
1732
- })).count;
1733
- }
1734
- async fetchUnmappedTables(mappedPaths) {
1735
- return (await this.sendMessage({
1736
- type: "FETCH_UNMAPPED_TABLES",
1737
- payload: { mappedPaths }
1738
- })).tables || [];
1739
- }
1740
- async fetchTableMetadata(tableName) {
1741
- return (await this.sendMessage({
1742
- type: "FETCH_TABLE_METADATA",
1743
- payload: { tableName }
1744
- })).metadata || {
1745
- columns: [],
1746
- foreignKeys: [],
1747
- junctions: [],
1748
- policies: []
1749
- };
1750
- }
1751
- async createBranch(name, options) {
1752
- return (await this.sendMessage({
1753
- type: "CREATE_BRANCH",
1754
- payload: {
1755
- name,
1756
- options
1757
- }
1758
- })).branch;
1759
- }
1760
- async deleteBranch(name) {
1761
- await this.sendMessage({
1762
- type: "DELETE_BRANCH",
1763
- payload: { name }
1764
- });
1765
- }
1766
- async listBranches() {
1767
- return (await this.sendMessage({
1768
- type: "LIST_BRANCHES",
1769
- payload: {}
1770
- })).branches || [];
1771
- }
1772
- /**
1773
- * Recursively compare two values for structural equality.
1774
- * Handles primitives, null, undefined, Date, RegExp, arrays, and plain objects.
1775
- */
1776
- deepEqual(a, b) {
1777
- if (a === b) return true;
1778
- if (a === null || b === null || a === void 0 || b === void 0) return false;
1779
- if (typeof a !== typeof b) return false;
1780
- if (typeof a !== "object") return false;
1781
- if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
1782
- if (a instanceof Date || b instanceof Date) return false;
1783
- if (a instanceof RegExp && b instanceof RegExp) return a.source === b.source && a.flags === b.flags;
1784
- if (a instanceof RegExp || b instanceof RegExp) return false;
1785
- const aIsArray = Array.isArray(a);
1786
- const bIsArray = Array.isArray(b);
1787
- if (aIsArray !== bIsArray) return false;
1788
- if (aIsArray && bIsArray) {
1789
- if (a.length !== b.length) return false;
1790
- for (let i = 0; i < a.length; i++) if (!this.deepEqual(a[i], b[i])) return false;
1791
- return true;
1792
- }
1793
- const aObj = a;
1794
- const bObj = b;
1795
- const aKeys = Object.keys(aObj);
1796
- const bKeys = Object.keys(bObj);
1797
- if (aKeys.length !== bKeys.length) return false;
1798
- for (const key of aKeys) {
1799
- if (!Object.prototype.hasOwnProperty.call(bObj, key)) return false;
1800
- if (!this.deepEqual(aObj[key], bObj[key])) return false;
1801
- }
1802
- return true;
1803
- }
1804
- normalizeForComparison(val) {
1805
- if (!val) return val;
1806
- if (Array.isArray(val)) return val.map((item) => this.normalizeForComparison(item));
1807
- if (typeof val === "object") {
1808
- if (val instanceof Date) return val;
1809
- if (val instanceof RegExp) return val;
1810
- const obj = val;
1811
- if (obj.__type === "relation") {
1812
- const { data, ...rest } = obj;
1813
- return rest;
1814
- }
1815
- const result = {};
1816
- for (const [k, v] of Object.entries(obj)) result[k] = this.normalizeForComparison(v);
1817
- return result;
1818
- }
1819
- return val;
1820
- }
1821
- /**
1822
- * Merge incoming entities with cached data, preserving cached references
1823
- * for entities whose values haven't changed. This avoids unnecessary
1824
- * React re-renders when the server refetches all entities but most
1825
- * haven't actually changed.
1826
- */
1827
- mergeEntities(cached, incoming) {
1828
- if (!cached || cached.length === 0) return incoming;
1829
- const cachedById = /* @__PURE__ */ new Map();
1830
- for (const entity of cached) cachedById.set(entity.id, entity);
1831
- return incoming.map((incomingEntity) => {
1832
- const cachedEntity = cachedById.get(incomingEntity.id);
1833
- if (!cachedEntity) return incomingEntity;
1834
- if (cachedEntity.path === incomingEntity.path) {
1835
- const normCached = this.normalizeForComparison(cachedEntity.values);
1836
- const normIncoming = this.normalizeForComparison(incomingEntity.values);
1837
- if (this.deepEqual(normCached, normIncoming)) return cachedEntity;
1838
- else {
1839
- const mismatches = {};
1840
- const allKeys = new Set([...Object.keys(normCached), ...Object.keys(normIncoming)]);
1841
- for (const key of allKeys) if (!this.deepEqual(normCached[key], normIncoming[key])) mismatches[key] = {
1842
- cached: normCached[key],
1843
- incoming: normIncoming[key]
1844
- };
1845
- console.debug(`[RebaseWS] Row ${incomingEntity.id} refetch mismatch:\n`, JSON.stringify(mismatches, null, 2));
1846
- }
1847
- }
1848
- return incomingEntity;
1849
- });
1850
- }
1851
- listenCollection(props, onUpdate, onError) {
1852
- const subscriptionKey = this.createCollectionSubscriptionKey(props);
1853
- const callbackId = `callback_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
1854
- const existingSubscription = this.collectionSubscriptions.get(subscriptionKey);
1855
- if (existingSubscription) {
1856
- const callbackMap = existingSubscription.callbacks;
1857
- callbackMap.set(callbackId, {
1858
- onUpdate,
1859
- onError
1860
- });
1861
- if (existingSubscription.latestData !== void 0 && existingSubscription.isInitialDataReceived) try {
1862
- onUpdate(existingSubscription.latestData);
1863
- } catch (error) {
1864
- console.error("Error in collection subscription callback:", error);
1865
- if (onError) onError(error instanceof Error ? error : new Error(String(error)));
1866
- }
1867
- return () => {
1868
- callbackMap.delete(callbackId);
1869
- if (callbackMap.size === 0) {
1870
- this.collectionSubscriptions.delete(subscriptionKey);
1871
- this.backendToCollectionKey.delete(existingSubscription.backendSubscriptionId);
1872
- if (this.isConnected && this.ws) this.sendMessage({
1873
- type: "unsubscribe",
1874
- payload: { subscriptionId: existingSubscription.backendSubscriptionId }
1875
- }).catch(console.error);
1876
- }
1877
- };
1878
- }
1879
- const backendSubscriptionId = `collection_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
1880
- const callbackMap = /* @__PURE__ */ new Map();
1881
- callbackMap.set(callbackId, {
1882
- onUpdate,
1883
- onError
1884
- });
1885
- this.collectionSubscriptions.set(subscriptionKey, {
1886
- backendSubscriptionId,
1887
- callbacks: callbackMap,
1888
- props
1889
- });
1890
- this.backendToCollectionKey.set(backendSubscriptionId, subscriptionKey);
1891
- this.sendMessage({
1892
- type: "subscribe_collection",
1893
- payload: {
1894
- ...props,
1895
- subscriptionId: backendSubscriptionId
1896
- }
1897
- }).catch((error) => {
1898
- if (onError) onError(error);
1899
- });
1900
- return () => {
1901
- const subscription = this.collectionSubscriptions.get(subscriptionKey);
1902
- if (subscription) {
1903
- const callbacks = subscription.callbacks;
1904
- callbacks.delete(callbackId);
1905
- if (callbacks.size === 0) {
1906
- this.collectionSubscriptions.delete(subscriptionKey);
1907
- this.backendToCollectionKey.delete(subscription.backendSubscriptionId);
1908
- if (this.isConnected && this.ws) this.sendMessage({
1909
- type: "unsubscribe",
1910
- payload: { subscriptionId: subscription.backendSubscriptionId }
1911
- }).catch(console.error);
1912
- }
1913
- }
1914
- };
1915
- }
1916
- listenEntity(props, onUpdate, onError) {
1917
- const subscriptionKey = this.createEntitySubscriptionKey(props);
1918
- const callbackId = `callback_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
1919
- const existingSubscription = this.entitySubscriptions.get(subscriptionKey);
1920
- if (existingSubscription) {
1921
- const callbackMap = existingSubscription.callbacks;
1922
- callbackMap.set(callbackId, {
1923
- onUpdate,
1924
- onError
1925
- });
1926
- if (existingSubscription.latestData !== void 0 && existingSubscription.isInitialDataReceived) try {
1927
- onUpdate(existingSubscription.latestData);
1928
- } catch (error) {
1929
- console.error("Error in entity subscription callback:", error);
1930
- if (onError) onError(error instanceof Error ? error : new Error(String(error)));
1931
- }
1932
- return () => {
1933
- callbackMap.delete(callbackId);
1934
- if (callbackMap.size === 0) {
1935
- this.entitySubscriptions.delete(subscriptionKey);
1936
- this.backendToEntityKey.delete(existingSubscription.backendSubscriptionId);
1937
- if (this.isConnected && this.ws) this.sendMessage({
1938
- type: "unsubscribe",
1939
- payload: { subscriptionId: existingSubscription.backendSubscriptionId }
1940
- }).catch(console.error);
1941
- }
1942
- };
1943
- }
1944
- const backendSubscriptionId = `entity_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
1945
- const callbackMap = /* @__PURE__ */ new Map();
1946
- callbackMap.set(callbackId, {
1947
- onUpdate,
1948
- onError
1949
- });
1950
- this.entitySubscriptions.set(subscriptionKey, {
1951
- backendSubscriptionId,
1952
- callbacks: callbackMap,
1953
- props
1954
- });
1955
- this.backendToEntityKey.set(backendSubscriptionId, subscriptionKey);
1956
- this.sendMessage({
1957
- type: "subscribe_entity",
1958
- payload: {
1959
- ...props,
1960
- subscriptionId: backendSubscriptionId
1961
- }
1962
- }).catch((error) => {
1963
- if (onError) onError(error);
1964
- });
1965
- return () => {
1966
- const subscription = this.entitySubscriptions.get(subscriptionKey);
1967
- if (subscription) {
1968
- const callbacks = subscription.callbacks;
1969
- callbacks.delete(callbackId);
1970
- if (callbacks.size === 0) {
1971
- this.entitySubscriptions.delete(subscriptionKey);
1972
- this.backendToEntityKey.delete(subscription.backendSubscriptionId);
1973
- if (this.isConnected && this.ws) this.sendMessage({
1974
- type: "unsubscribe",
1975
- payload: { subscriptionId: subscription.backendSubscriptionId }
1976
- }).catch(console.error);
1977
- }
1978
- }
1979
- };
1980
- }
1981
- /**
1982
- * Re-send all active subscriptions to the backend after a reconnect.
1983
- * The server wipes subscription state when a client disconnects, so
1984
- * we need to re-register everything to resume receiving updates.
1985
- */
1986
- resubscribeAll() {
1987
- console.debug(`[WS] Re-subscribing: ${this.collectionSubscriptions.size} collection(s), ${this.entitySubscriptions.size} entity(ies)`);
1988
- for (const [key, sub] of this.collectionSubscriptions.entries()) {
1989
- const oldBackendId = sub.backendSubscriptionId;
1990
- const newBackendId = `collection_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
1991
- sub.backendSubscriptionId = newBackendId;
1992
- this.backendToCollectionKey.delete(oldBackendId);
1993
- this.backendToCollectionKey.set(newBackendId, key);
1994
- this.sendMessage({
1995
- type: "subscribe_collection",
1996
- payload: {
1997
- ...sub.props,
1998
- subscriptionId: newBackendId
1999
- }
2000
- }).catch((error) => {
2001
- console.error("[WS] Failed to re-subscribe collection:", key, error);
2002
- });
2003
- }
2004
- for (const [key, sub] of this.entitySubscriptions.entries()) {
2005
- const oldBackendId = sub.backendSubscriptionId;
2006
- const newBackendId = `entity_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
2007
- sub.backendSubscriptionId = newBackendId;
2008
- this.backendToEntityKey.delete(oldBackendId);
2009
- this.backendToEntityKey.set(newBackendId, key);
2010
- this.sendMessage({
2011
- type: "subscribe_entity",
2012
- payload: {
2013
- ...sub.props,
2014
- subscriptionId: newBackendId
2015
- }
2016
- }).catch((error) => {
2017
- console.error("[WS] Failed to re-subscribe entity:", key, error);
2018
- });
2019
- }
2020
- }
2021
- createCollectionSubscriptionKey(props) {
2022
- const key = {
2023
- path: props.path,
2024
- filter: props.filter,
2025
- limit: props.limit,
2026
- startAfter: props.startAfter,
2027
- orderBy: props.orderBy,
2028
- order: props.order,
2029
- searchString: props.searchString,
2030
- collection: props.collection?.name
2031
- };
2032
- return JSON.stringify(key, (_, value) => {
2033
- if (value && typeof value === "object" && !Array.isArray(value)) return Object.keys(value).sort().reduce((sorted, k) => {
2034
- sorted[k] = value[k];
2035
- return sorted;
2036
- }, {});
2037
- return value;
2038
- });
2039
- }
2040
- createEntitySubscriptionKey(props) {
2041
- return `${props.path}|${props.entityId}`;
2042
- }
2043
- };
2044
- //#endregion
2045
- //#region src/index.ts
2046
- /**
2047
- * Derive a WebSocket URL from an HTTP base URL.
2048
- * `http://` → `ws://`, `https://` → `wss://`.
2049
- */
2050
- function deriveWebSocketUrl(baseUrl) {
2051
- if (typeof window !== "undefined") {
2052
- let absoluteUrl = "";
2053
- if (!baseUrl) absoluteUrl = window.location.origin;
2054
- else if (/^https?:\/\//i.test(baseUrl) || /^wss?:\/\//i.test(baseUrl)) absoluteUrl = baseUrl;
2055
- else try {
2056
- absoluteUrl = new URL(baseUrl, window.location.href).origin;
2057
- } catch {
2058
- absoluteUrl = window.location.origin;
2059
- }
2060
- const protocol = absoluteUrl.startsWith("https:") || absoluteUrl.startsWith("wss:") ? "wss:" : "ws:";
2061
- return absoluteUrl.replace(/^https?:\/\//i, `${protocol}//`).replace(/^wss?:\/\//i, `${protocol}//`).replace(/\/$/, "");
2062
- }
2063
- if (!baseUrl) return "";
2064
- if (!/^https?:\/\//i.test(baseUrl) && !/^wss?:\/\//i.test(baseUrl)) return "";
2065
- return baseUrl.replace(/^https?:\/\//i, (match) => match.toLowerCase() === "https://" ? "wss://" : "ws://").replace(/\/$/, "");
2066
- }
2067
- function createRebaseClient(options) {
2068
- const transport = createTransport(options);
2069
- const auth = createAuth(transport, options.auth);
2070
- const admin = createAdmin(transport, options.admin);
2071
- const cron = createCron(transport, options.cron);
2072
- const apiKeys = createApiKeys(transport, options.apiKeys);
2073
- const storage = createStorage(transport);
2074
- const functions = createFunctionsClient(transport);
2075
- const createStorageSource = (storageId) => storageId === _rebasepro_types.DEFAULT_STORAGE_SOURCE_KEY ? storage : createStorage(transport, storageId);
2076
- const storageRegistry = new ClientStorageSourceRegistry();
2077
- storageRegistry.register(_rebasepro_types.DEFAULT_STORAGE_SOURCE_KEY, storage);
2078
- for (const def of options.storageSources ?? []) if (def.transport === "server" && def.key !== _rebasepro_types.DEFAULT_STORAGE_SOURCE_KEY) storageRegistry.register(def.key, createStorageSource(def.key));
2079
- let storageSourcesPromise;
2080
- const fetchStorageSources = () => {
2081
- if (storageSourcesPromise) return storageSourcesPromise;
2082
- storageSourcesPromise = transport.request("/storage/sources").then((res) => {
2083
- const defs = res.data ?? [];
2084
- for (const def of defs) if (def.transport === "server" && def.key !== _rebasepro_types.DEFAULT_STORAGE_SOURCE_KEY && !storageRegistry.has(def.key)) storageRegistry.register(def.key, createStorageSource(def.key));
2085
- return defs;
2086
- }).catch((e) => {
2087
- storageSourcesPromise = void 0;
2088
- throw e;
2089
- });
2090
- return storageSourcesPromise;
2091
- };
2092
- const resolvedWsUrl = options.websocketUrl ?? deriveWebSocketUrl(options.baseUrl);
2093
- let ws;
2094
- if (resolvedWsUrl) {
2095
- ws = new RebaseWebSocketClient({
2096
- websocketUrl: resolvedWsUrl,
2097
- getAuthToken: async () => {
2098
- let session = auth.getSession();
2099
- if (session && session.expiresAt <= Date.now() + 1e4) try {
2100
- session = await auth.refreshSession();
2101
- } catch (e) {}
2102
- return session?.accessToken || options.token || "";
2103
- },
2104
- onUnauthorized: options.onUnauthorized || (async () => {
2105
- try {
2106
- await auth.refreshSession();
2107
- return true;
2108
- } catch (e) {
2109
- return false;
2110
- }
2111
- })
2112
- });
2113
- auth.onAuthStateChange((event, session) => {
2114
- if (!ws) return;
2115
- if (event === "SIGNED_OUT") ws.disconnect();
2116
- else if (event === "SIGNED_IN" || event === "TOKEN_REFRESHED") {
2117
- if (session?.accessToken) ws.authenticate(session.accessToken).catch(console.warn);
2118
- }
2119
- });
2120
- }
2121
- if (!options.onUnauthorized) transport.setOnUnauthorized(async () => {
2122
- try {
2123
- await auth.refreshSession();
2124
- return true;
2125
- } catch (e) {
2126
- return false;
2127
- }
2128
- });
2129
- const collectionClients = /* @__PURE__ */ new Map();
2130
- function collection(slug) {
2131
- if (!collectionClients.has(slug)) collectionClients.set(slug, createCollectionClient(transport, slug, ws));
2132
- return collectionClients.get(slug);
2133
- }
2134
- const dataProxy = new Proxy({ collection }, { get(_target, prop) {
2135
- if (prop === "collection") return collection;
2136
- if (typeof prop === "symbol") return void 0;
2137
- if (typeof prop === "string" && prop !== "then" && prop !== "toJSON" && prop !== "$$typeof") {
2138
- if (options.collections && prop in options.collections) return collection(options.collections[prop]);
2139
- return collection((0, _rebasepro_utils.toSnakeCase)(prop));
2140
- }
2141
- } });
2142
- return {
2143
- auth,
2144
- admin,
2145
- cron,
2146
- apiKeys,
2147
- functions,
2148
- storage,
2149
- storageRegistry,
2150
- createStorageSource,
2151
- fetchStorageSources,
2152
- ws,
2153
- setToken: transport.setToken,
2154
- setAuthTokenGetter: transport.setAuthTokenGetter,
2155
- setOnUnauthorized: transport.setOnUnauthorized,
2156
- resolveToken: transport.resolveToken,
2157
- baseUrl: transport.baseUrl,
2158
- collection,
2159
- call: async (endpoint, payload) => {
2160
- const prefix = endpoint.startsWith("/") ? "" : "/";
2161
- const res = await transport.request(`${prefix}${endpoint}`, {
2162
- method: "POST",
2163
- body: payload ? JSON.stringify(payload) : void 0
2164
- });
2165
- return res.data ?? res;
2166
- },
2167
- data: dataProxy,
2168
- email: void 0
2169
- };
2170
- }
2171
- //#endregion
2172
- exports.ApiError = ApiError;
2173
- exports.ClientStorageSourceRegistry = ClientStorageSourceRegistry;
2174
- Object.defineProperty(exports, "QueryBuilder", {
2175
- enumerable: true,
2176
- get: function() {
2177
- return _rebasepro_common.QueryBuilder;
2178
- }
2179
- });
2180
- exports.RebaseApiError = RebaseApiError;
2181
- exports.RebaseWebSocketClient = RebaseWebSocketClient;
2182
- Object.defineProperty(exports, "and", {
2183
- enumerable: true,
2184
- get: function() {
2185
- return _rebasepro_common.and;
2186
- }
2187
- });
2188
- exports.buildQueryString = buildQueryString;
2189
- Object.defineProperty(exports, "cond", {
2190
- enumerable: true,
2191
- get: function() {
2192
- return _rebasepro_common.cond;
2193
- }
2194
- });
2195
- exports.createAdmin = createAdmin;
2196
- exports.createApiKeys = createApiKeys;
2197
- exports.createAuth = createAuth;
2198
- exports.createCollectionClient = createCollectionClient;
2199
- exports.createCookieStorage = createCookieStorage;
2200
- exports.createCron = createCron;
2201
- exports.createFunctionsClient = createFunctionsClient;
2202
- exports.createMemoryStorage = createMemoryStorage;
2203
- exports.createRebaseClient = createRebaseClient;
2204
- exports.createStorage = createStorage;
2205
- exports.createTransport = createTransport;
2206
- Object.defineProperty(exports, "or", {
2207
- enumerable: true,
2208
- get: function() {
2209
- return _rebasepro_common.or;
2210
- }
2211
- });
2212
- exports.rebaseReviver = rebaseReviver;
2213
- });
2214
-
2215
- //# sourceMappingURL=index.umd.js.map