@poly-x/react 0.1.0-alpha.9 → 0.1.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/index.cjs +897 -26
- package/dist/index.d.cts +322 -4
- package/dist/index.d.mts +322 -4
- package/dist/index.mjs +891 -28
- package/dist/styles.css +216 -0
- package/package.json +2 -2
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { AuthClient, FetchTransport, InMemoryLock, InMemoryPkceStore, InMemorySessionChannel, InMemorySessionStore, createSessionEngine, generatePkce, randomState, resolveConfig } from "@poly-x/core";
|
|
3
|
-
import { Fragment, createContext, useCallback, useContext, useEffect, useMemo, useState, useSyncExternalStore } from "react";
|
|
3
|
+
import { Children, Fragment, createContext, isValidElement, useCallback, useContext, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
|
4
4
|
import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
|
|
5
5
|
//#region src/auth-channel.ts
|
|
6
6
|
var BroadcastAuthChannel = class {
|
|
@@ -299,31 +299,225 @@ function PolyXProvider({ publishableKey, baseUrl, signInUrl, children }) {
|
|
|
299
299
|
});
|
|
300
300
|
}
|
|
301
301
|
//#endregion
|
|
302
|
+
//#region src/bff-session.ts
|
|
303
|
+
/**
|
|
304
|
+
* Client session under BFF custody (ADR-0004).
|
|
305
|
+
*
|
|
306
|
+
* `@poly-x/next` seals the tokens in an httpOnly cookie, so a consuming app mounts no
|
|
307
|
+
* `<PolyXProvider>` and there is no client engine to read — there is nothing for it to own.
|
|
308
|
+
* The hooks still have to work there, so they fall back to this: a single module-level store
|
|
309
|
+
* that reads server truth from the `session` route handler once and feeds the *same*
|
|
310
|
+
* `SessionState` machine the engine drives. That is what ADR-0004 meant by custody being
|
|
311
|
+
* "invisible to the consumer API surface".
|
|
312
|
+
*
|
|
313
|
+
* It follows `<SignIn/>`'s precedent — work without a provider, degrade quietly — rather than
|
|
314
|
+
* asking BFF apps to adopt a provider whose whole purpose is holding tokens they don't have.
|
|
315
|
+
*/
|
|
316
|
+
const SESSION_ENDPOINT = "/api/polyx/session";
|
|
317
|
+
const SIGNOUT_ENDPOINT = "/api/polyx/signout";
|
|
318
|
+
var BffSessionStore = class {
|
|
319
|
+
state = { status: "resolving" };
|
|
320
|
+
listeners = /* @__PURE__ */ new Set();
|
|
321
|
+
loading = false;
|
|
322
|
+
watching = false;
|
|
323
|
+
getState = () => this.state;
|
|
324
|
+
/** SSR has no session to read; render the resolving branch and settle on the client. */
|
|
325
|
+
getServerState = () => ({ status: "resolving" });
|
|
326
|
+
subscribe = (listener) => {
|
|
327
|
+
this.listeners.add(listener);
|
|
328
|
+
this.load();
|
|
329
|
+
this.watchFocus();
|
|
330
|
+
return () => {
|
|
331
|
+
this.listeners.delete(listener);
|
|
332
|
+
};
|
|
333
|
+
};
|
|
334
|
+
/**
|
|
335
|
+
* The platform revokes every session for a user when an admin changes their permission,
|
|
336
|
+
* suspends them, or resets their password — and it pushes nothing, so a revoked user keeps
|
|
337
|
+
* looking signed in until they happen to make a request. Re-checking when the tab regains
|
|
338
|
+
* focus is the cheapest way to notice: come back to the tab, discover you're signed out.
|
|
339
|
+
*
|
|
340
|
+
* It is not a replacement for the 401 the next request will get; it just moves the discovery
|
|
341
|
+
* to a moment the user is actually looking at the screen.
|
|
342
|
+
*/
|
|
343
|
+
watchFocus() {
|
|
344
|
+
if (this.watching || typeof window === "undefined") return;
|
|
345
|
+
this.watching = true;
|
|
346
|
+
const recheck = () => {
|
|
347
|
+
if (typeof document !== "undefined" && document.visibilityState === "hidden") return;
|
|
348
|
+
this.revalidate();
|
|
349
|
+
};
|
|
350
|
+
window.addEventListener("focus", recheck);
|
|
351
|
+
document?.addEventListener?.("visibilitychange", recheck);
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* Re-read the session without passing through `resolving` — a confirmed session must not
|
|
355
|
+
* flicker the UI back to a loading state. Only a definite signed-out answer signs the user
|
|
356
|
+
* out: an unreachable server is a blip, not a revocation.
|
|
357
|
+
*/
|
|
358
|
+
async revalidate() {
|
|
359
|
+
if (this.loading || this.state.status === "resolving") return;
|
|
360
|
+
this.loading = true;
|
|
361
|
+
try {
|
|
362
|
+
const response = await fetch(SESSION_ENDPOINT, {
|
|
363
|
+
credentials: "same-origin",
|
|
364
|
+
headers: { accept: "application/json" }
|
|
365
|
+
});
|
|
366
|
+
const body = response.ok ? await response.json() : null;
|
|
367
|
+
const signedIn = Boolean(body?.isSignedIn && body.claims);
|
|
368
|
+
if (!signedIn && this.state.status !== "signed-out") this.set({
|
|
369
|
+
status: "signed-out",
|
|
370
|
+
reason: "revoked"
|
|
371
|
+
});
|
|
372
|
+
else if (signedIn && body?.claims) this.set({
|
|
373
|
+
status: "authenticated",
|
|
374
|
+
session: { claims: body.claims }
|
|
375
|
+
});
|
|
376
|
+
} catch {} finally {
|
|
377
|
+
this.loading = false;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* Reading the session is a one-shot per page load, shared by every component that asks —
|
|
382
|
+
* a user menu and three gates must not mean four round-trips.
|
|
383
|
+
*/
|
|
384
|
+
async load() {
|
|
385
|
+
if (this.loading || this.state.status !== "resolving") return;
|
|
386
|
+
this.loading = true;
|
|
387
|
+
try {
|
|
388
|
+
const response = await fetch(SESSION_ENDPOINT, {
|
|
389
|
+
credentials: "same-origin",
|
|
390
|
+
headers: { accept: "application/json" }
|
|
391
|
+
});
|
|
392
|
+
const body = response.ok ? await response.json() : null;
|
|
393
|
+
this.set(body?.isSignedIn && body.claims ? {
|
|
394
|
+
status: "authenticated",
|
|
395
|
+
session: { claims: body.claims }
|
|
396
|
+
} : {
|
|
397
|
+
status: "signed-out",
|
|
398
|
+
reason: "signed-out"
|
|
399
|
+
});
|
|
400
|
+
} catch {
|
|
401
|
+
this.set({
|
|
402
|
+
status: "signed-out",
|
|
403
|
+
reason: "signed-out"
|
|
404
|
+
});
|
|
405
|
+
} finally {
|
|
406
|
+
this.loading = false;
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
410
|
+
* v2 (FR-LIVE-1/2): re-read server truth and update claims, resolving whether **authorization
|
|
411
|
+
* actually changed**. Drives the live-authz orchestrator (`startLiveAuthz`): a `true` means a
|
|
412
|
+
* consumer that gates on `useUser()` should re-guard. Never flickers to `resolving`; a definite
|
|
413
|
+
* signed-out answer signs the user out (revoked), a network blip keeps the last-known claims.
|
|
414
|
+
* The orchestrator single-flights callers, so this needs no internal in-flight guard.
|
|
415
|
+
*/
|
|
416
|
+
refresh = async () => {
|
|
417
|
+
try {
|
|
418
|
+
const response = await fetch(SESSION_ENDPOINT, {
|
|
419
|
+
credentials: "same-origin",
|
|
420
|
+
headers: { accept: "application/json" }
|
|
421
|
+
});
|
|
422
|
+
const body = response.ok ? await response.json() : null;
|
|
423
|
+
if (!Boolean(body?.isSignedIn && body.claims)) {
|
|
424
|
+
const changed = this.state.status !== "signed-out";
|
|
425
|
+
if (changed) this.set({
|
|
426
|
+
status: "signed-out",
|
|
427
|
+
reason: "revoked"
|
|
428
|
+
});
|
|
429
|
+
return changed;
|
|
430
|
+
}
|
|
431
|
+
const prevClaims = this.state.status === "authenticated" ? JSON.stringify(this.state.session.claims) : null;
|
|
432
|
+
const nextClaims = body.claims;
|
|
433
|
+
const changed = prevClaims !== JSON.stringify(nextClaims);
|
|
434
|
+
if (changed) this.set({
|
|
435
|
+
status: "authenticated",
|
|
436
|
+
session: { claims: nextClaims }
|
|
437
|
+
});
|
|
438
|
+
return changed;
|
|
439
|
+
} catch {
|
|
440
|
+
return false;
|
|
441
|
+
}
|
|
442
|
+
};
|
|
443
|
+
set(next) {
|
|
444
|
+
this.state = next;
|
|
445
|
+
for (const listener of this.listeners) listener();
|
|
446
|
+
}
|
|
447
|
+
/**
|
|
448
|
+
* Sign-out has to reach the server — only it can unseal an httpOnly cookie, and only it
|
|
449
|
+
* holds the token needed to revoke the session upstream (X002).
|
|
450
|
+
*
|
|
451
|
+
* A same-origin fetch, not a navigation: the response's Set-Cookie still applies, and it
|
|
452
|
+
* leaves the destination to the caller. That is why the handler is content-negotiated —
|
|
453
|
+
* a server-side redirect target would be an open redirect on the auth path, and the client
|
|
454
|
+
* already knows where it wants to land.
|
|
455
|
+
*/
|
|
456
|
+
signOut = async (options) => {
|
|
457
|
+
const query = options?.scope === "everywhere" ? "?scope=everywhere" : "";
|
|
458
|
+
try {
|
|
459
|
+
await fetch(`${SIGNOUT_ENDPOINT}${query}`, {
|
|
460
|
+
method: "POST",
|
|
461
|
+
credentials: "same-origin",
|
|
462
|
+
headers: { accept: "application/json" }
|
|
463
|
+
});
|
|
464
|
+
} catch {}
|
|
465
|
+
this.set({
|
|
466
|
+
status: "signed-out",
|
|
467
|
+
reason: "signed-out"
|
|
468
|
+
});
|
|
469
|
+
if (options?.onSignOut) try {
|
|
470
|
+
await options.onSignOut();
|
|
471
|
+
} catch {}
|
|
472
|
+
window.location.assign(options?.redirectTo ?? "/");
|
|
473
|
+
};
|
|
474
|
+
/** Null by design: under BFF custody the token never reaches the browser (FR-SES-3). */
|
|
475
|
+
getToken = async () => null;
|
|
476
|
+
};
|
|
477
|
+
let store = new BffSessionStore();
|
|
478
|
+
function getBffSessionStore() {
|
|
479
|
+
return store;
|
|
480
|
+
}
|
|
481
|
+
//#endregion
|
|
302
482
|
//#region src/hooks.ts
|
|
303
|
-
function
|
|
483
|
+
function useSessionSource() {
|
|
304
484
|
const ctx = useContext(PolyXContext);
|
|
305
|
-
if (!ctx)
|
|
306
|
-
|
|
485
|
+
if (!ctx) return {
|
|
486
|
+
source: getBffSessionStore(),
|
|
487
|
+
canSignIn: false
|
|
488
|
+
};
|
|
489
|
+
const { engine, controller } = ctx;
|
|
490
|
+
return {
|
|
491
|
+
source: {
|
|
492
|
+
getState: () => engine.getState(),
|
|
493
|
+
subscribe: (listener) => engine.subscribe(listener),
|
|
494
|
+
signOut: () => engine.signOut(),
|
|
495
|
+
getToken: async () => {
|
|
496
|
+
try {
|
|
497
|
+
return await engine.getAccessToken();
|
|
498
|
+
} catch {
|
|
499
|
+
return null;
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
},
|
|
503
|
+
canSignIn: Boolean(controller)
|
|
504
|
+
};
|
|
307
505
|
}
|
|
308
506
|
/** The raw session state machine value — tearing-free under concurrent React. */
|
|
309
507
|
function useSession() {
|
|
310
|
-
const {
|
|
311
|
-
|
|
312
|
-
const getSnapshot = useCallback(() => engine.getState(), [engine]);
|
|
313
|
-
return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
|
|
508
|
+
const { source } = useSessionSource();
|
|
509
|
+
return useSyncExternalStore(useCallback((onChange) => source.subscribe(onChange), [source]), useCallback(() => source.getState(), [source]), useCallback(() => (source.getServerState ?? source.getState)(), [source]));
|
|
314
510
|
}
|
|
315
511
|
function useAuth() {
|
|
316
|
-
const
|
|
512
|
+
const ctx = useContext(PolyXContext);
|
|
513
|
+
const { source } = useSessionSource();
|
|
317
514
|
const state = useSession();
|
|
318
|
-
const signIn = useCallback((options) =>
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
return null;
|
|
325
|
-
}
|
|
326
|
-
}, [engine]);
|
|
515
|
+
const signIn = useCallback(async (options) => {
|
|
516
|
+
if (!ctx) throw new Error("PolyX: signIn() needs a <PolyXProvider> (it owns the publishable key and the popup flow). Under BFF custody, render <SignIn/> or link to your sign-in route instead.");
|
|
517
|
+
return ctx.controller.signIn(options);
|
|
518
|
+
}, [ctx]);
|
|
519
|
+
const signOut = useCallback((options) => source.signOut(options), [source]);
|
|
520
|
+
const getToken = useCallback(() => source.getToken(), [source]);
|
|
327
521
|
return {
|
|
328
522
|
isLoaded: state.status !== "resolving",
|
|
329
523
|
isSignedIn: state.status === "authenticated" || state.status === "refreshing",
|
|
@@ -334,8 +528,11 @@ function useAuth() {
|
|
|
334
528
|
}
|
|
335
529
|
/** Run this on your callback route to complete a sign-in (see `<AuthCallback>`). */
|
|
336
530
|
function useAuthCallback() {
|
|
337
|
-
const
|
|
338
|
-
return useCallback(() =>
|
|
531
|
+
const ctx = useContext(PolyXContext);
|
|
532
|
+
return useCallback(() => {
|
|
533
|
+
if (!ctx) throw new Error("PolyX: <AuthCallback> / useAuthCallback() must be used within a <PolyXProvider>.");
|
|
534
|
+
return ctx.controller.handleCallback();
|
|
535
|
+
}, [ctx]);
|
|
339
536
|
}
|
|
340
537
|
function useUser() {
|
|
341
538
|
const state = useSession();
|
|
@@ -350,8 +547,89 @@ function Protected({ children, fallback = null, loading = null }) {
|
|
|
350
547
|
return isSignedIn ? children : fallback;
|
|
351
548
|
}
|
|
352
549
|
//#endregion
|
|
550
|
+
//#region src/geolocation.ts
|
|
551
|
+
/** W3C Geolocation `PositionError.PERMISSION_DENIED`. The only code that means a real "no". */
|
|
552
|
+
const PERMISSION_DENIED = 1;
|
|
553
|
+
/** One capture attempt at a given accuracy. Never rejects. */
|
|
554
|
+
function attemptCapture(geo, highAccuracy, timeout) {
|
|
555
|
+
return new Promise((resolve) => {
|
|
556
|
+
let settled = false;
|
|
557
|
+
const done = (outcome) => {
|
|
558
|
+
if (settled) return;
|
|
559
|
+
settled = true;
|
|
560
|
+
resolve(outcome);
|
|
561
|
+
};
|
|
562
|
+
const timer = setTimeout(() => done({
|
|
563
|
+
result: { consent: "granted" },
|
|
564
|
+
retriable: true
|
|
565
|
+
}), timeout + 1500);
|
|
566
|
+
const finish = (outcome) => {
|
|
567
|
+
clearTimeout(timer);
|
|
568
|
+
done(outcome);
|
|
569
|
+
};
|
|
570
|
+
try {
|
|
571
|
+
geo.getCurrentPosition((position) => finish({
|
|
572
|
+
result: {
|
|
573
|
+
latitude: String(position.coords.latitude),
|
|
574
|
+
longitude: String(position.coords.longitude),
|
|
575
|
+
accuracyMeters: typeof position.coords.accuracy === "number" ? position.coords.accuracy : void 0,
|
|
576
|
+
consent: "granted"
|
|
577
|
+
},
|
|
578
|
+
retriable: false
|
|
579
|
+
}), (err) => {
|
|
580
|
+
const code = err?.code;
|
|
581
|
+
const denied = typeof code === "number" && code === PERMISSION_DENIED;
|
|
582
|
+
finish({
|
|
583
|
+
result: { consent: denied ? "denied" : "granted" },
|
|
584
|
+
retriable: !denied
|
|
585
|
+
});
|
|
586
|
+
}, {
|
|
587
|
+
enableHighAccuracy: highAccuracy,
|
|
588
|
+
timeout,
|
|
589
|
+
maximumAge: 0
|
|
590
|
+
});
|
|
591
|
+
} catch {
|
|
592
|
+
finish({
|
|
593
|
+
result: { consent: "granted" },
|
|
594
|
+
retriable: true
|
|
595
|
+
});
|
|
596
|
+
}
|
|
597
|
+
});
|
|
598
|
+
}
|
|
599
|
+
/**
|
|
600
|
+
* Capture the browser's precise location. Resolves to a consent-labelled result and never
|
|
601
|
+
* throws/rejects. High-accuracy first; on a no-fix (not a denial) retries once at low accuracy.
|
|
602
|
+
*/
|
|
603
|
+
async function capturePreciseLocation(consented, opts = {}) {
|
|
604
|
+
if (!consented) return { consent: "denied" };
|
|
605
|
+
const geo = opts.geolocation ?? (typeof navigator !== "undefined" ? navigator.geolocation : void 0);
|
|
606
|
+
if (!geo) return { consent: "denied" };
|
|
607
|
+
const highAccuracyMs = opts.timeoutMs ?? 8e3;
|
|
608
|
+
const lowAccuracyMs = opts.fallbackTimeoutMs ?? 12e3;
|
|
609
|
+
const first = await attemptCapture(geo, true, highAccuracyMs);
|
|
610
|
+
if (first.result.latitude !== void 0 || !first.retriable) return first.result;
|
|
611
|
+
return (await attemptCapture(geo, false, lowAccuracyMs)).result;
|
|
612
|
+
}
|
|
613
|
+
//#endregion
|
|
614
|
+
//#region src/device-context.ts
|
|
615
|
+
/** Capture the browser's timezone + screen resolution. Never throws; omits anything unavailable. */
|
|
616
|
+
function captureDeviceContext() {
|
|
617
|
+
const context = {};
|
|
618
|
+
try {
|
|
619
|
+
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
620
|
+
if (typeof timezone === "string" && timezone) context.timezone = timezone;
|
|
621
|
+
} catch {}
|
|
622
|
+
try {
|
|
623
|
+
if (typeof window !== "undefined" && window.screen) {
|
|
624
|
+
const { width, height } = window.screen;
|
|
625
|
+
if (Number.isFinite(width) && Number.isFinite(height) && width > 0 && height > 0) context.screenResolution = `${Math.round(width)}x${Math.round(height)}`;
|
|
626
|
+
}
|
|
627
|
+
} catch {}
|
|
628
|
+
return context;
|
|
629
|
+
}
|
|
630
|
+
//#endregion
|
|
353
631
|
//#region src/components/sign-in.tsx
|
|
354
|
-
const DEFAULT_LABELS$
|
|
632
|
+
const DEFAULT_LABELS$3 = {
|
|
355
633
|
heading: "Sign in",
|
|
356
634
|
subheading: "Enter your credentials to continue.",
|
|
357
635
|
tagline: "",
|
|
@@ -466,7 +744,7 @@ function SignIn(props) {
|
|
|
466
744
|
const action = props.action ?? "/api/polyx/authenticate";
|
|
467
745
|
const variant = props.variant ?? "card";
|
|
468
746
|
const labels = {
|
|
469
|
-
...DEFAULT_LABELS$
|
|
747
|
+
...DEFAULT_LABELS$3,
|
|
470
748
|
...props.labels
|
|
471
749
|
};
|
|
472
750
|
const [email, setEmail] = useState("");
|
|
@@ -509,6 +787,8 @@ function SignIn(props) {
|
|
|
509
787
|
setSubmitting(true);
|
|
510
788
|
setError(null);
|
|
511
789
|
try {
|
|
790
|
+
const geo = props.captureLocation ? await capturePreciseLocation(true) : void 0;
|
|
791
|
+
const deviceContext = captureDeviceContext();
|
|
512
792
|
const body = await (await fetch(action, {
|
|
513
793
|
method: "POST",
|
|
514
794
|
headers: { "content-type": "application/json" },
|
|
@@ -517,6 +797,8 @@ function SignIn(props) {
|
|
|
517
797
|
password,
|
|
518
798
|
organizationCode: props.organizationCode,
|
|
519
799
|
tenantId: options.tenantId,
|
|
800
|
+
...geo ? { geo } : {},
|
|
801
|
+
...Object.keys(deviceContext).length ? { deviceContext } : {},
|
|
520
802
|
...options.passwords
|
|
521
803
|
})
|
|
522
804
|
})).json().catch(() => ({}));
|
|
@@ -855,7 +1137,7 @@ function RecoveryStatus(props) {
|
|
|
855
1137
|
}
|
|
856
1138
|
//#endregion
|
|
857
1139
|
//#region src/components/forgot-password.tsx
|
|
858
|
-
const DEFAULT_LABELS$
|
|
1140
|
+
const DEFAULT_LABELS$2 = {
|
|
859
1141
|
heading: "Reset your password",
|
|
860
1142
|
subheading: "Enter your email and we'll send you a reset link.",
|
|
861
1143
|
emailLabel: "Email",
|
|
@@ -863,7 +1145,7 @@ const DEFAULT_LABELS$1 = {
|
|
|
863
1145
|
submit: "Send reset link",
|
|
864
1146
|
submitting: "Sending…",
|
|
865
1147
|
sentHeading: "Check your email",
|
|
866
|
-
sentSubheading: "If an account exists for {email}, a password reset link is on its way
|
|
1148
|
+
sentSubheading: "If an account exists for {email}, a password reset link is on its way — it expires in 30 minutes. If it doesn't arrive within a few minutes, check your spam folder, then contact your workspace administrator.",
|
|
867
1149
|
differentEmail: "Use a different email",
|
|
868
1150
|
backToSignIn: "Back to sign in",
|
|
869
1151
|
securedBy: "Secured by PolyX",
|
|
@@ -890,7 +1172,7 @@ function ForgotPassword(props) {
|
|
|
890
1172
|
const action = props.action ?? "/api/polyx/forgot-password";
|
|
891
1173
|
const signInPath = props.signInPath ?? "/sign-in";
|
|
892
1174
|
const labels = {
|
|
893
|
-
...DEFAULT_LABELS$
|
|
1175
|
+
...DEFAULT_LABELS$2,
|
|
894
1176
|
...props.labels
|
|
895
1177
|
};
|
|
896
1178
|
const [email, setEmail] = useState("");
|
|
@@ -1018,7 +1300,7 @@ function ForgotPassword(props) {
|
|
|
1018
1300
|
}
|
|
1019
1301
|
//#endregion
|
|
1020
1302
|
//#region src/components/reset-password.tsx
|
|
1021
|
-
const DEFAULT_LABELS = {
|
|
1303
|
+
const DEFAULT_LABELS$1 = {
|
|
1022
1304
|
heading: "Choose a new password",
|
|
1023
1305
|
subheading: "Enter and confirm your new password.",
|
|
1024
1306
|
newPasswordLabel: "New password",
|
|
@@ -1054,7 +1336,7 @@ function ResetPassword(props) {
|
|
|
1054
1336
|
const signInPath = props.signInPath ?? "/sign-in";
|
|
1055
1337
|
const forgotPasswordPath = props.forgotPasswordPath ?? "/forgot-password";
|
|
1056
1338
|
const labels = {
|
|
1057
|
-
...DEFAULT_LABELS,
|
|
1339
|
+
...DEFAULT_LABELS$1,
|
|
1058
1340
|
...props.labels
|
|
1059
1341
|
};
|
|
1060
1342
|
const [token] = useState(() => props.token ?? (typeof window !== "undefined" ? new URLSearchParams(window.location.search).get("token") ?? "" : ""));
|
|
@@ -1248,6 +1530,587 @@ function AuthCallback({ children = null }) {
|
|
|
1248
1530
|
return children;
|
|
1249
1531
|
}
|
|
1250
1532
|
//#endregion
|
|
1533
|
+
//#region src/components/placement.ts
|
|
1534
|
+
const OPPOSITE = {
|
|
1535
|
+
top: "bottom",
|
|
1536
|
+
bottom: "top",
|
|
1537
|
+
left: "right",
|
|
1538
|
+
right: "left"
|
|
1539
|
+
};
|
|
1540
|
+
/** Preference order when nothing is requested: vertical reads better for a menu than sideways. */
|
|
1541
|
+
const AUTO_ORDER = [
|
|
1542
|
+
"bottom",
|
|
1543
|
+
"top",
|
|
1544
|
+
"right",
|
|
1545
|
+
"left"
|
|
1546
|
+
];
|
|
1547
|
+
/** Room between the trigger and each viewport edge. */
|
|
1548
|
+
function spaceAround(trigger, viewport) {
|
|
1549
|
+
return {
|
|
1550
|
+
top: trigger.top,
|
|
1551
|
+
bottom: viewport.height - trigger.bottom,
|
|
1552
|
+
left: trigger.left,
|
|
1553
|
+
right: viewport.width - trigger.right
|
|
1554
|
+
};
|
|
1555
|
+
}
|
|
1556
|
+
function required(menu, gap) {
|
|
1557
|
+
return {
|
|
1558
|
+
top: menu.height + gap,
|
|
1559
|
+
bottom: menu.height + gap,
|
|
1560
|
+
left: menu.width + gap,
|
|
1561
|
+
right: menu.width + gap
|
|
1562
|
+
};
|
|
1563
|
+
}
|
|
1564
|
+
/**
|
|
1565
|
+
* Which side the menu should open on.
|
|
1566
|
+
*
|
|
1567
|
+
* An explicit side is honoured when it fits and flipped to its opposite when it doesn't — a
|
|
1568
|
+
* requested side that runs off-screen is a worse answer than the one that doesn't. `auto` takes
|
|
1569
|
+
* the first side that fits, and if none do, the roomiest: something has to be chosen, and the
|
|
1570
|
+
* least-bad option beats an arbitrary default.
|
|
1571
|
+
*/
|
|
1572
|
+
function resolveSide(preferred, trigger, menu, viewport, gap = 8) {
|
|
1573
|
+
const space = spaceAround(trigger, viewport);
|
|
1574
|
+
const need = required(menu, gap);
|
|
1575
|
+
const fits = (side) => space[side] >= need[side];
|
|
1576
|
+
if (preferred !== "auto") {
|
|
1577
|
+
if (fits(preferred)) return preferred;
|
|
1578
|
+
const opposite = OPPOSITE[preferred];
|
|
1579
|
+
return fits(opposite) ? opposite : preferred;
|
|
1580
|
+
}
|
|
1581
|
+
const firstFitting = AUTO_ORDER.find(fits);
|
|
1582
|
+
if (firstFitting) return firstFitting;
|
|
1583
|
+
return AUTO_ORDER.reduce((best, side) => space[side] > space[best] ? side : best, AUTO_ORDER[0]);
|
|
1584
|
+
}
|
|
1585
|
+
//#endregion
|
|
1586
|
+
//#region src/components/user-avatar.tsx
|
|
1587
|
+
/**
|
|
1588
|
+
* Up to two initials from a display name. Handles the shapes the platform actually
|
|
1589
|
+
* produces — "Ali Ikram", a bare username, an email address.
|
|
1590
|
+
*/
|
|
1591
|
+
function initialsFrom(name) {
|
|
1592
|
+
const source = (name ?? "").trim();
|
|
1593
|
+
if (source.length === 0) return "?";
|
|
1594
|
+
const words = (source.includes("@") ? source.split("@")[0] : source).split(/[\s._-]+/).filter(Boolean);
|
|
1595
|
+
if (words.length === 0) return "?";
|
|
1596
|
+
return (words.length === 1 ? [words[0][0]] : [words[0][0], words[words.length - 1][0]]).join("").toUpperCase();
|
|
1597
|
+
}
|
|
1598
|
+
/**
|
|
1599
|
+
* The user's picture, or their initials. A missing avatar is the ordinary case rather than
|
|
1600
|
+
* an error, so initials are a first-class state, not a broken image.
|
|
1601
|
+
*/
|
|
1602
|
+
function UserAvatar({ src, name, size = 32, className }) {
|
|
1603
|
+
const rootClass = ["polyx-userbutton__avatar", className].filter(Boolean).join(" ");
|
|
1604
|
+
const style = {
|
|
1605
|
+
width: `${size}px`,
|
|
1606
|
+
height: `${size}px`
|
|
1607
|
+
};
|
|
1608
|
+
if (src) return /* @__PURE__ */ jsx("img", {
|
|
1609
|
+
className: rootClass,
|
|
1610
|
+
style,
|
|
1611
|
+
src,
|
|
1612
|
+
alt: name ?? ""
|
|
1613
|
+
});
|
|
1614
|
+
return /* @__PURE__ */ jsx("span", {
|
|
1615
|
+
className: rootClass,
|
|
1616
|
+
style,
|
|
1617
|
+
"aria-hidden": "true",
|
|
1618
|
+
children: initialsFrom(name)
|
|
1619
|
+
});
|
|
1620
|
+
}
|
|
1621
|
+
//#endregion
|
|
1622
|
+
//#region src/components/user-button.tsx
|
|
1623
|
+
const DEFAULT_LABELS = {
|
|
1624
|
+
trigger: "Account menu",
|
|
1625
|
+
manageAccount: "Manage account",
|
|
1626
|
+
signOut: "Sign out",
|
|
1627
|
+
signOutEverywhere: "Sign out everywhere"
|
|
1628
|
+
};
|
|
1629
|
+
const BUILT_INS = [
|
|
1630
|
+
"manageAccount",
|
|
1631
|
+
"signOut",
|
|
1632
|
+
"signOutEverywhere"
|
|
1633
|
+
];
|
|
1634
|
+
function isBuiltIn(label) {
|
|
1635
|
+
return BUILT_INS.includes(label);
|
|
1636
|
+
}
|
|
1637
|
+
/**
|
|
1638
|
+
* Declarative markers. `<UserButton/>` reads their props off the element tree and renders the
|
|
1639
|
+
* menu itself, so these never render anything. Their public prop types come from the signatures
|
|
1640
|
+
* declared on the exported object below.
|
|
1641
|
+
*
|
|
1642
|
+
* `Custom` and `Header` take arbitrary nodes on purpose: an app adopting this component in place
|
|
1643
|
+
* of its own user menu has to be able to bring its own UI, or it won't adopt it. That is
|
|
1644
|
+
* composition, not the style injection FR-BRAND-1 guards against — a consumer renders their own
|
|
1645
|
+
* subtree in a slot; they still cannot restyle the SDK's own chrome.
|
|
1646
|
+
*/
|
|
1647
|
+
function MenuItems() {
|
|
1648
|
+
return null;
|
|
1649
|
+
}
|
|
1650
|
+
function Action() {
|
|
1651
|
+
return null;
|
|
1652
|
+
}
|
|
1653
|
+
function Link() {
|
|
1654
|
+
return null;
|
|
1655
|
+
}
|
|
1656
|
+
function Custom() {
|
|
1657
|
+
return null;
|
|
1658
|
+
}
|
|
1659
|
+
function Header() {
|
|
1660
|
+
return null;
|
|
1661
|
+
}
|
|
1662
|
+
/**
|
|
1663
|
+
* Read the declarative children into a flat item list. A custom entry naming a built-in
|
|
1664
|
+
* *moves* it; unnamed built-ins keep their default order at the end. This is the whole reason
|
|
1665
|
+
* the API is declarative rather than a config array: it composes without letting a consumer
|
|
1666
|
+
* inject arbitrary markup or styles into the menu (FR-BRAND-1).
|
|
1667
|
+
*/
|
|
1668
|
+
function resolveItems(children, builtIns) {
|
|
1669
|
+
const supplied = [];
|
|
1670
|
+
const placed = /* @__PURE__ */ new Set();
|
|
1671
|
+
Children.forEach(children, (child) => {
|
|
1672
|
+
if (!isValidElement(child) || child.type !== MenuItems) return;
|
|
1673
|
+
Children.forEach(child.props.children, (item, index) => {
|
|
1674
|
+
if (!isValidElement(item)) return;
|
|
1675
|
+
if (item.type === Action) {
|
|
1676
|
+
const props = item.props;
|
|
1677
|
+
if (isBuiltIn(props.label)) {
|
|
1678
|
+
const builtIn = builtIns.get(props.label);
|
|
1679
|
+
if (builtIn) {
|
|
1680
|
+
supplied.push(builtIn);
|
|
1681
|
+
placed.add(props.label);
|
|
1682
|
+
}
|
|
1683
|
+
return;
|
|
1684
|
+
}
|
|
1685
|
+
supplied.push({
|
|
1686
|
+
key: `action-${index}`,
|
|
1687
|
+
label: props.label,
|
|
1688
|
+
labelIcon: props.labelIcon,
|
|
1689
|
+
onClick: props.onClick
|
|
1690
|
+
});
|
|
1691
|
+
return;
|
|
1692
|
+
}
|
|
1693
|
+
if (item.type === Link) {
|
|
1694
|
+
const props = item.props;
|
|
1695
|
+
supplied.push({
|
|
1696
|
+
key: `link-${index}`,
|
|
1697
|
+
label: props.label,
|
|
1698
|
+
labelIcon: props.labelIcon,
|
|
1699
|
+
href: props.href
|
|
1700
|
+
});
|
|
1701
|
+
return;
|
|
1702
|
+
}
|
|
1703
|
+
if (item.type === Custom) supplied.push({
|
|
1704
|
+
key: `custom-${index}`,
|
|
1705
|
+
custom: item.props.children
|
|
1706
|
+
});
|
|
1707
|
+
});
|
|
1708
|
+
});
|
|
1709
|
+
const remaining = [...builtIns.entries()].filter(([name]) => !placed.has(name)).map(([, item]) => item);
|
|
1710
|
+
return [...supplied, ...remaining];
|
|
1711
|
+
}
|
|
1712
|
+
/** The consumer's replacement for the identity block, if they supplied one. */
|
|
1713
|
+
function findHeader(children) {
|
|
1714
|
+
let header;
|
|
1715
|
+
Children.forEach(children, (child) => {
|
|
1716
|
+
if (isValidElement(child) && child.type === Header) header = child.props.children;
|
|
1717
|
+
});
|
|
1718
|
+
return header;
|
|
1719
|
+
}
|
|
1720
|
+
function UserButtonRoot(props) {
|
|
1721
|
+
const labels = {
|
|
1722
|
+
...DEFAULT_LABELS,
|
|
1723
|
+
...props.labels
|
|
1724
|
+
};
|
|
1725
|
+
const { isLoaded, isSignedIn, signOut } = useAuth();
|
|
1726
|
+
const user = useUser();
|
|
1727
|
+
const [open, setOpen] = useState(props.defaultOpen ?? false);
|
|
1728
|
+
const [focused, setFocused] = useState(0);
|
|
1729
|
+
const [side, setSide] = useState(props.side && props.side !== "auto" ? props.side : "bottom");
|
|
1730
|
+
const triggerRef = useRef(null);
|
|
1731
|
+
const menuRef = useRef(null);
|
|
1732
|
+
const itemRefs = useRef([]);
|
|
1733
|
+
const menuId = useId();
|
|
1734
|
+
const align = props.align ?? "end";
|
|
1735
|
+
const close = useCallback((returnFocus) => {
|
|
1736
|
+
setOpen(false);
|
|
1737
|
+
if (returnFocus) triggerRef.current?.focus();
|
|
1738
|
+
}, []);
|
|
1739
|
+
const onOpenChange = props.onOpenChange;
|
|
1740
|
+
const mounted = useRef(false);
|
|
1741
|
+
useEffect(() => {
|
|
1742
|
+
if (!mounted.current) {
|
|
1743
|
+
mounted.current = true;
|
|
1744
|
+
return;
|
|
1745
|
+
}
|
|
1746
|
+
onOpenChange?.(open);
|
|
1747
|
+
}, [open, onOpenChange]);
|
|
1748
|
+
useEffect(() => {
|
|
1749
|
+
if (!open) return;
|
|
1750
|
+
const onKeyDown = (event) => {
|
|
1751
|
+
if (event.key === "Escape") close(true);
|
|
1752
|
+
};
|
|
1753
|
+
const onPointerDown = (event) => {
|
|
1754
|
+
const root = triggerRef.current?.closest(".polyx-userbutton");
|
|
1755
|
+
if (root && !root.contains(event.target)) close(false);
|
|
1756
|
+
};
|
|
1757
|
+
document.addEventListener("keydown", onKeyDown);
|
|
1758
|
+
document.addEventListener("mousedown", onPointerDown);
|
|
1759
|
+
return () => {
|
|
1760
|
+
document.removeEventListener("keydown", onKeyDown);
|
|
1761
|
+
document.removeEventListener("mousedown", onPointerDown);
|
|
1762
|
+
};
|
|
1763
|
+
}, [open, close]);
|
|
1764
|
+
useEffect(() => {
|
|
1765
|
+
if (open) itemRefs.current[focused]?.focus();
|
|
1766
|
+
}, [open, focused]);
|
|
1767
|
+
/**
|
|
1768
|
+
* Choose the side once the menu exists and can be measured. `useLayoutEffect` runs before
|
|
1769
|
+
* paint, so the correction never shows as a jump — the menu is only ever painted where it
|
|
1770
|
+
* belongs. Re-measured on resize and on scroll, since either can invalidate the choice.
|
|
1771
|
+
*/
|
|
1772
|
+
useLayoutEffect(() => {
|
|
1773
|
+
if (!open) return;
|
|
1774
|
+
const place = () => {
|
|
1775
|
+
const trigger = triggerRef.current?.getBoundingClientRect();
|
|
1776
|
+
const menu = menuRef.current?.getBoundingClientRect();
|
|
1777
|
+
if (!trigger || !menu) return;
|
|
1778
|
+
setSide(resolveSide(props.side ?? "auto", trigger, {
|
|
1779
|
+
width: menu.width,
|
|
1780
|
+
height: menu.height
|
|
1781
|
+
}, {
|
|
1782
|
+
width: window.innerWidth,
|
|
1783
|
+
height: window.innerHeight
|
|
1784
|
+
}));
|
|
1785
|
+
};
|
|
1786
|
+
place();
|
|
1787
|
+
window.addEventListener("resize", place);
|
|
1788
|
+
window.addEventListener("scroll", place, true);
|
|
1789
|
+
return () => {
|
|
1790
|
+
window.removeEventListener("resize", place);
|
|
1791
|
+
window.removeEventListener("scroll", place, true);
|
|
1792
|
+
};
|
|
1793
|
+
}, [open, props.side]);
|
|
1794
|
+
if (!isLoaded) return props.fallback ?? null;
|
|
1795
|
+
if (!isSignedIn || !user) return null;
|
|
1796
|
+
const name = user.displayName ?? user.email ?? "";
|
|
1797
|
+
const builtIns = /* @__PURE__ */ new Map();
|
|
1798
|
+
if (props.manageAccountUrl) builtIns.set("manageAccount", {
|
|
1799
|
+
key: "manageAccount",
|
|
1800
|
+
label: labels.manageAccount,
|
|
1801
|
+
labelIcon: /* @__PURE__ */ jsx(GearIcon, {}),
|
|
1802
|
+
href: props.manageAccountUrl
|
|
1803
|
+
});
|
|
1804
|
+
builtIns.set("signOut", {
|
|
1805
|
+
key: "signOut",
|
|
1806
|
+
label: labels.signOut,
|
|
1807
|
+
labelIcon: /* @__PURE__ */ jsx(ExitIcon, {}),
|
|
1808
|
+
onClick: () => void signOut({
|
|
1809
|
+
redirectTo: props.afterSignOutUrl,
|
|
1810
|
+
onSignOut: props.onSignOut
|
|
1811
|
+
})
|
|
1812
|
+
});
|
|
1813
|
+
if (props.showSignOutEverywhere) builtIns.set("signOutEverywhere", {
|
|
1814
|
+
key: "signOutEverywhere",
|
|
1815
|
+
label: labels.signOutEverywhere,
|
|
1816
|
+
labelIcon: /* @__PURE__ */ jsx(ExitIcon, {}),
|
|
1817
|
+
onClick: () => void signOut({
|
|
1818
|
+
scope: "everywhere",
|
|
1819
|
+
redirectTo: props.afterSignOutUrl,
|
|
1820
|
+
onSignOut: props.onSignOut
|
|
1821
|
+
})
|
|
1822
|
+
});
|
|
1823
|
+
const items = resolveItems(props.children, builtIns);
|
|
1824
|
+
const customHeader = findHeader(props.children);
|
|
1825
|
+
const navigable = items.map((item, index) => ({
|
|
1826
|
+
item,
|
|
1827
|
+
index
|
|
1828
|
+
})).filter(({ item }) => !item.custom);
|
|
1829
|
+
const onMenuKeyDown = (event) => {
|
|
1830
|
+
if (navigable.length === 0) return;
|
|
1831
|
+
if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return;
|
|
1832
|
+
event.preventDefault();
|
|
1833
|
+
const next = (navigable.findIndex(({ index }) => index === focused) + (event.key === "ArrowDown" ? 1 : -1) + navigable.length) % navigable.length;
|
|
1834
|
+
setFocused(navigable[next].index);
|
|
1835
|
+
};
|
|
1836
|
+
return /* @__PURE__ */ jsxs("div", {
|
|
1837
|
+
className: [
|
|
1838
|
+
"polyx-signin",
|
|
1839
|
+
"polyx-userbutton",
|
|
1840
|
+
props.className
|
|
1841
|
+
].filter(Boolean).join(" "),
|
|
1842
|
+
"data-polyx-userbutton": open ? "open" : "closed",
|
|
1843
|
+
children: [/* @__PURE__ */ jsx("button", {
|
|
1844
|
+
ref: triggerRef,
|
|
1845
|
+
type: "button",
|
|
1846
|
+
className: ["polyx-userbutton__trigger", props.triggerClassName].filter(Boolean).join(" "),
|
|
1847
|
+
"aria-haspopup": "menu",
|
|
1848
|
+
"aria-expanded": open,
|
|
1849
|
+
"aria-controls": open ? menuId : void 0,
|
|
1850
|
+
"aria-label": labels.trigger,
|
|
1851
|
+
onClick: () => {
|
|
1852
|
+
setFocused(0);
|
|
1853
|
+
setOpen((current) => !current);
|
|
1854
|
+
},
|
|
1855
|
+
children: props.trigger ?? /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx(UserAvatar, {
|
|
1856
|
+
src: user.avatarUrl,
|
|
1857
|
+
name,
|
|
1858
|
+
size: props.avatarSize
|
|
1859
|
+
}), props.showName ? /* @__PURE__ */ jsx("span", {
|
|
1860
|
+
className: "polyx-userbutton__trigger-name",
|
|
1861
|
+
children: name
|
|
1862
|
+
}) : null] })
|
|
1863
|
+
}), open ? /* @__PURE__ */ jsxs("div", {
|
|
1864
|
+
ref: menuRef,
|
|
1865
|
+
id: menuId,
|
|
1866
|
+
role: "menu",
|
|
1867
|
+
className: "polyx-userbutton__menu",
|
|
1868
|
+
"data-polyx-side": side,
|
|
1869
|
+
"data-polyx-align": align,
|
|
1870
|
+
onKeyDown: onMenuKeyDown,
|
|
1871
|
+
children: [customHeader ?? /* @__PURE__ */ jsxs("div", {
|
|
1872
|
+
className: "polyx-userbutton__identity",
|
|
1873
|
+
children: [/* @__PURE__ */ jsx(UserAvatar, {
|
|
1874
|
+
src: user.avatarUrl,
|
|
1875
|
+
name,
|
|
1876
|
+
size: 36
|
|
1877
|
+
}), /* @__PURE__ */ jsxs("div", {
|
|
1878
|
+
className: "polyx-userbutton__identity-text",
|
|
1879
|
+
children: [user.displayName ? /* @__PURE__ */ jsx("span", {
|
|
1880
|
+
className: "polyx-userbutton__name",
|
|
1881
|
+
children: user.displayName
|
|
1882
|
+
}) : null, user.email ? /* @__PURE__ */ jsx("span", {
|
|
1883
|
+
className: "polyx-userbutton__email",
|
|
1884
|
+
children: user.email
|
|
1885
|
+
}) : null]
|
|
1886
|
+
})]
|
|
1887
|
+
}), /* @__PURE__ */ jsx("ul", {
|
|
1888
|
+
className: "polyx-userbutton__items",
|
|
1889
|
+
children: items.map((item, index) => /* @__PURE__ */ jsx("li", { children: item.custom ? /* @__PURE__ */ jsx("div", {
|
|
1890
|
+
className: "polyx-userbutton__custom",
|
|
1891
|
+
children: item.custom
|
|
1892
|
+
}) : item.href ? /* @__PURE__ */ jsxs("a", {
|
|
1893
|
+
ref: (node) => {
|
|
1894
|
+
itemRefs.current[index] = node;
|
|
1895
|
+
},
|
|
1896
|
+
role: "menuitem",
|
|
1897
|
+
tabIndex: index === focused ? 0 : -1,
|
|
1898
|
+
className: "polyx-userbutton__item",
|
|
1899
|
+
href: item.href,
|
|
1900
|
+
onClick: () => close(false),
|
|
1901
|
+
children: [item.labelIcon, item.label]
|
|
1902
|
+
}) : /* @__PURE__ */ jsxs("button", {
|
|
1903
|
+
ref: (node) => {
|
|
1904
|
+
itemRefs.current[index] = node;
|
|
1905
|
+
},
|
|
1906
|
+
role: "menuitem",
|
|
1907
|
+
tabIndex: index === focused ? 0 : -1,
|
|
1908
|
+
type: "button",
|
|
1909
|
+
className: "polyx-userbutton__item",
|
|
1910
|
+
onClick: () => {
|
|
1911
|
+
close(false);
|
|
1912
|
+
item.onClick?.();
|
|
1913
|
+
},
|
|
1914
|
+
children: [item.labelIcon, item.label]
|
|
1915
|
+
}) }, item.key))
|
|
1916
|
+
})]
|
|
1917
|
+
}) : null]
|
|
1918
|
+
});
|
|
1919
|
+
}
|
|
1920
|
+
function GearIcon() {
|
|
1921
|
+
return /* @__PURE__ */ jsxs("svg", {
|
|
1922
|
+
className: "polyx-userbutton__icon",
|
|
1923
|
+
viewBox: "0 0 16 16",
|
|
1924
|
+
fill: "none",
|
|
1925
|
+
"aria-hidden": "true",
|
|
1926
|
+
focusable: "false",
|
|
1927
|
+
children: [/* @__PURE__ */ jsx("circle", {
|
|
1928
|
+
cx: "8",
|
|
1929
|
+
cy: "8",
|
|
1930
|
+
r: "2.25",
|
|
1931
|
+
stroke: "currentColor",
|
|
1932
|
+
strokeWidth: "1.3"
|
|
1933
|
+
}), /* @__PURE__ */ jsx("path", {
|
|
1934
|
+
d: "M8 1.75v1.5M8 12.75v1.5M14.25 8h-1.5M3.25 8h-1.5M12.42 3.58l-1.06 1.06M4.64 11.36l-1.06 1.06M12.42 12.42l-1.06-1.06M4.64 4.64L3.58 3.58",
|
|
1935
|
+
stroke: "currentColor",
|
|
1936
|
+
strokeWidth: "1.3",
|
|
1937
|
+
strokeLinecap: "round"
|
|
1938
|
+
})]
|
|
1939
|
+
});
|
|
1940
|
+
}
|
|
1941
|
+
function ExitIcon() {
|
|
1942
|
+
return /* @__PURE__ */ jsx("svg", {
|
|
1943
|
+
className: "polyx-userbutton__icon",
|
|
1944
|
+
viewBox: "0 0 16 16",
|
|
1945
|
+
fill: "none",
|
|
1946
|
+
"aria-hidden": "true",
|
|
1947
|
+
focusable: "false",
|
|
1948
|
+
children: /* @__PURE__ */ jsx("path", {
|
|
1949
|
+
d: "M6 2.75H3.75a1 1 0 0 0-1 1v8.5a1 1 0 0 0 1 1H6M10.5 10.5 13 8l-2.5-2.5M13 8H6",
|
|
1950
|
+
stroke: "currentColor",
|
|
1951
|
+
strokeWidth: "1.3",
|
|
1952
|
+
strokeLinecap: "round",
|
|
1953
|
+
strokeLinejoin: "round"
|
|
1954
|
+
})
|
|
1955
|
+
});
|
|
1956
|
+
}
|
|
1957
|
+
/**
|
|
1958
|
+
* The signed-in user surface: avatar trigger + a menu with their identity and sign-out
|
|
1959
|
+
* (FR-SIGNIN-6). Reads only the hooks, so it behaves identically under either custody model
|
|
1960
|
+
* — an httpOnly BFF session or an in-memory SPA one — and needs no provider in a
|
|
1961
|
+
* `@poly-x/next` app.
|
|
1962
|
+
*
|
|
1963
|
+
* Custom entries compose declaratively:
|
|
1964
|
+
*
|
|
1965
|
+
* ```tsx
|
|
1966
|
+
* <UserButton manageAccountUrl="/account">
|
|
1967
|
+
* <UserButton.MenuItems>
|
|
1968
|
+
* <UserButton.Action label="signOut" /> // reposition a built-in
|
|
1969
|
+
* <UserButton.Link label="Docs" href="/docs" />
|
|
1970
|
+
* </UserButton.MenuItems>
|
|
1971
|
+
* </UserButton>
|
|
1972
|
+
* ```
|
|
1973
|
+
*/
|
|
1974
|
+
const UserButton = Object.assign(UserButtonRoot, {
|
|
1975
|
+
MenuItems,
|
|
1976
|
+
Action,
|
|
1977
|
+
Link,
|
|
1978
|
+
Custom,
|
|
1979
|
+
Header
|
|
1980
|
+
});
|
|
1981
|
+
//#endregion
|
|
1982
|
+
//#region src/live-authz.ts
|
|
1983
|
+
const DEFAULT_POLL_MS = 6e4;
|
|
1984
|
+
const DEFAULT_FOCUS_THROTTLE_MS = 5e3;
|
|
1985
|
+
/** Wire the triggers and return a handle. Safe to call with no window/document (SSR → no-op wiring). */
|
|
1986
|
+
function startLiveAuthz(opts) {
|
|
1987
|
+
const pollMs = opts.pollMs ?? DEFAULT_POLL_MS;
|
|
1988
|
+
const throttleMs = opts.focusThrottleMs ?? DEFAULT_FOCUS_THROTTLE_MS;
|
|
1989
|
+
const win = opts.win ?? (typeof window !== "undefined" ? window : void 0);
|
|
1990
|
+
const doc = opts.doc ?? (typeof document !== "undefined" ? document : void 0);
|
|
1991
|
+
let stopped = false;
|
|
1992
|
+
let inFlight = false;
|
|
1993
|
+
let pending = false;
|
|
1994
|
+
let lastRefreshAt = -Infinity;
|
|
1995
|
+
/**
|
|
1996
|
+
* Single-flight refresh (FR-LIVE-5). `coalesce` = queue exactly one follow-up run if a refresh
|
|
1997
|
+
* is already in flight — used by the explicit push signal so a change mid-refresh isn't missed.
|
|
1998
|
+
* Ambient triggers (focus/online/poll) pass `false`: if a refresh is already running, drop —
|
|
1999
|
+
* they carry no new information the in-flight run won't already pick up.
|
|
2000
|
+
*/
|
|
2001
|
+
async function run(coalesce) {
|
|
2002
|
+
if (stopped) return;
|
|
2003
|
+
if (inFlight) {
|
|
2004
|
+
if (coalesce) pending = true;
|
|
2005
|
+
return;
|
|
2006
|
+
}
|
|
2007
|
+
inFlight = true;
|
|
2008
|
+
try {
|
|
2009
|
+
let changed = false;
|
|
2010
|
+
try {
|
|
2011
|
+
changed = await opts.refresh();
|
|
2012
|
+
} catch {}
|
|
2013
|
+
lastRefreshAt = Date.now();
|
|
2014
|
+
if (changed && !stopped) opts.onChanged?.();
|
|
2015
|
+
} finally {
|
|
2016
|
+
inFlight = false;
|
|
2017
|
+
if (pending && !stopped) {
|
|
2018
|
+
pending = false;
|
|
2019
|
+
run(true);
|
|
2020
|
+
}
|
|
2021
|
+
}
|
|
2022
|
+
}
|
|
2023
|
+
/** Throttled, non-queuing refresh for ambient triggers (focus/visible/online). */
|
|
2024
|
+
function throttledRun() {
|
|
2025
|
+
if (Date.now() - lastRefreshAt >= throttleMs) run(false);
|
|
2026
|
+
}
|
|
2027
|
+
const isVisible = () => !doc || doc.visibilityState !== "hidden";
|
|
2028
|
+
const onFocus = () => throttledRun();
|
|
2029
|
+
const onOnline = () => throttledRun();
|
|
2030
|
+
const onVisibility = () => {
|
|
2031
|
+
if (isVisible()) throttledRun();
|
|
2032
|
+
};
|
|
2033
|
+
if (win) {
|
|
2034
|
+
win.addEventListener("focus", onFocus);
|
|
2035
|
+
win.addEventListener("online", onOnline);
|
|
2036
|
+
}
|
|
2037
|
+
if (doc) doc.addEventListener("visibilitychange", onVisibility);
|
|
2038
|
+
const unsubscribeSignal = opts.subscribeSignal?.(() => void run(true));
|
|
2039
|
+
let pollTimer;
|
|
2040
|
+
if (pollMs > 0) pollTimer = setInterval(() => {
|
|
2041
|
+
if (isVisible()) run(false);
|
|
2042
|
+
}, pollMs);
|
|
2043
|
+
return {
|
|
2044
|
+
refreshNow: () => void run(true),
|
|
2045
|
+
stop: () => {
|
|
2046
|
+
if (stopped) return;
|
|
2047
|
+
stopped = true;
|
|
2048
|
+
if (win) {
|
|
2049
|
+
win.removeEventListener("focus", onFocus);
|
|
2050
|
+
win.removeEventListener("online", onOnline);
|
|
2051
|
+
}
|
|
2052
|
+
if (doc) doc.removeEventListener("visibilitychange", onVisibility);
|
|
2053
|
+
unsubscribeSignal?.();
|
|
2054
|
+
if (pollTimer !== void 0) clearInterval(pollTimer);
|
|
2055
|
+
}
|
|
2056
|
+
};
|
|
2057
|
+
}
|
|
2058
|
+
//#endregion
|
|
2059
|
+
//#region src/live-session.ts
|
|
2060
|
+
/**
|
|
2061
|
+
* @poly-x/react/live-session — the React glue that keeps the BFF session live (SDK v2).
|
|
2062
|
+
*
|
|
2063
|
+
* `useLiveAuthz` starts the framework-agnostic orchestrator (`startLiveAuthz`, F013) bound to the
|
|
2064
|
+
* BFF session store's `refresh()`: the platform `authz:changed` signal (when a `subscribeSignal`
|
|
2065
|
+
* transport is supplied) + window focus/reconnect + a ~60s safety poll → a single-flight
|
|
2066
|
+
* re-introspect that updates reactive `useUser()`. `useAuthzChanged` lets an app with its own guard
|
|
2067
|
+
* layer react to a change (FR-REACT-1). Apps that gate on `useUser()` re-guard automatically
|
|
2068
|
+
* (FR-REACT-2) — they need no callback.
|
|
2069
|
+
*
|
|
2070
|
+
* The `subscribeSignal` transport is optional: without it the passive triggers still converge
|
|
2071
|
+
* (FR-SIG-4). The default poly-alert transport is provided separately (a later slice) once the
|
|
2072
|
+
* subscription-credential custody decision lands.
|
|
2073
|
+
*/
|
|
2074
|
+
const changeListeners = /* @__PURE__ */ new Set();
|
|
2075
|
+
function emitChanged() {
|
|
2076
|
+
for (const listener of changeListeners) listener();
|
|
2077
|
+
}
|
|
2078
|
+
/**
|
|
2079
|
+
* Start the live-authz orchestrator for this app's BFF session. Mount once (e.g. in the app root).
|
|
2080
|
+
* Returns nothing; drives `useUser()` reactivity + fires `useAuthzChanged` callbacks on a change.
|
|
2081
|
+
*/
|
|
2082
|
+
function useLiveAuthz(options = {}) {
|
|
2083
|
+
const { subscribeSignal, pollMs, focusThrottleMs } = options;
|
|
2084
|
+
useEffect(() => {
|
|
2085
|
+
const store = getBffSessionStore();
|
|
2086
|
+
const handle = startLiveAuthz({
|
|
2087
|
+
refresh: () => store.refresh(),
|
|
2088
|
+
onChanged: emitChanged,
|
|
2089
|
+
subscribeSignal,
|
|
2090
|
+
pollMs,
|
|
2091
|
+
focusThrottleMs
|
|
2092
|
+
});
|
|
2093
|
+
return () => handle.stop();
|
|
2094
|
+
}, [
|
|
2095
|
+
subscribeSignal,
|
|
2096
|
+
pollMs,
|
|
2097
|
+
focusThrottleMs
|
|
2098
|
+
]);
|
|
2099
|
+
}
|
|
2100
|
+
/**
|
|
2101
|
+
* Register a callback fired when the user's authorization changes (FR-REACT-1) — for apps that keep
|
|
2102
|
+
* their own ability/route model and need to re-run their guard or refetch view data. Apps that gate
|
|
2103
|
+
* on `useUser()` do not need this. Requires `useLiveAuthz` to be mounted somewhere in the tree.
|
|
2104
|
+
*/
|
|
2105
|
+
function useAuthzChanged(callback) {
|
|
2106
|
+
useEffect(() => {
|
|
2107
|
+
changeListeners.add(callback);
|
|
2108
|
+
return () => {
|
|
2109
|
+
changeListeners.delete(callback);
|
|
2110
|
+
};
|
|
2111
|
+
}, [callback]);
|
|
2112
|
+
}
|
|
2113
|
+
//#endregion
|
|
1251
2114
|
//#region src/index.ts
|
|
1252
2115
|
/**
|
|
1253
2116
|
* @poly-x/react — PolyX SDK for React SPAs. Sign-in UI + orchestration land in
|
|
@@ -1256,4 +2119,4 @@ function AuthCallback({ children = null }) {
|
|
|
1256
2119
|
const PACKAGE_NAME = "@poly-x/react";
|
|
1257
2120
|
const version = "0.0.0";
|
|
1258
2121
|
//#endregion
|
|
1259
|
-
export { AuthCallback, BroadcastAuthChannel, BroadcastChannelSessionChannel, ForgotPassword, PACKAGE_NAME, PolyXContext, PolyXProvider, PopupCancelledError, Protected, ResetPassword, SessionStoragePkceStore, SignIn, WebLocksLock, WindowBrowserBridge, createLoginController, useAuth, useAuthCallback, useSession, useUser, version };
|
|
2122
|
+
export { AuthCallback, BroadcastAuthChannel, BroadcastChannelSessionChannel, ForgotPassword, PACKAGE_NAME, PolyXContext, PolyXProvider, PopupCancelledError, Protected, ResetPassword, SessionStoragePkceStore, SignIn, UserAvatar, UserButton, WebLocksLock, WindowBrowserBridge, capturePreciseLocation, createLoginController, initialsFrom, resolveSide, startLiveAuthz, useAuth, useAuthCallback, useAuthzChanged, useLiveAuthz, useSession, useUser, version };
|