@rebasepro/client 0.26.0 → 0.28.0
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/admin.d.ts +21 -1
- package/dist/apple-sign-in.d.ts +59 -0
- package/dist/auth.d.ts +55 -10
- package/dist/exports-contract.types.d.ts +4 -1
- package/dist/index.d.ts +19 -8
- package/dist/index.es.js +491 -64
- package/dist/index.es.js.map +1 -1
- package/dist/{offline-AvuEcg7u.js → offline-BjJdcVBb.js} +32 -4
- package/dist/offline-BjJdcVBb.js.map +1 -0
- package/dist/{offline-store-BhYXViha.js → offline-store-Cxhh99Q-.js} +40 -6
- package/dist/offline-store-Cxhh99Q-.js.map +1 -0
- package/dist/offline.d.ts +11 -0
- package/dist/realtime-channel.d.ts +27 -0
- package/dist/storage-contract.types.d.ts +16 -0
- package/dist/storage.d.ts +4 -2
- package/dist/transport.d.ts +18 -1
- package/dist/websocket.d.ts +28 -0
- package/package.json +4 -4
- package/dist/offline-AvuEcg7u.js.map +0 -1
- package/dist/offline-store-BhYXViha.js.map +0 -1
package/dist/index.es.js
CHANGED
|
@@ -1,7 +1,119 @@
|
|
|
1
|
-
import { c as invalidBulkBody, d as RebaseApiError, h as parseRebaseJson, i as isOfflineError, l as SDKQueryBuilder, m as defaultCodeForStatus, n as MemoryOfflineStore, o as createCollectionClient, p as createTransport, s as etagOf, u as RebaseClientError } from "./offline-store-
|
|
1
|
+
import { c as invalidBulkBody, d as RebaseApiError, h as parseRebaseJson, i as isOfflineError, l as SDKQueryBuilder, m as defaultCodeForStatus, n as MemoryOfflineStore, o as createCollectionClient, p as createTransport, s as etagOf, u as RebaseClientError } from "./offline-store-Cxhh99Q-.js";
|
|
2
2
|
import { DEFAULT_STORAGE_SOURCE_KEY, PUBLIC_STORAGE_PREFIX, RebaseApiError as RebaseApiError$1, RebaseClientError as RebaseClientError$1, STORAGE_REFERENCE_SCHEME, isPublicStoragePath, isStorageReference, isUnsupported, parseStorageReference, resolveStorageReferences, simulationHeaders, storageObjectPath, storageReference, storageReferencesForDownloadUrls, storageTargetOfDownloadUrl, storageTargetsInText } from "@rebasepro/types";
|
|
3
3
|
import { COMPOSITE_ID_SEPARATOR, DOWNLOAD_URL_CONCURRENCY, RESUMABLE_UPLOAD_THRESHOLD, RebasePaginationError, and, buildCompositeId, cond, createBatchLoader, createConcurrencyLimit, createDownloadUrlCache, not, or, warnDeprecated, withETag } from "@rebasepro/common";
|
|
4
4
|
import { toSnakeCase, unref } from "@rebasepro/utils";
|
|
5
|
+
//#region src/apple-sign-in.ts
|
|
6
|
+
/**
|
|
7
|
+
* The browser half of Sign in with Apple.
|
|
8
|
+
*
|
|
9
|
+
* Apple is the one provider a single-page app cannot take through the usual
|
|
10
|
+
* redirect: asking for the `name` or `email` scope obliges
|
|
11
|
+
* `response_mode=form_post`, so Apple answers with a cross-site POST to the
|
|
12
|
+
* redirect URI — a request a static page never sees. Apple's own JS SDK has a
|
|
13
|
+
* popup mode that hands the answer back to the opening page with
|
|
14
|
+
* `postMessage` instead, and that is what this uses. The redirect URI still
|
|
15
|
+
* has to be listed under the Services ID's Return URLs (HTTPS, no
|
|
16
|
+
* `localhost`), because Apple matches it and the token exchange repeats it.
|
|
17
|
+
*
|
|
18
|
+
* `state` is generated and checked here, which is what binds the code that
|
|
19
|
+
* comes back to the click that started it.
|
|
20
|
+
*/
|
|
21
|
+
/** Apple's JS SDK, the only way into its popup mode. */
|
|
22
|
+
var APPLE_JS_SDK_URL = "https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleauth.js";
|
|
23
|
+
/** Apple's popup answers with `{ error }` when the visitor backs out. */
|
|
24
|
+
var APPLE_CANCELLATIONS = /* @__PURE__ */ new Set(["popup_closed_by_user", "user_cancelled_authorize"]);
|
|
25
|
+
var sdkLoad = null;
|
|
26
|
+
function appleIdGlobal() {
|
|
27
|
+
return globalThis.AppleID;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Load Apple's SDK once per page. A failed load is forgotten, so a retry tries
|
|
31
|
+
* again. A tag someone else added and that has not finished yet is not waited
|
|
32
|
+
* on — it may already have failed, and its events would never come — so a
|
|
33
|
+
* second, cached copy is added instead, which is harmless.
|
|
34
|
+
*/
|
|
35
|
+
function loadAppleSdk() {
|
|
36
|
+
const loaded = appleIdGlobal();
|
|
37
|
+
if (loaded) return Promise.resolve(loaded);
|
|
38
|
+
if (sdkLoad) return sdkLoad;
|
|
39
|
+
sdkLoad = new Promise((resolve, reject) => {
|
|
40
|
+
const script = document.createElement("script");
|
|
41
|
+
script.src = APPLE_JS_SDK_URL;
|
|
42
|
+
script.async = true;
|
|
43
|
+
script.onload = () => {
|
|
44
|
+
const apple = appleIdGlobal();
|
|
45
|
+
if (apple) resolve(apple);
|
|
46
|
+
else reject(/* @__PURE__ */ new Error("Apple's sign-in script loaded without defining AppleID"));
|
|
47
|
+
};
|
|
48
|
+
script.onerror = () => reject(/* @__PURE__ */ new Error("Apple's sign-in script could not be loaded"));
|
|
49
|
+
document.head.appendChild(script);
|
|
50
|
+
}).catch((err) => {
|
|
51
|
+
sdkLoad = null;
|
|
52
|
+
throw new RebaseClientError("Sign in with Apple could not be loaded. Check your connection or any script blockers, then try again.", {
|
|
53
|
+
code: "APPLE_SIGN_IN_UNAVAILABLE",
|
|
54
|
+
cause: err
|
|
55
|
+
});
|
|
56
|
+
});
|
|
57
|
+
return sdkLoad;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Start loading Apple's SDK ahead of the click. Worth calling when the sign-in
|
|
61
|
+
* button mounts: with the SDK already on the page, the popup opens in the same
|
|
62
|
+
* task as the click, and Safari blocks a popup that opens later than that.
|
|
63
|
+
*/
|
|
64
|
+
async function preloadAppleSignIn() {
|
|
65
|
+
if (typeof document === "undefined") return;
|
|
66
|
+
await loadAppleSdk();
|
|
67
|
+
}
|
|
68
|
+
function randomState() {
|
|
69
|
+
const bytes = /* @__PURE__ */ new Uint8Array(16);
|
|
70
|
+
crypto.getRandomValues(bytes);
|
|
71
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Open Apple's sign-in popup and return the authorization code, without
|
|
75
|
+
* spending it. Call it from a click handler: browsers block a popup that no
|
|
76
|
+
* gesture opened. Call {@link preloadAppleSignIn} first (on mount) so the
|
|
77
|
+
* popup does not wait on a script download.
|
|
78
|
+
*
|
|
79
|
+
* Throws a `RebaseClientError` whose `code` is `APPLE_SIGN_IN_CANCELLED` when
|
|
80
|
+
* the visitor closes the popup or declines, `APPLE_SIGN_IN_UNAVAILABLE` when
|
|
81
|
+
* Apple's script cannot load or this is not a browser, and
|
|
82
|
+
* `APPLE_SIGN_IN_FAILED` otherwise.
|
|
83
|
+
*/
|
|
84
|
+
async function requestAppleAuthorization(request) {
|
|
85
|
+
if (typeof window === "undefined" || typeof document === "undefined") throw new RebaseClientError("Sign in with Apple's popup needs a browser. A native app gets the code from ASAuthorizationController and passes it to signInWithApple({ code, bundleId }).", { code: "APPLE_SIGN_IN_UNAVAILABLE" });
|
|
86
|
+
const apple = appleIdGlobal() ?? await loadAppleSdk();
|
|
87
|
+
const redirectUri = request.redirectUri ?? `${window.location.origin}/`;
|
|
88
|
+
const state = randomState();
|
|
89
|
+
apple.auth.init({
|
|
90
|
+
clientId: request.clientId,
|
|
91
|
+
scope: "name email",
|
|
92
|
+
redirectURI: redirectUri,
|
|
93
|
+
state,
|
|
94
|
+
usePopup: true
|
|
95
|
+
});
|
|
96
|
+
let response;
|
|
97
|
+
try {
|
|
98
|
+
response = await apple.auth.signIn();
|
|
99
|
+
} catch (err) {
|
|
100
|
+
const reason = typeof err === "object" && err !== null && "error" in err && typeof err.error === "string" ? err.error : void 0;
|
|
101
|
+
if (reason && APPLE_CANCELLATIONS.has(reason)) throw new RebaseClientError("Sign in with Apple was cancelled.", { code: "APPLE_SIGN_IN_CANCELLED" });
|
|
102
|
+
throw new RebaseClientError(reason ? `Sign in with Apple failed: ${reason}` : "Sign in with Apple failed. Please try again.", {
|
|
103
|
+
code: "APPLE_SIGN_IN_FAILED",
|
|
104
|
+
cause: err
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
const authorization = response.authorization;
|
|
108
|
+
if (!authorization?.code) throw new RebaseClientError("Apple returned no authorization code.", { code: "APPLE_SIGN_IN_FAILED" });
|
|
109
|
+
if (authorization.state !== state) throw new RebaseClientError("This Apple sign-in could not be verified as one started on this page. Please try again.", { code: "APPLE_SIGN_IN_FAILED" });
|
|
110
|
+
return {
|
|
111
|
+
code: authorization.code,
|
|
112
|
+
redirectUri,
|
|
113
|
+
...response.user?.name ? { user: { name: response.user.name } } : {}
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
//#endregion
|
|
5
117
|
//#region src/auth.ts
|
|
6
118
|
/** Map a raw user object from an auth response (`/login`, `/refresh`, `/me`) to a `User`. */
|
|
7
119
|
function mapRawUser(raw) {
|
|
@@ -51,13 +163,31 @@ function detectStorage() {
|
|
|
51
163
|
} catch (e) {}
|
|
52
164
|
return createMemoryStorage();
|
|
53
165
|
}
|
|
166
|
+
/**
|
|
167
|
+
* The flow mode a client uses when `authFlowMode` is not set.
|
|
168
|
+
*
|
|
169
|
+
* Cookie in a browser. A backend run by the Rebase runtime always keeps the
|
|
170
|
+
* refresh token in a cookie and answers the body's with `""`, so a browser
|
|
171
|
+
* client defaulting to json held nothing to renew with, and was signed out
|
|
172
|
+
* without a word once its access token expired, about an hour after sign-in.
|
|
173
|
+
*
|
|
174
|
+
* Json off the browser (Node, a worker, React Native), where there is no
|
|
175
|
+
* cookie jar to keep it in — and in a browser that passes its own `storage`,
|
|
176
|
+
* which says where the session is to be kept: a second client on the page
|
|
177
|
+
* that keeps its own sign-in apart from the page's cookie. In cookie mode
|
|
178
|
+
* nothing would be kept there, and every reload would lose that sign-in.
|
|
179
|
+
*/
|
|
180
|
+
function resolveAuthFlowMode(options) {
|
|
181
|
+
if (options?.authFlowMode) return options.authFlowMode;
|
|
182
|
+
return typeof document !== "undefined" && !options?.storage ? "cookie" : "json";
|
|
183
|
+
}
|
|
54
184
|
function createAuth(transport, options) {
|
|
55
185
|
const opts = options || {};
|
|
56
186
|
const storage = opts.storage || detectStorage();
|
|
57
187
|
const authPath = opts.authPath || "/auth";
|
|
58
188
|
const autoRefresh = opts.autoRefresh !== false;
|
|
59
189
|
const persistSession = opts.persistSession !== false;
|
|
60
|
-
const authFlowMode = opts
|
|
190
|
+
const authFlowMode = resolveAuthFlowMode(opts);
|
|
61
191
|
const STORAGE_KEY = "rebase_auth";
|
|
62
192
|
const REFRESH_BUFFER_MS = 12e4;
|
|
63
193
|
/**
|
|
@@ -129,6 +259,25 @@ function createAuth(transport, options) {
|
|
|
129
259
|
if (authFlowMode === "cookie") return "";
|
|
130
260
|
return received || currentSession?.refreshToken || "";
|
|
131
261
|
}
|
|
262
|
+
let flowMismatchReported = false;
|
|
263
|
+
/**
|
|
264
|
+
* Say so at sign-in, once, when the server's answer shows this client
|
|
265
|
+
* cannot renew the session it is starting.
|
|
266
|
+
*
|
|
267
|
+
* A server with `cookieAuth` answers `refreshToken: ""` and puts the token
|
|
268
|
+
* in the cookie; one without it puts the token in the body. A client in
|
|
269
|
+
* the other mode holds nothing it can renew with, and finds out when the
|
|
270
|
+
* access token expires — in json mode by dropping the session without a
|
|
271
|
+
* word. The answer to the sign-in is the first moment it is known.
|
|
272
|
+
*/
|
|
273
|
+
function reportFlowMismatch(received, expiresAt) {
|
|
274
|
+
if (flowMismatchReported || received === void 0) return;
|
|
275
|
+
const serverUsesCookie = received === "";
|
|
276
|
+
if (serverUsesCookie === (authFlowMode === "cookie")) return;
|
|
277
|
+
flowMismatchReported = true;
|
|
278
|
+
const ends = Number.isFinite(expiresAt) ? `in about ${Math.max(1, Math.round((expiresAt - Date.now()) / 6e4))} minutes` : "when its access token expires";
|
|
279
|
+
console.error(serverUsesCookie ? `[rebase] This server keeps the refresh token in an HttpOnly cookie (its \`auth.cookieAuth\`), but this client is in json mode and was handed none, so the session it just started cannot be renewed and ends ${ends}. Create the client with \`auth: { authFlowMode: "cookie" }\`.` : `[rebase] This server returned the refresh token in the response body, so it does not use \`auth.cookieAuth\`, and this client, in cookie mode, cannot renew the session it just started: it ends ${ends}. Turn on \`auth.cookieAuth\` on the server, or create the client with \`auth: { authFlowMode: "json" }\`.`);
|
|
280
|
+
}
|
|
132
281
|
/**
|
|
133
282
|
* Whether the server refused a refresh as malformed: a 400, which says the
|
|
134
283
|
* request this client built is not one that server accepts.
|
|
@@ -267,6 +416,15 @@ function createAuth(transport, options) {
|
|
|
267
416
|
*/
|
|
268
417
|
const SPENT_TOKEN_MARGIN_MS = 1e4;
|
|
269
418
|
/**
|
|
419
|
+
* Whether a request about to carry this session's token should first get a
|
|
420
|
+
* fresh one: the token has expired or is about to, and can be renewed.
|
|
421
|
+
*/
|
|
422
|
+
function needsFreshToken(session) {
|
|
423
|
+
if (!Number.isFinite(session.expiresAt)) return false;
|
|
424
|
+
if (session.expiresAt > Date.now() + SPENT_TOKEN_MARGIN_MS) return false;
|
|
425
|
+
return authFlowMode === "cookie" || !!session.refreshToken;
|
|
426
|
+
}
|
|
427
|
+
/**
|
|
270
428
|
* The transport's {@link TokenRefresher}: whether a request should wait for
|
|
271
429
|
* a fresher token than the one held, and which token to send when it does.
|
|
272
430
|
*
|
|
@@ -282,23 +440,22 @@ function createAuth(transport, options) {
|
|
|
282
440
|
* round trip of latency each.
|
|
283
441
|
*
|
|
284
442
|
* The refresh is {@link refreshSession}, so a burst of requests shares one
|
|
285
|
-
* (the one started at load included). A refresh that fails
|
|
286
|
-
* token
|
|
287
|
-
* exactly what it always did. One
|
|
288
|
-
*
|
|
289
|
-
*
|
|
290
|
-
* the account
|
|
291
|
-
*
|
|
443
|
+
* (the one started at load included). A refresh that fails without the
|
|
444
|
+
* refresh token being refused hands back the token the request would have
|
|
445
|
+
* carried anyway: the 401 path then does exactly what it always did. One
|
|
446
|
+
* refused, or one whose session ended while it ran, hands back nothing, so
|
|
447
|
+
* the transport sends what it holds now — no token after a sign-out or a
|
|
448
|
+
* refused restore, the new account's after a sign-in — and never the
|
|
449
|
+
* token of the account that has gone. The realtime socket authenticates
|
|
450
|
+
* through this same path.
|
|
292
451
|
*/
|
|
293
452
|
function tokenForRequest() {
|
|
294
453
|
if (refreshOwnRequests > 0) return void 0;
|
|
295
454
|
const session = currentSession;
|
|
296
455
|
if (!session) return cookieRestore?.then(() => void 0);
|
|
297
|
-
if (!
|
|
298
|
-
if (session.expiresAt > Date.now() + SPENT_TOKEN_MARGIN_MS) return void 0;
|
|
299
|
-
if (authFlowMode !== "cookie" && !session.refreshToken) return void 0;
|
|
456
|
+
if (!needsFreshToken(session)) return void 0;
|
|
300
457
|
const epoch = sessionEpoch;
|
|
301
|
-
return refreshSession().then((fresh) => epoch === sessionEpoch ? fresh.accessToken : void 0, () => epoch === sessionEpoch ? session.accessToken : void 0);
|
|
458
|
+
return refreshSession().then((fresh) => epoch === sessionEpoch ? fresh.accessToken : void 0, (err) => epoch === sessionEpoch && !isFatalRefreshError(err) ? session.accessToken : void 0);
|
|
302
459
|
}
|
|
303
460
|
transport.setTokenRefresher?.(tokenForRequest);
|
|
304
461
|
async function attemptScheduledRefresh(attempt) {
|
|
@@ -368,6 +525,7 @@ function createAuth(transport, options) {
|
|
|
368
525
|
}
|
|
369
526
|
function handleAuthResponse(data, event) {
|
|
370
527
|
sessionEpoch++;
|
|
528
|
+
reportFlowMismatch(data.tokens.refreshToken, data.tokens.accessTokenExpiresAt);
|
|
371
529
|
const user = mapRawUser(data.user);
|
|
372
530
|
const session = {
|
|
373
531
|
accessToken: data.tokens.accessToken,
|
|
@@ -505,13 +663,55 @@ function createAuth(transport, options) {
|
|
|
505
663
|
redirectUri
|
|
506
664
|
});
|
|
507
665
|
}
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
666
|
+
/**
|
|
667
|
+
* Sign in with an Apple authorization code.
|
|
668
|
+
*
|
|
669
|
+
* - Web: `signInWithApple({ code, redirectUri, user })` — or let
|
|
670
|
+
* {@link signInWithApplePopup} obtain the code for you.
|
|
671
|
+
* - Native (iOS, iPadOS, macOS): `signInWithApple({ code, bundleId, user })`
|
|
672
|
+
* with the `authorizationCode` from `ASAuthorizationController`. The
|
|
673
|
+
* bundle id must be in the backend's `APPLE_BUNDLE_IDS`.
|
|
674
|
+
*
|
|
675
|
+
* `user` carries the name Apple reports on the first authorization only.
|
|
676
|
+
* The positional `(code, redirectUri, user)` form is the web call, kept for
|
|
677
|
+
* existing callers.
|
|
678
|
+
*/
|
|
679
|
+
async function signInWithApple(payloadOrCode, redirectUri, user) {
|
|
680
|
+
const payload = typeof payloadOrCode === "string" ? {
|
|
681
|
+
code: payloadOrCode,
|
|
511
682
|
redirectUri,
|
|
512
683
|
user
|
|
684
|
+
} : payloadOrCode;
|
|
685
|
+
return signInWithOAuth("apple", {
|
|
686
|
+
code: payload.code,
|
|
687
|
+
...payload.redirectUri !== void 0 ? { redirectUri: payload.redirectUri } : {},
|
|
688
|
+
...payload.bundleId !== void 0 ? { bundleId: payload.bundleId } : {},
|
|
689
|
+
...payload.user?.name ? { user: { name: payload.user.name } } : {}
|
|
513
690
|
});
|
|
514
691
|
}
|
|
692
|
+
/**
|
|
693
|
+
* Sign in with Apple in a browser: opens Apple's popup, then spends the
|
|
694
|
+
* code it returns. Call it from a click handler, since browsers block a
|
|
695
|
+
* popup that no gesture opened.
|
|
696
|
+
*
|
|
697
|
+
* `clientId` defaults to the Services ID the backend publishes in
|
|
698
|
+
* `GET /auth/config` — but pass it when you can: fetching it first delays
|
|
699
|
+
* the popup past the click, which Safari blocks. Call
|
|
700
|
+
* `preloadAppleSignIn()` on mount for the same reason. `redirectUri`
|
|
701
|
+
* defaults to this page's origin plus `/`; either way it must be a Return
|
|
702
|
+
* URL registered on the Services ID.
|
|
703
|
+
*
|
|
704
|
+
* A closed popup rejects with a `RebaseClientError` whose `code` is
|
|
705
|
+
* `APPLE_SIGN_IN_CANCELLED` — an answer, not a failure.
|
|
706
|
+
*/
|
|
707
|
+
async function signInWithApplePopup(options = {}) {
|
|
708
|
+
const clientId = options.clientId ?? (await getAuthConfig()).providerClientIds?.apple;
|
|
709
|
+
if (!clientId) throw new RebaseClientError$1("Sign in with Apple needs a Services ID: set APPLE_CLIENT_ID on the backend, or pass clientId.", { code: "APPLE_SIGN_IN_UNAVAILABLE" });
|
|
710
|
+
return signInWithApple(await requestAppleAuthorization({
|
|
711
|
+
clientId,
|
|
712
|
+
redirectUri: options.redirectUri
|
|
713
|
+
}));
|
|
714
|
+
}
|
|
515
715
|
async function signInWithFacebook(code, redirectUri) {
|
|
516
716
|
return signInWithOAuth("facebook", {
|
|
517
717
|
code,
|
|
@@ -822,12 +1022,21 @@ function createAuth(transport, options) {
|
|
|
822
1022
|
* Throws `IDENTITY_ALREADY_LINKED` (409) if that provider identity is
|
|
823
1023
|
* attached to a different user. Succeeds idempotently (`alreadyLinked:
|
|
824
1024
|
* true`) if it is already attached to the current one.
|
|
1025
|
+
*
|
|
1026
|
+
* From an anonymous session the link makes the guest an account: the
|
|
1027
|
+
* account's session replaces the guest's and `USER_UPDATED` is emitted.
|
|
825
1028
|
*/
|
|
826
1029
|
async function linkProvider(providerId, payload) {
|
|
827
|
-
|
|
1030
|
+
const result = await transport.request(authPath + "/link/" + providerId, {
|
|
828
1031
|
method: "POST",
|
|
829
|
-
body: JSON.stringify(payload)
|
|
1032
|
+
body: JSON.stringify(payload),
|
|
1033
|
+
credentials: authFlowMode === "cookie" ? "include" : void 0
|
|
830
1034
|
});
|
|
1035
|
+
if (result.tokens && result.user) handleAuthResponse({
|
|
1036
|
+
tokens: result.tokens,
|
|
1037
|
+
user: result.user
|
|
1038
|
+
}, "USER_UPDATED");
|
|
1039
|
+
return result;
|
|
831
1040
|
}
|
|
832
1041
|
async function sendVerificationEmail() {
|
|
833
1042
|
return transport.request(authPath + "/send-verification", { method: "POST" });
|
|
@@ -1052,7 +1261,8 @@ function createAuth(transport, options) {
|
|
|
1052
1261
|
body: JSON.stringify({
|
|
1053
1262
|
email,
|
|
1054
1263
|
password
|
|
1055
|
-
})
|
|
1264
|
+
}),
|
|
1265
|
+
credentials: authFlowMode === "cookie" ? "include" : void 0
|
|
1056
1266
|
}), "USER_UPDATED");
|
|
1057
1267
|
return {
|
|
1058
1268
|
user: session.user,
|
|
@@ -1154,7 +1364,8 @@ function createAuth(transport, options) {
|
|
|
1154
1364
|
});
|
|
1155
1365
|
const session = handleAuthResponse(options?.mfaToken ? await withPendingToken("/mfa/challenge/verify", payload, options.mfaToken) : await transport.request(authPath + "/mfa/challenge/verify", {
|
|
1156
1366
|
method: "POST",
|
|
1157
|
-
body: payload
|
|
1367
|
+
body: payload,
|
|
1368
|
+
credentials: authFlowMode === "cookie" ? "include" : void 0
|
|
1158
1369
|
}), "SIGNED_IN");
|
|
1159
1370
|
return {
|
|
1160
1371
|
user: session.user,
|
|
@@ -1208,9 +1419,49 @@ function createAuth(transport, options) {
|
|
|
1208
1419
|
if (!res.ok) throwApiError(res.status, body, res.statusText);
|
|
1209
1420
|
return body;
|
|
1210
1421
|
}
|
|
1422
|
+
/**
|
|
1423
|
+
* The session as it is now, or `null`.
|
|
1424
|
+
*
|
|
1425
|
+
* A snapshot: every renewal of the access token (about hourly) replaces
|
|
1426
|
+
* the session with a new object, so one kept from an earlier call carries
|
|
1427
|
+
* a token the server refuses once it expires. Read it when you need it.
|
|
1428
|
+
* For a token to send, use {@link getAccessToken}.
|
|
1429
|
+
*/
|
|
1211
1430
|
function getSession() {
|
|
1212
1431
|
return currentSession;
|
|
1213
1432
|
}
|
|
1433
|
+
/**
|
|
1434
|
+
* The access token to put on a request of your own — a route outside
|
|
1435
|
+
* Rebase, a header for an upload — renewed first when it has expired or
|
|
1436
|
+
* is about to. `null` when no one is signed in.
|
|
1437
|
+
*
|
|
1438
|
+
* Ask for it for each request rather than keeping it: every renewal
|
|
1439
|
+
* replaces it. A Rebase function needs none of this, since
|
|
1440
|
+
* `functions.invoke` renews before sending and retries once on a 401.
|
|
1441
|
+
*
|
|
1442
|
+
* Waits for the session restored on load, and calls made together share
|
|
1443
|
+
* one renewal. A renewal the server refuses ends the session, as a refused
|
|
1444
|
+
* request does, and answers `null`. One that cannot reach the server
|
|
1445
|
+
* answers the token held, for the server to judge.
|
|
1446
|
+
*/
|
|
1447
|
+
async function getAccessToken() {
|
|
1448
|
+
await isInitialized;
|
|
1449
|
+
const session = currentSession;
|
|
1450
|
+
if (!session) return null;
|
|
1451
|
+
if (!needsFreshToken(session)) return session.accessToken;
|
|
1452
|
+
const epoch = sessionEpoch;
|
|
1453
|
+
try {
|
|
1454
|
+
const fresh = await refreshSession();
|
|
1455
|
+
return epoch === sessionEpoch ? fresh.accessToken : currentSession?.accessToken ?? null;
|
|
1456
|
+
} catch (err) {
|
|
1457
|
+
if (epoch !== sessionEpoch) return currentSession?.accessToken ?? null;
|
|
1458
|
+
if (isFatalRefreshError(err)) {
|
|
1459
|
+
abandonSessionLocally();
|
|
1460
|
+
return null;
|
|
1461
|
+
}
|
|
1462
|
+
return session.accessToken;
|
|
1463
|
+
}
|
|
1464
|
+
}
|
|
1214
1465
|
function onAuthStateChange(callback) {
|
|
1215
1466
|
listeners.add(callback);
|
|
1216
1467
|
return () => listeners.delete(callback);
|
|
@@ -1261,6 +1512,7 @@ function createAuth(transport, options) {
|
|
|
1261
1512
|
signInWithGitHub,
|
|
1262
1513
|
signInWithMicrosoft,
|
|
1263
1514
|
signInWithApple,
|
|
1515
|
+
signInWithApplePopup,
|
|
1264
1516
|
signInWithFacebook,
|
|
1265
1517
|
signInWithTwitter,
|
|
1266
1518
|
signInWithDiscord,
|
|
@@ -1295,8 +1547,9 @@ function createAuth(transport, options) {
|
|
|
1295
1547
|
revokeAllSessions,
|
|
1296
1548
|
getAuthConfig,
|
|
1297
1549
|
getSession,
|
|
1550
|
+
getAccessToken,
|
|
1298
1551
|
onAuthStateChange,
|
|
1299
|
-
canRestoreSession: () => persistSession
|
|
1552
|
+
canRestoreSession: () => persistSession,
|
|
1300
1553
|
isInitialized: () => isInitialized,
|
|
1301
1554
|
/**
|
|
1302
1555
|
* How restoring the session on load ended — see
|
|
@@ -1346,6 +1599,7 @@ function createCookieStorage(options = {}) {
|
|
|
1346
1599
|
}
|
|
1347
1600
|
//#endregion
|
|
1348
1601
|
//#region src/admin.ts
|
|
1602
|
+
var isoDate = (date) => date instanceof Date ? date.toISOString() : date;
|
|
1349
1603
|
function createAdmin(transport, options) {
|
|
1350
1604
|
const adminPath = (options || {}).adminPath || "/admin";
|
|
1351
1605
|
/**
|
|
@@ -1409,6 +1663,29 @@ function createAdmin(transport, options) {
|
|
|
1409
1663
|
async function resetMfa(userId) {
|
|
1410
1664
|
return transport.request(adminPath + "/users/" + encodeURIComponent(userId) + "/mfa", { method: "DELETE" });
|
|
1411
1665
|
}
|
|
1666
|
+
/** One page of guests, the ones last seen longest ago first, with the `total` matching. */
|
|
1667
|
+
async function listGuests(options) {
|
|
1668
|
+
const params = new URLSearchParams();
|
|
1669
|
+
if (options?.limit !== void 0) params.set("limit", String(options.limit));
|
|
1670
|
+
if (options?.offset !== void 0) params.set("offset", String(options.offset));
|
|
1671
|
+
if (options?.lastSeenBefore !== void 0) params.set("lastSeenBefore", isoDate(options.lastSeenBefore));
|
|
1672
|
+
const qs = params.toString();
|
|
1673
|
+
return transport.request(adminPath + "/guests" + (qs ? "?" + qs : ""), { method: "GET" });
|
|
1674
|
+
}
|
|
1675
|
+
/** Delete one guest. An account is refused with `NOT_ANONYMOUS`; {@link deleteUser} deletes those. */
|
|
1676
|
+
async function deleteGuest(userId) {
|
|
1677
|
+
return transport.request(adminPath + "/guests/" + encodeURIComponent(userId), { method: "DELETE" });
|
|
1678
|
+
}
|
|
1679
|
+
/**
|
|
1680
|
+
* Delete one batch of the guests last seen before a date. It can only ever
|
|
1681
|
+
* touch guests. Repeat it while `remaining` is not 0, passing how many have
|
|
1682
|
+
* been skipped so far as `offset`.
|
|
1683
|
+
*/
|
|
1684
|
+
async function deleteGuests(options) {
|
|
1685
|
+
const params = new URLSearchParams({ lastSeenBefore: isoDate(options.lastSeenBefore) });
|
|
1686
|
+
if (options.offset) params.set("offset", String(options.offset));
|
|
1687
|
+
return transport.request(adminPath + "/guests?" + params.toString(), { method: "DELETE" });
|
|
1688
|
+
}
|
|
1412
1689
|
async function resetPassword(userId, options) {
|
|
1413
1690
|
return transport.request(adminPath + "/users/" + encodeURIComponent(userId) + "/reset-password", {
|
|
1414
1691
|
method: "POST",
|
|
@@ -1429,6 +1706,9 @@ function createAdmin(transport, options) {
|
|
|
1429
1706
|
updateUser,
|
|
1430
1707
|
deleteUser,
|
|
1431
1708
|
resetMfa,
|
|
1709
|
+
listGuests,
|
|
1710
|
+
deleteGuest,
|
|
1711
|
+
deleteGuests,
|
|
1432
1712
|
resetPassword,
|
|
1433
1713
|
listRoles,
|
|
1434
1714
|
bootstrap
|
|
@@ -1694,8 +1974,8 @@ function createFunctionsClient(transport) {
|
|
|
1694
1974
|
code: "INVALID_FUNCTION_NAME",
|
|
1695
1975
|
details: { name }
|
|
1696
1976
|
});
|
|
1697
|
-
const pathPart = (options?.path ?? "").split(/[?#]/)[0];
|
|
1698
|
-
if (isDotSegment(name) || pathPart.split(
|
|
1977
|
+
const pathPart = (options?.path ?? "").replace(/[\t\n\r]/g, "").split(/[?#]/)[0];
|
|
1978
|
+
if (isDotSegment(name) || pathPart.split(/[/\\]/).some(isDotSegment)) throw new RebaseClientError$1(`Invalid function route "${name}${options?.path ? ` + ${options.path}` : ""}": a \`.\` or \`..\` segment would leave /functions/` + name + ".", {
|
|
1699
1979
|
code: "INVALID_FUNCTION_PATH",
|
|
1700
1980
|
details: {
|
|
1701
1981
|
name,
|
|
@@ -1750,9 +2030,16 @@ function createFunctionsClient(transport) {
|
|
|
1750
2030
|
* other character is encoded, including a literal `%`. Verified to round-trip
|
|
1751
2031
|
* through the server's decode for all of the above, plus `+`, accented
|
|
1752
2032
|
* characters and a trailing `%`.
|
|
2033
|
+
*
|
|
2034
|
+
* Throws `INVALID_STORAGE_KEY` for a key with a `..` segment.
|
|
1753
2035
|
*/
|
|
1754
2036
|
function encodeStorageKey(key) {
|
|
1755
|
-
|
|
2037
|
+
const segments = key.split("/");
|
|
2038
|
+
if (segments.includes("..")) throw new RebaseClientError$1(`Storage key ${JSON.stringify(key)} contains a '..' path segment. Keys must name an object directly.`, {
|
|
2039
|
+
code: "INVALID_STORAGE_KEY",
|
|
2040
|
+
details: { key }
|
|
2041
|
+
});
|
|
2042
|
+
return segments.map(encodeURIComponent).join("/");
|
|
1756
2043
|
}
|
|
1757
2044
|
/**
|
|
1758
2045
|
* The fields of an upload's form, as the resumable endpoint's
|
|
@@ -2238,15 +2525,31 @@ var SOCKET_OPT_INS = [
|
|
|
2238
2525
|
"channel_seq",
|
|
2239
2526
|
"cancel_sql"
|
|
2240
2527
|
];
|
|
2528
|
+
/**
|
|
2529
|
+
* The query parameter naming the group a socket belongs to. A platform that
|
|
2530
|
+
* routes on it sends sockets with the same value to the same instance; the
|
|
2531
|
+
* server itself never reads it.
|
|
2532
|
+
*/
|
|
2533
|
+
var SOCKET_AFFINITY_PARAM = "affinity";
|
|
2241
2534
|
/** Slack on top of two heartbeat intervals before a silent socket is given up on. */
|
|
2242
2535
|
var HEARTBEAT_GRACE_MS = 5e3;
|
|
2243
2536
|
/**
|
|
2244
|
-
* `url` with the opt-ins named on it
|
|
2245
|
-
* `URL`, which would rewrite the address
|
|
2246
|
-
* a `/`).
|
|
2537
|
+
* `url` with the opt-ins named on it, and `affinity` when there is one.
|
|
2538
|
+
* Appended rather than rebuilt through `URL`, which would rewrite the address
|
|
2539
|
+
* the caller gave (a bare origin gains a `/`).
|
|
2540
|
+
*
|
|
2541
|
+
* `affinity` replaces one already in `url`: a router takes one value, and it
|
|
2542
|
+
* may not be the last.
|
|
2247
2543
|
*/
|
|
2248
|
-
function withOptIns(url) {
|
|
2249
|
-
|
|
2544
|
+
function withOptIns(url, affinity) {
|
|
2545
|
+
const queryAt = url.indexOf("?");
|
|
2546
|
+
const address = queryAt === -1 ? url : url.slice(0, queryAt);
|
|
2547
|
+
const params = queryAt === -1 ? [] : url.slice(queryAt + 1).split("&");
|
|
2548
|
+
return `${address}?${[
|
|
2549
|
+
...affinity ? params.filter((param) => !param.startsWith(`${SOCKET_AFFINITY_PARAM}=`)) : params,
|
|
2550
|
+
...affinity ? [`${SOCKET_AFFINITY_PARAM}=${encodeURIComponent(affinity)}`] : [],
|
|
2551
|
+
`${SOCKET_OPT_IN_PARAM}=${SOCKET_OPT_INS.join(",")}`
|
|
2552
|
+
].join("&")}`;
|
|
2250
2553
|
}
|
|
2251
2554
|
/**
|
|
2252
2555
|
* Broadcast and presence frames.
|
|
@@ -2334,8 +2637,15 @@ function isCollectionUpdate(message) {
|
|
|
2334
2637
|
function isChannelMessage(message) {
|
|
2335
2638
|
return typeof message.channel === "string" && CHANNEL_FRAME_TYPES.has(message.type);
|
|
2336
2639
|
}
|
|
2640
|
+
/** The code of a channel `ERROR` frame, if it is one and carries a code. */
|
|
2641
|
+
function channelErrorCode(message) {
|
|
2642
|
+
if (message.type !== "ERROR" && message.type !== "error") return void 0;
|
|
2643
|
+
const raw = message.payload?.error;
|
|
2644
|
+
if (raw && typeof raw === "object" && "code" in raw && typeof raw.code === "string") return raw.code;
|
|
2645
|
+
}
|
|
2337
2646
|
var RebaseWebSocketClient = class {
|
|
2338
2647
|
websocketUrl;
|
|
2648
|
+
affinity;
|
|
2339
2649
|
ws = null;
|
|
2340
2650
|
/**
|
|
2341
2651
|
* Where the socket's token comes from. A client built by
|
|
@@ -2527,6 +2837,7 @@ var RebaseWebSocketClient = class {
|
|
|
2527
2837
|
}
|
|
2528
2838
|
constructor(config) {
|
|
2529
2839
|
this.websocketUrl = config.websocketUrl;
|
|
2840
|
+
this.affinity = config.affinity;
|
|
2530
2841
|
this.getAuthToken = config.getAuthToken;
|
|
2531
2842
|
this.onUnauthorized = config.onUnauthorized;
|
|
2532
2843
|
this.impersonate = config.impersonate;
|
|
@@ -2534,6 +2845,13 @@ var RebaseWebSocketClient = class {
|
|
|
2534
2845
|
this.WebSocketConstructor = config.WebSocket || (typeof WebSocket !== "undefined" ? WebSocket : void 0);
|
|
2535
2846
|
}
|
|
2536
2847
|
/**
|
|
2848
|
+
* Name the group this socket belongs to, or clear it with `null`. Read at
|
|
2849
|
+
* each dial, so a socket already open stays where it is until it redials.
|
|
2850
|
+
*/
|
|
2851
|
+
setAffinity(key) {
|
|
2852
|
+
this.affinity = key ?? void 0;
|
|
2853
|
+
}
|
|
2854
|
+
/**
|
|
2537
2855
|
* Open the socket if it is not open (or opening) already.
|
|
2538
2856
|
*
|
|
2539
2857
|
* Idempotent, synchronous, and safe to call on every operation that needs a
|
|
@@ -2637,6 +2955,55 @@ var RebaseWebSocketClient = class {
|
|
|
2637
2955
|
/**
|
|
2638
2956
|
* Authenticate the WebSocket connection
|
|
2639
2957
|
*/
|
|
2958
|
+
/**
|
|
2959
|
+
* {@link authenticate}, asked again a few times when the server could not
|
|
2960
|
+
* answer (its auth store busy, `ROLE_LOOKUP_FAILED`, a timeout) — not when
|
|
2961
|
+
* it refused the session or the socket ceiling, which a retry cannot
|
|
2962
|
+
* change. Stops as soon as `socket` is no longer this client's.
|
|
2963
|
+
*/
|
|
2964
|
+
async authenticateRetrying(token, socket) {
|
|
2965
|
+
const delays = [
|
|
2966
|
+
500,
|
|
2967
|
+
1500,
|
|
2968
|
+
3500
|
|
2969
|
+
];
|
|
2970
|
+
for (let attempt = 0;; attempt++) try {
|
|
2971
|
+
await this.authenticate(token);
|
|
2972
|
+
return;
|
|
2973
|
+
} catch (error) {
|
|
2974
|
+
if (attempt >= delays.length || this.ws !== socket || isSocketCeilingRefusal(error) || isSessionRefusal(error)) throw error;
|
|
2975
|
+
await new Promise((resolve) => setTimeout(resolve, delays[attempt]));
|
|
2976
|
+
if (this.ws !== socket) throw error;
|
|
2977
|
+
}
|
|
2978
|
+
}
|
|
2979
|
+
/** A sign-in again after a channel was refused for not being signed in, in flight. */
|
|
2980
|
+
channelAuthRecovery = null;
|
|
2981
|
+
/**
|
|
2982
|
+
* A channel frame refused `UNAUTHORIZED` while this client holds a way to
|
|
2983
|
+
* get a token: the socket is open but not signed in (an authentication that
|
|
2984
|
+
* failed on a reconnect, a token that expired). Nothing else signs it in —
|
|
2985
|
+
* channel frames expect no answer, so the refusal reaches only the channel —
|
|
2986
|
+
* and every later frame is refused the same way. Sign in again, once for
|
|
2987
|
+
* all the channels that noticed, and have them re-join.
|
|
2988
|
+
*/
|
|
2989
|
+
recoverChannelAuth() {
|
|
2990
|
+
if (this.channelAuthRecovery || !this.getAuthToken || this.isAuthenticated) return;
|
|
2991
|
+
const socket = this.ws;
|
|
2992
|
+
this.channelAuthRecovery = (async () => {
|
|
2993
|
+
try {
|
|
2994
|
+
const token = await this.getAuthToken();
|
|
2995
|
+
if (!token || !socket || this.ws !== socket) return;
|
|
2996
|
+
await this.authenticateRetrying(token, socket);
|
|
2997
|
+
if (this.ws === socket) this.emit("reconnect");
|
|
2998
|
+
} catch (error) {
|
|
2999
|
+
this.connectionDebug("Could not sign the socket in again for a channel:", error?.message || error);
|
|
3000
|
+
} finally {
|
|
3001
|
+
setTimeout(() => {
|
|
3002
|
+
this.channelAuthRecovery = null;
|
|
3003
|
+
}, 2e3);
|
|
3004
|
+
}
|
|
3005
|
+
})();
|
|
3006
|
+
}
|
|
2640
3007
|
async authenticate(token) {
|
|
2641
3008
|
return new Promise((resolve, reject) => {
|
|
2642
3009
|
const requestId = `auth_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
|
|
@@ -2733,7 +3100,7 @@ var RebaseWebSocketClient = class {
|
|
|
2733
3100
|
this.ws = null;
|
|
2734
3101
|
}
|
|
2735
3102
|
try {
|
|
2736
|
-
const socket = new this.WebSocketConstructor(withOptIns(this.websocketUrl));
|
|
3103
|
+
const socket = new this.WebSocketConstructor(withOptIns(this.websocketUrl, this.affinity));
|
|
2737
3104
|
this.ws = socket;
|
|
2738
3105
|
this.ws.onopen = async () => {
|
|
2739
3106
|
this.connectionDebug("Connected to PostgreSQL backend");
|
|
@@ -2748,7 +3115,7 @@ var RebaseWebSocketClient = class {
|
|
|
2748
3115
|
try {
|
|
2749
3116
|
token = await this.getAuthToken();
|
|
2750
3117
|
if (token) {
|
|
2751
|
-
await this.
|
|
3118
|
+
await this.authenticateRetrying(token, socket);
|
|
2752
3119
|
this.connectionDebug("WebSocket auto-authenticated");
|
|
2753
3120
|
}
|
|
2754
3121
|
} catch (error) {
|
|
@@ -2756,7 +3123,13 @@ var RebaseWebSocketClient = class {
|
|
|
2756
3123
|
this.noteSocketCeiling(error);
|
|
2757
3124
|
return;
|
|
2758
3125
|
}
|
|
2759
|
-
if (!(token && this.noteSessionRefused(token, error)))
|
|
3126
|
+
if (!(token && this.noteSessionRefused(token, error))) {
|
|
3127
|
+
this.connectionDebug("WebSocket connected, not signed in yet:", error?.message || error);
|
|
3128
|
+
if (token && this.ws === socket && !this.refusedSession) {
|
|
3129
|
+
socket.close(4e3, "Could not authenticate; reconnecting");
|
|
3130
|
+
return;
|
|
3131
|
+
}
|
|
3132
|
+
}
|
|
2760
3133
|
}
|
|
2761
3134
|
}
|
|
2762
3135
|
if (this.ws !== socket) return;
|
|
@@ -3059,6 +3432,7 @@ var RebaseWebSocketClient = class {
|
|
|
3059
3432
|
return;
|
|
3060
3433
|
}
|
|
3061
3434
|
if (isChannelMessage(message)) {
|
|
3435
|
+
if (channelErrorCode(message) === "UNAUTHORIZED") this.recoverChannelAuth();
|
|
3062
3436
|
const handlers = this.channelHandlers.get(message.channel);
|
|
3063
3437
|
if (handlers) for (const handler of [...handlers]) try {
|
|
3064
3438
|
handler(message);
|
|
@@ -3136,10 +3510,7 @@ var RebaseWebSocketClient = class {
|
|
|
3136
3510
|
if (collectionSub.subscribeTimeout) clearTimeout(collectionSub.subscribeTimeout);
|
|
3137
3511
|
collectionSub.subscribeTimeout = void 0;
|
|
3138
3512
|
collectionSub.subscribeInFlight = false;
|
|
3139
|
-
|
|
3140
|
-
collectionSub.callbacks.forEach((callback) => {
|
|
3141
|
-
if (callback.onError) callback.onError(error);
|
|
3142
|
-
});
|
|
3513
|
+
this.notifyError(collectionSub.callbacks, frameError(message));
|
|
3143
3514
|
return;
|
|
3144
3515
|
}
|
|
3145
3516
|
}
|
|
@@ -3154,10 +3525,7 @@ var RebaseWebSocketClient = class {
|
|
|
3154
3525
|
if (entitySub.subscribeTimeout) clearTimeout(entitySub.subscribeTimeout);
|
|
3155
3526
|
entitySub.subscribeTimeout = void 0;
|
|
3156
3527
|
entitySub.subscribeInFlight = false;
|
|
3157
|
-
|
|
3158
|
-
entitySub.callbacks.forEach((callback) => {
|
|
3159
|
-
if (callback.onError) callback.onError(error);
|
|
3160
|
-
});
|
|
3528
|
+
this.notifyError(entitySub.callbacks, frameError(message));
|
|
3161
3529
|
return;
|
|
3162
3530
|
}
|
|
3163
3531
|
}
|
|
@@ -4100,9 +4468,33 @@ var RebaseRealtimeChannel = class {
|
|
|
4100
4468
|
const onConnectionLost = this.transport.onConnectionLost?.((error) => this.emitError(error));
|
|
4101
4469
|
if (onConnectionLost) this.unsubscribers.push(onConnectionLost);
|
|
4102
4470
|
await this.send("join_channel");
|
|
4471
|
+
if (!this.joined) return;
|
|
4103
4472
|
await this.send("presence_state");
|
|
4473
|
+
if (!this.joined) return;
|
|
4104
4474
|
if (this.wantsHistory) await this.requestHistory();
|
|
4105
4475
|
}
|
|
4476
|
+
/** Consecutive re-joins asked for by refusals, for the backoff; reset after a quiet minute. */
|
|
4477
|
+
rejoinAttempts = 0;
|
|
4478
|
+
rejoinTimer;
|
|
4479
|
+
lastRejoinAt = 0;
|
|
4480
|
+
/**
|
|
4481
|
+
* Re-join after the server refused this channel for a reason a retry can
|
|
4482
|
+
* change: it could not check permissions at that moment, or it has no record
|
|
4483
|
+
* of the join (a join that was itself refused, so every broadcast after it
|
|
4484
|
+
* came back "not a member"). The join was fire-and-forget and `joined` was
|
|
4485
|
+
* already set, so nothing else would ever send it again. Backs off 1, 2, 4…
|
|
4486
|
+
* up to 30 seconds, one re-join at a time.
|
|
4487
|
+
*/
|
|
4488
|
+
scheduleRejoin() {
|
|
4489
|
+
if (this.rejoinTimer || !this.joined) return;
|
|
4490
|
+
if (Date.now() - this.lastRejoinAt > 6e4) this.rejoinAttempts = 0;
|
|
4491
|
+
const delay = Math.min(3e4, 1e3 * 2 ** this.rejoinAttempts++);
|
|
4492
|
+
this.rejoinTimer = setTimeout(() => {
|
|
4493
|
+
this.rejoinTimer = void 0;
|
|
4494
|
+
this.lastRejoinAt = Date.now();
|
|
4495
|
+
if (this.joined) this.rejoin();
|
|
4496
|
+
}, delay);
|
|
4497
|
+
}
|
|
4106
4498
|
async rejoin() {
|
|
4107
4499
|
try {
|
|
4108
4500
|
await this.send("join_channel");
|
|
@@ -4162,8 +4554,10 @@ var RebaseRealtimeChannel = class {
|
|
|
4162
4554
|
*/
|
|
4163
4555
|
async track(state) {
|
|
4164
4556
|
await this.join();
|
|
4557
|
+
if (!this.joined) return;
|
|
4165
4558
|
this.trackedState = state;
|
|
4166
4559
|
await this.send("presence_track", { state });
|
|
4560
|
+
if (!this.joined || this.trackedState !== state) return;
|
|
4167
4561
|
if (!this.heartbeat) {
|
|
4168
4562
|
this.heartbeat = setInterval(() => {
|
|
4169
4563
|
if (!this.trackedState) return;
|
|
@@ -4290,6 +4684,10 @@ var RebaseRealtimeChannel = class {
|
|
|
4290
4684
|
/** Leave the channel and release every listener and timer. */
|
|
4291
4685
|
async leave() {
|
|
4292
4686
|
this.stopHeartbeat();
|
|
4687
|
+
if (this.rejoinTimer) {
|
|
4688
|
+
clearTimeout(this.rejoinTimer);
|
|
4689
|
+
this.rejoinTimer = void 0;
|
|
4690
|
+
}
|
|
4293
4691
|
this.trackedState = null;
|
|
4294
4692
|
this.presences = {};
|
|
4295
4693
|
this.presenceHandlers.clear();
|
|
@@ -4433,6 +4831,7 @@ var RebaseRealtimeChannel = class {
|
|
|
4433
4831
|
const asObject = typeof raw === "object" ? raw : void 0;
|
|
4434
4832
|
const text = asObject?.message ?? (typeof raw === "string" ? raw : void 0) ?? message.error ?? "The server refused a channel operation.";
|
|
4435
4833
|
this.emitError(new RebaseApiError$1(text, { ...asObject?.code ? { code: asObject.code } : {} }));
|
|
4834
|
+
if (this.joined && rejoinsAfter(asObject?.code, text)) this.scheduleRejoin();
|
|
4436
4835
|
break;
|
|
4437
4836
|
}
|
|
4438
4837
|
}
|
|
@@ -4499,14 +4898,39 @@ var RebaseRealtimeChannel = class {
|
|
|
4499
4898
|
this.deliver(event);
|
|
4500
4899
|
}
|
|
4501
4900
|
}
|
|
4901
|
+
/**
|
|
4902
|
+
* Hand an event to every broadcast handler, each isolated from the
|
|
4903
|
+
* others. A throw is reported and goes no further: this runs in the middle
|
|
4904
|
+
* of a replay or a flush, and one escaping it would end that pass with the
|
|
4905
|
+
* catch-up still marked in flight and its timeout already cleared, so every
|
|
4906
|
+
* later message on the channel would be held back for good.
|
|
4907
|
+
*/
|
|
4502
4908
|
deliver(event) {
|
|
4503
|
-
for (const handler of [...this.broadcastHandlers])
|
|
4909
|
+
for (const handler of [...this.broadcastHandlers]) try {
|
|
4910
|
+
handler(event);
|
|
4911
|
+
} catch (e) {
|
|
4912
|
+
console.error("Error in channel broadcast handler:", e);
|
|
4913
|
+
}
|
|
4504
4914
|
}
|
|
4505
4915
|
emitPresence(diff) {
|
|
4506
4916
|
const snapshot = { ...this.presences };
|
|
4507
|
-
for (const handler of this.presenceHandlers)
|
|
4917
|
+
for (const handler of [...this.presenceHandlers]) try {
|
|
4918
|
+
handler(snapshot, diff);
|
|
4919
|
+
} catch (e) {
|
|
4920
|
+
console.error("Error in channel presence handler:", e);
|
|
4921
|
+
}
|
|
4508
4922
|
}
|
|
4509
4923
|
};
|
|
4924
|
+
/**
|
|
4925
|
+
* Whether a channel refusal is one a re-join can recover from: the server's
|
|
4926
|
+
* auth store could not answer (`ROLE_LOOKUP_FAILED`, `DATABASE_UNAVAILABLE`), or
|
|
4927
|
+
* it no longer counts this client a member. A channel the client may not use
|
|
4928
|
+
* (any other `CHANNEL_FORBIDDEN`) is not retried.
|
|
4929
|
+
*/
|
|
4930
|
+
function rejoinsAfter(code, message) {
|
|
4931
|
+
if (code === "ROLE_LOOKUP_FAILED" || code === "DATABASE_UNAVAILABLE") return true;
|
|
4932
|
+
return code === "CHANNEL_FORBIDDEN" && /not a member/i.test(message);
|
|
4933
|
+
}
|
|
4510
4934
|
//#endregion
|
|
4511
4935
|
//#region src/offline-lazy.ts
|
|
4512
4936
|
/**
|
|
@@ -4543,7 +4967,7 @@ var LazyOfflineManager = class {
|
|
|
4543
4967
|
keepsLastUser;
|
|
4544
4968
|
constructor(config, createInner) {
|
|
4545
4969
|
this.keepsLastUser = config.keepLastUser === true;
|
|
4546
|
-
import("./offline-
|
|
4970
|
+
import("./offline-BjJdcVBb.js").then(({ OfflineManager: Engine }) => {
|
|
4547
4971
|
const engine = new Engine(config, createInner);
|
|
4548
4972
|
this.engine = engine;
|
|
4549
4973
|
const queued = this.queued;
|
|
@@ -4728,7 +5152,7 @@ function deriveWebSocketUrl(baseUrl) {
|
|
|
4728
5152
|
return toWsProtocol(baseUrl);
|
|
4729
5153
|
}
|
|
4730
5154
|
function createRebaseClient(options) {
|
|
4731
|
-
const transport = createTransport(options, { credentialOutOfBand: options.auth
|
|
5155
|
+
const transport = createTransport(options, { credentialOutOfBand: resolveAuthFlowMode(options.auth) === "cookie" });
|
|
4732
5156
|
const auth = createAuth(transport, options.auth);
|
|
4733
5157
|
const admin = createAdmin(transport, options.admin);
|
|
4734
5158
|
const cron = createCron(transport, options.cron);
|
|
@@ -4776,6 +5200,7 @@ function createRebaseClient(options) {
|
|
|
4776
5200
|
if (resolvedWsUrl) {
|
|
4777
5201
|
ws = new RebaseWebSocketClient({
|
|
4778
5202
|
websocketUrl: resolvedWsUrl,
|
|
5203
|
+
affinity: options.realtime && options.realtime !== true ? options.realtime.affinity : void 0,
|
|
4779
5204
|
getAuthToken: () => transport.resolveToken(),
|
|
4780
5205
|
onUnauthorized: () => onUnauthorized(),
|
|
4781
5206
|
impersonate: options.impersonate,
|
|
@@ -4787,7 +5212,7 @@ function createRebaseClient(options) {
|
|
|
4787
5212
|
if (event === "SIGNED_OUT") {
|
|
4788
5213
|
realtimeUid = null;
|
|
4789
5214
|
ws.disconnect();
|
|
4790
|
-
} else if (event === "SIGNED_IN" || event === "TOKEN_REFRESHED") {
|
|
5215
|
+
} else if (event === "SIGNED_IN" || event === "TOKEN_REFRESHED" || event === "USER_UPDATED") {
|
|
4791
5216
|
const uid = session?.user?.uid ?? null;
|
|
4792
5217
|
if (uid !== realtimeUid) {
|
|
4793
5218
|
realtimeUid = uid;
|
|
@@ -4957,24 +5382,26 @@ function createRebaseClient(options) {
|
|
|
4957
5382
|
createStorageSource,
|
|
4958
5383
|
fetchStorageSources,
|
|
4959
5384
|
ws,
|
|
4960
|
-
realtime: {
|
|
4961
|
-
|
|
4962
|
-
|
|
4963
|
-
|
|
4964
|
-
|
|
4965
|
-
|
|
4966
|
-
|
|
4967
|
-
|
|
4968
|
-
|
|
4969
|
-
channel: (name, options) => {
|
|
4970
|
-
|
|
4971
|
-
|
|
4972
|
-
|
|
4973
|
-
|
|
4974
|
-
|
|
4975
|
-
|
|
4976
|
-
|
|
4977
|
-
|
|
5385
|
+
realtime: {
|
|
5386
|
+
/**
|
|
5387
|
+
* Join a broadcast/presence channel.
|
|
5388
|
+
*
|
|
5389
|
+
* Repeated calls with the same name return the same channel, so
|
|
5390
|
+
* separate components can attach handlers without each opening its
|
|
5391
|
+
* own membership — and `leave()` from one would otherwise silently
|
|
5392
|
+
* cut off the others.
|
|
5393
|
+
*/
|
|
5394
|
+
channel: (name, options) => {
|
|
5395
|
+
if (!ws) throw new RebaseClientError(realtimeUnreachable ? `Realtime is enabled but ${unreachableReason}` : "Realtime is disabled on this client (realtime: false), so channels are unavailable.", { code: "REALTIME_DISABLED" });
|
|
5396
|
+
let existing = realtimeChannels.get(name);
|
|
5397
|
+
if (!existing) {
|
|
5398
|
+
existing = new RebaseRealtimeChannel(name, ws, options);
|
|
5399
|
+
realtimeChannels.set(name, existing);
|
|
5400
|
+
} else if (options?.history) existing.enableHistory();
|
|
5401
|
+
return existing;
|
|
5402
|
+
},
|
|
5403
|
+
setAffinity: (key) => ws?.setAffinity(key)
|
|
5404
|
+
},
|
|
4978
5405
|
/**
|
|
4979
5406
|
* Release every handle that can keep a process alive — see the
|
|
4980
5407
|
* `close` docblock on the client interface.
|
|
@@ -5062,6 +5489,6 @@ channel: (name, options) => {
|
|
|
5062
5489
|
};
|
|
5063
5490
|
}
|
|
5064
5491
|
//#endregion
|
|
5065
|
-
export { MemoryOfflineStore, RebaseApiError, RebaseClientError, RebasePaginationError, RebaseRealtimeChannel, RebaseWebSocketClient, STORAGE_REFERENCE_SCHEME, and, cond, createCookieStorage, createMemoryStorage, createRebaseClient, etagOf, isOfflineError, isStorageReference, not, or, parseStorageReference, resolveStorageReferences, storageReference, storageReferencesForDownloadUrls, storageTargetOfDownloadUrl, storageTargetsInText };
|
|
5492
|
+
export { APPLE_JS_SDK_URL, MemoryOfflineStore, RebaseApiError, RebaseClientError, RebasePaginationError, RebaseRealtimeChannel, RebaseWebSocketClient, STORAGE_REFERENCE_SCHEME, and, cond, createCookieStorage, createMemoryStorage, createRebaseClient, etagOf, isOfflineError, isStorageReference, not, or, parseStorageReference, preloadAppleSignIn, requestAppleAuthorization, resolveStorageReferences, storageReference, storageReferencesForDownloadUrls, storageTargetOfDownloadUrl, storageTargetsInText };
|
|
5066
5493
|
|
|
5067
5494
|
//# sourceMappingURL=index.es.js.map
|