@oxyhq/core 7.0.0 → 7.1.1

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.
@@ -0,0 +1,621 @@
1
+ /**
2
+ * Headless controller for the unified Oxy account dialog.
3
+ *
4
+ * A framework-agnostic state machine + subscribe/getSnapshot store (the same
5
+ * pattern {@link SessionClient} uses — no React, no RN) that both
6
+ * `@oxyhq/services` (RN `OxyProvider`) and `@oxyhq/auth` (web `WebOxyProvider`)
7
+ * bind to via `useSyncExternalStore`, so the account chooser is ONE
8
+ * implementation across the ecosystem instead of the five drifting copies it
9
+ * replaces.
10
+ *
11
+ * The controller owns:
12
+ * - the unified account list (via {@link projectSwitchableAccounts}), fetched
13
+ * from `SessionClient` state ∪ `oxyServices.listAccounts()` and hydrated
14
+ * with `oxyServices.getUsersByIds()`;
15
+ * - the dialog `view` state machine (`accounts` | `signin` | `qr` | `add`);
16
+ * - `switchTo` (the uniform switch: `SessionClient.switchAccount` for an
17
+ * account already on the device, `oxyServices.switchToAccount` to mint on
18
+ * first entry into a graph account — reusing the existing SDK primitives, no
19
+ * new switch path);
20
+ * - the "Sign in with Oxy" device flow (same-device shared-keychain via
21
+ * `oxyServices.signInWithSharedIdentity`, else the cross-device QR handoff
22
+ * via `startCommonsSignIn` → poll → `claimSessionByToken`).
23
+ *
24
+ * It deliberately owns NO password/2FA logic — those live at the IdP
25
+ * (auth.oxy.so). {@link AccountDialogController.openPasswordAtOxyAuth} only
26
+ * builds the hand-off URL; device-first convergence syncs the session back.
27
+ */
28
+ import { logger } from '../utils/loggerUtils.js';
29
+ import { CENTRAL_IDP_APEX } from '../utils/authWebUrl.js';
30
+ import { projectSwitchableAccounts, switchableAccountIds, } from './accountProjection.js';
31
+ const DEFAULT_POLL_INTERVAL_MS = 3000;
32
+ const IDLE_SIGN_IN = {
33
+ phase: 'idle',
34
+ authorizeCode: null,
35
+ qrPayload: null,
36
+ expiresAt: null,
37
+ error: null,
38
+ };
39
+ function errorMessage(error) {
40
+ return error instanceof Error ? error.message : String(error);
41
+ }
42
+ export class AccountDialogController {
43
+ constructor(options) {
44
+ this.listeners = new Set();
45
+ // --- Internal (unprojected) state ---
46
+ this.view = 'accounts';
47
+ this.graph = [];
48
+ this.profilesById = new Map();
49
+ this.loading = false;
50
+ this.error = null;
51
+ this.switchingAccountId = null;
52
+ this.signIn = IDLE_SIGN_IN;
53
+ // --- Sign-in device-flow bookkeeping ---
54
+ /** The secret device-flow token of the active QR flow (never surfaced). */
55
+ this.signInToken = null;
56
+ this.pollTimer = null;
57
+ // --- Store plumbing ---
58
+ this.unsubscribeSession = null;
59
+ this.unsubscribeTokens = null;
60
+ /** Last-observed SDK auth readiness (a planted bearer). Drives the fetch edge. */
61
+ this.authed = false;
62
+ this.started = false;
63
+ this.refreshSeq = 0;
64
+ this.oxyServices = options.oxyServices;
65
+ this.sessionClient = options.sessionClient;
66
+ this.clientId = options.clientId ?? null;
67
+ this.locale = options.locale;
68
+ this.commitSession = options.commitSession;
69
+ this.onSignedIn = options.onSignedIn;
70
+ this.idpApex = options.idpApex ?? CENTRAL_IDP_APEX;
71
+ this.pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
72
+ this.openUrl = options.openUrl;
73
+ this.snapshot = this.computeSnapshot();
74
+ }
75
+ // =========================================================================
76
+ // Store surface (useSyncExternalStore)
77
+ // =========================================================================
78
+ /** Returns the current immutable snapshot (stable reference between changes). */
79
+ getSnapshot() {
80
+ return this.snapshot;
81
+ }
82
+ /** Subscribe to snapshot changes. Returns an unsubscribe function. */
83
+ subscribe(listener) {
84
+ this.listeners.add(listener);
85
+ return () => {
86
+ this.listeners.delete(listener);
87
+ };
88
+ }
89
+ // =========================================================================
90
+ // Lifecycle
91
+ // =========================================================================
92
+ /**
93
+ * Begin driving the dialog: subscribe to `SessionClient` state and load the
94
+ * account list. Idempotent — a second `start()` is a no-op. Pair with
95
+ * {@link destroy}.
96
+ */
97
+ start() {
98
+ if (this.started)
99
+ return;
100
+ this.started = true;
101
+ this.authed = this.isAuthenticated();
102
+ this.unsubscribeSession = this.sessionClient.subscribe(() => {
103
+ // A device-state change (switch / sign-out / sibling sign-in) can add or
104
+ // remove accounts — re-project immediately, refetch profiles when new
105
+ // account ids appeared, and reconcile the auth-readiness edge.
106
+ this.emit();
107
+ void this.ensureProfiles();
108
+ this.reconcileAuth();
109
+ });
110
+ // The access token is planted AFTER `SessionClient.applyState` fires its
111
+ // subscription (`applySync` calls `setTokens` only once `applyState`/notify
112
+ // has returned; `ensureActiveToken` plants it async later), so the
113
+ // device-state subscription alone cannot observe the signed-out → signed-in
114
+ // edge. Observe the SDK-canonical readiness signal directly — a change to
115
+ // `oxyServices.getAccessToken()`, the `hasAccessToken` term of
116
+ // `OxyContext.canUsePrivateApi`.
117
+ this.unsubscribeTokens = this.oxyServices.onTokensChanged(() => {
118
+ this.reconcileAuth();
119
+ });
120
+ // Initial projection is device-only. `refresh()` fetches the graph IFF a
121
+ // bearer is already planted (warm start); when signed out (cold boot before
122
+ // restore) it re-projects from device state and makes NO private call.
123
+ void this.refresh();
124
+ }
125
+ /**
126
+ * Stop driving the dialog: unsubscribe from `SessionClient` and tear down the
127
+ * active sign-in flow (timers). Idempotent.
128
+ */
129
+ destroy() {
130
+ this.started = false;
131
+ if (this.unsubscribeSession) {
132
+ this.unsubscribeSession();
133
+ this.unsubscribeSession = null;
134
+ }
135
+ if (this.unsubscribeTokens) {
136
+ this.unsubscribeTokens();
137
+ this.unsubscribeTokens = null;
138
+ }
139
+ this.clearPollTimer();
140
+ this.listeners.clear();
141
+ }
142
+ // =========================================================================
143
+ // Auth readiness (SDK-canonical — mirrors OxyContext.canUsePrivateApi)
144
+ // =========================================================================
145
+ /**
146
+ * Whether a PRIVATE endpoint may be called right now. Mirrors the
147
+ * `hasAccessToken` term of `OxyContext.canUsePrivateApi`
148
+ * (`authResolved && isAuthenticated && tokenReady && hasAccessToken`, where
149
+ * `hasAccessToken = Boolean(oxyServices.getAccessToken())`): a planted bearer
150
+ * is the only term that decides whether a request carries auth — the other
151
+ * three are provider render-lifecycle gates with no headless equivalent.
152
+ *
153
+ * `listAccounts()` (`GET /accounts`) and `getUsersByIds()`
154
+ * (`POST /users/by-ids`) are private; calling either before cold-boot restore
155
+ * plants the token 401s → `HttpService` clears the bearer + emits
156
+ * `onTokensChanged(null)` → the app signs out. Every graph/profile fetch gates
157
+ * on this.
158
+ */
159
+ isAuthenticated() {
160
+ return Boolean(this.oxyServices.getAccessToken());
161
+ }
162
+ /**
163
+ * Reconcile the account graph against the current auth-readiness edge. On the
164
+ * signed-out → signed-in edge fetch the graph ONCE; on signed-in → signed-out
165
+ * drop it and re-project device-only. A no-op when readiness is unchanged, so
166
+ * a burst of token events / device pushes cannot restart the fetch — and a
167
+ * failed `listAccounts()` never flips the edge, so it cannot re-trigger itself
168
+ * (no retry storm).
169
+ */
170
+ reconcileAuth() {
171
+ const authed = this.isAuthenticated();
172
+ if (authed === this.authed)
173
+ return;
174
+ this.authed = authed;
175
+ if (authed) {
176
+ void this.refresh();
177
+ return;
178
+ }
179
+ // Signed out: the graph is no longer fetchable/switchable — drop it and
180
+ // re-project from the device session set alone.
181
+ this.graph = [];
182
+ this.error = null;
183
+ this.loading = false;
184
+ this.emit();
185
+ }
186
+ // =========================================================================
187
+ // View actions
188
+ // =========================================================================
189
+ /** Set the dialog view directly. */
190
+ setView(view) {
191
+ if (this.view === view)
192
+ return;
193
+ this.view = view;
194
+ this.emit();
195
+ }
196
+ /** Return to the account list and cancel any in-flight sign-in flow. */
197
+ close() {
198
+ this.cancelSignIn();
199
+ this.setView('accounts');
200
+ }
201
+ /** Switch to the "add account" view (the sign-in entry chooser). */
202
+ add() {
203
+ this.setView('add');
204
+ }
205
+ // =========================================================================
206
+ // Account list
207
+ // =========================================================================
208
+ /**
209
+ * Reload the account graph and per-account profiles, then re-project. Safe to
210
+ * call repeatedly; concurrent calls are reconciled by a sequence guard so a
211
+ * slow earlier fetch never overwrites a newer result.
212
+ */
213
+ async refresh() {
214
+ const seq = ++this.refreshSeq;
215
+ // Never hit the private `listAccounts()` while signed out: at cold boot the
216
+ // bearer is not planted yet, so the call 401s → `HttpService` clears the
217
+ // token and signs the user out. Re-project from the device session set alone
218
+ // (`projectSwitchableAccounts` works from `SessionClient` state) and stop.
219
+ if (!this.isAuthenticated()) {
220
+ this.graph = [];
221
+ this.loading = false;
222
+ this.error = null;
223
+ this.emit();
224
+ return;
225
+ }
226
+ const hadAccounts = this.snapshot.accounts.length > 0;
227
+ this.loading = !hadAccounts;
228
+ this.error = null;
229
+ this.emit();
230
+ let graph = this.graph;
231
+ try {
232
+ graph = await this.oxyServices.listAccounts();
233
+ }
234
+ catch (error) {
235
+ // A graph-load failure is non-fatal: device rows still render. Surface the
236
+ // message but keep going with whatever graph we already had.
237
+ this.error = errorMessage(error);
238
+ logger.warn('[AccountDialogController] listAccounts failed', { component: 'AccountDialogController' }, error);
239
+ }
240
+ if (seq !== this.refreshSeq)
241
+ return; // superseded by a newer refresh
242
+ this.graph = graph;
243
+ await this.loadProfiles(seq);
244
+ if (seq !== this.refreshSeq)
245
+ return;
246
+ this.loading = false;
247
+ this.emit();
248
+ }
249
+ /**
250
+ * Fetch profiles for any account id (device set ∪ graph) not yet resolved.
251
+ * Cheap no-op when everything is already hydrated — used from the session
252
+ * subscription so a newly-added device account gets a name/avatar.
253
+ */
254
+ async ensureProfiles() {
255
+ // `getUsersByIds` is private — skip the whole path while signed out.
256
+ if (!this.isAuthenticated())
257
+ return;
258
+ const ids = switchableAccountIds(this.sessionClient.getState(), this.graph);
259
+ if (ids.every((id) => this.profilesById.has(id)))
260
+ return;
261
+ await this.loadProfiles(this.refreshSeq);
262
+ this.emit();
263
+ }
264
+ async loadProfiles(seq) {
265
+ // `getUsersByIds` (`POST /users/by-ids`) is a private call — never issue it
266
+ // while signed out (the 401 → sign-out cascade). Callers already gate; this
267
+ // guards the network chokepoint too (e.g. the token was cleared mid-refresh).
268
+ if (!this.isAuthenticated())
269
+ return;
270
+ const ids = switchableAccountIds(this.sessionClient.getState(), this.graph);
271
+ if (ids.length === 0)
272
+ return;
273
+ let profiles = [];
274
+ try {
275
+ profiles = await this.oxyServices.getUsersByIds(ids);
276
+ }
277
+ catch (error) {
278
+ // `getUsersByIds` already swallows per-chunk failures and returns `[]`;
279
+ // this guards the unexpected total failure. Non-fatal — keep prior map.
280
+ logger.warn('[AccountDialogController] getUsersByIds failed', { component: 'AccountDialogController' }, error);
281
+ return;
282
+ }
283
+ if (seq !== this.refreshSeq)
284
+ return; // superseded
285
+ const next = new Map(this.profilesById);
286
+ for (const profile of profiles) {
287
+ next.set(profile.id, profile);
288
+ }
289
+ this.profilesById = next;
290
+ }
291
+ // =========================================================================
292
+ // Switching (uniform switch model — reuses the existing SDK primitives)
293
+ // =========================================================================
294
+ /**
295
+ * Switch the active account to `accountId`.
296
+ *
297
+ * Uniform switch model, mirroring the SDK's existing path — NOT a new switch
298
+ * mechanism:
299
+ * - already on this device → `SessionClient.switchAccount` (device-first
300
+ * switch of `/session/device/switch`);
301
+ * - a graph account not yet on the device (first entry) →
302
+ * `oxyServices.switchToAccount` mints + plants a real session and the
303
+ * server registers it into the device set, then it is committed
304
+ * (`commitSession` when supplied, else `SessionClient.registerAndActivate`).
305
+ *
306
+ * The resulting device-state change flows back through the `SessionClient`
307
+ * subscription, which re-projects the active row. Concurrent switches are
308
+ * ignored while one is in flight.
309
+ */
310
+ async switchTo(accountId) {
311
+ if (this.switchingAccountId)
312
+ return;
313
+ this.switchingAccountId = accountId;
314
+ this.error = null;
315
+ this.emit();
316
+ try {
317
+ const state = this.sessionClient.getState();
318
+ const onDevice = state?.accounts.some((account) => account.accountId === accountId) ?? false;
319
+ if (onDevice) {
320
+ await this.sessionClient.switchAccount(accountId);
321
+ }
322
+ else {
323
+ const result = await this.oxyServices.switchToAccount(accountId);
324
+ if (!result?.user || !result?.sessionId) {
325
+ throw new Error('Account switch did not return a valid session');
326
+ }
327
+ await this.commitAuthorizedSession({
328
+ sessionId: result.sessionId,
329
+ deviceId: result.deviceId,
330
+ expiresAt: result.expiresAt,
331
+ user: result.user,
332
+ accessToken: result.accessToken,
333
+ ...(readRefreshToken(result) ? { refreshToken: readRefreshToken(result) } : {}),
334
+ }, result.user);
335
+ }
336
+ // Re-project + refetch immediately; the subscription also fires.
337
+ await this.refresh();
338
+ }
339
+ catch (error) {
340
+ this.error = errorMessage(error);
341
+ }
342
+ finally {
343
+ this.switchingAccountId = null;
344
+ this.emit();
345
+ }
346
+ }
347
+ // =========================================================================
348
+ // Sign in with Oxy (device flow — shared keychain, else cross-device QR)
349
+ // =========================================================================
350
+ /**
351
+ * Start "Sign in with Oxy". Native devices with a shared identity mint a
352
+ * session silently (`signInWithSharedIdentity`); everything else (web, or a
353
+ * native device without a shared identity) falls through to the cross-device
354
+ * QR handoff.
355
+ */
356
+ async signInWithOxy() {
357
+ this.setView('qr');
358
+ this.setSignIn({ ...IDLE_SIGN_IN, phase: 'starting' });
359
+ try {
360
+ const session = await this.oxyServices.signInWithSharedIdentity();
361
+ if (session) {
362
+ await this.completeSignIn(session, session.user);
363
+ return;
364
+ }
365
+ }
366
+ catch (error) {
367
+ // Shared-key mint failed — log and fall through to the QR handoff rather
368
+ // than dead-ending the sign-in.
369
+ logger.warn('[AccountDialogController] signInWithSharedIdentity failed', { component: 'AccountDialogController' }, error);
370
+ }
371
+ await this.showQr();
372
+ }
373
+ /**
374
+ * Begin (or restart) the cross-device QR handoff: create a device-flow
375
+ * session, surface its `authorizeCode` + `qrPayload`, and poll for approval.
376
+ * On approval the secret token is exchanged (`claimSessionByToken`) and the
377
+ * session committed. Requires `clientId`.
378
+ */
379
+ async showQr() {
380
+ this.cancelSignIn();
381
+ this.setView('qr');
382
+ if (!this.clientId) {
383
+ this.setSignIn({ ...IDLE_SIGN_IN, phase: 'error', error: 'This app is not configured for sign-in (missing clientId).' });
384
+ return;
385
+ }
386
+ this.setSignIn({ ...IDLE_SIGN_IN, phase: 'starting' });
387
+ try {
388
+ const handle = await this.oxyServices.startCommonsSignIn({ clientId: this.clientId });
389
+ this.signInToken = handle.sessionToken;
390
+ this.setSignIn({
391
+ phase: 'waiting',
392
+ authorizeCode: handle.authorizeCode,
393
+ qrPayload: handle.qrPayload,
394
+ expiresAt: handle.expiresAt,
395
+ error: null,
396
+ });
397
+ this.scheduleNextPoll(handle.sessionToken);
398
+ }
399
+ catch (error) {
400
+ this.setSignIn({ ...IDLE_SIGN_IN, phase: 'error', error: errorMessage(error) });
401
+ }
402
+ }
403
+ /** Tear down the active sign-in device flow (timers + token) and reset to idle. */
404
+ cancelSignIn() {
405
+ this.clearPollTimer();
406
+ this.signInToken = null;
407
+ if (this.signIn !== IDLE_SIGN_IN) {
408
+ this.setSignIn(IDLE_SIGN_IN);
409
+ }
410
+ }
411
+ /**
412
+ * Build (and, when an `openUrl` handler was supplied, open) the auth.oxy.so
413
+ * password sign-in URL. Password + 2FA are NOT in the SDK — they live at the
414
+ * IdP; this only hands off. Device-first: after login at the IdP the device
415
+ * session converges and the caller is woken via the device socket /
416
+ * `BroadcastChannel`, so the URL only needs to point at the IdP sign-in with
417
+ * the right return.
418
+ *
419
+ * @param params.returnUrl - Where the IdP returns after login. Defaults to the
420
+ * current document URL on web (`globalThis.location.href`); pass explicitly
421
+ * on native (no `location`).
422
+ * @param params.state - Optional opaque state echoed back on return.
423
+ * @returns The absolute auth.oxy.so sign-in URL.
424
+ */
425
+ openPasswordAtOxyAuth(params = {}) {
426
+ const base = `https://auth.${this.idpApex}`;
427
+ const url = new URL('/login', base);
428
+ const returnUrl = params.returnUrl ?? currentLocationHref();
429
+ if (returnUrl) {
430
+ url.searchParams.set('redirect_uri', returnUrl);
431
+ }
432
+ if (this.clientId) {
433
+ url.searchParams.set('client_id', this.clientId);
434
+ }
435
+ if (params.state) {
436
+ url.searchParams.set('state', params.state);
437
+ }
438
+ const href = url.toString();
439
+ this.openUrl?.(href);
440
+ return href;
441
+ }
442
+ // =========================================================================
443
+ // Internal sign-in helpers
444
+ // =========================================================================
445
+ scheduleNextPoll(sessionToken) {
446
+ this.clearPollTimer();
447
+ this.pollTimer = setTimeout(() => {
448
+ void this.pollOnce(sessionToken);
449
+ }, this.pollIntervalMs);
450
+ }
451
+ async pollOnce(sessionToken) {
452
+ // A superseded / cancelled flow must not act.
453
+ if (this.signInToken !== sessionToken)
454
+ return;
455
+ const expiresAt = this.signIn.expiresAt;
456
+ if (typeof expiresAt === 'number' && Date.now() > expiresAt) {
457
+ this.failSignIn('Session expired. Please try again.');
458
+ return;
459
+ }
460
+ try {
461
+ const status = await this.oxyServices.pollCommonsSignIn(sessionToken);
462
+ if (this.signInToken !== sessionToken)
463
+ return; // cancelled mid-request
464
+ if (status.authorized && status.sessionId) {
465
+ this.clearPollTimer();
466
+ await this.claimAndComplete(status.sessionId, sessionToken);
467
+ return;
468
+ }
469
+ if (status.status === 'cancelled') {
470
+ this.failSignIn('Authorization was denied.');
471
+ return;
472
+ }
473
+ if (status.status === 'expired') {
474
+ this.failSignIn('Session expired. Please try again.');
475
+ return;
476
+ }
477
+ }
478
+ catch (error) {
479
+ // Transient poll error — the next tick retries. Logged, never thrown.
480
+ logger.debug('[AccountDialogController] poll error (will retry)', { component: 'AccountDialogController' }, error);
481
+ }
482
+ if (this.signInToken === sessionToken) {
483
+ this.scheduleNextPoll(sessionToken);
484
+ }
485
+ }
486
+ async claimAndComplete(sessionId, sessionToken) {
487
+ this.setSignIn({ ...this.signIn, phase: 'authorized' });
488
+ let claimed;
489
+ try {
490
+ claimed = await this.oxyServices.claimSessionByToken(sessionToken);
491
+ }
492
+ catch (error) {
493
+ this.failSignIn(errorMessage(error));
494
+ return;
495
+ }
496
+ if (!claimed?.accessToken || !claimed.user) {
497
+ this.failSignIn('Authorization succeeded but the session could not be claimed. Please try again.');
498
+ return;
499
+ }
500
+ // `SessionLoginResponse.user` is the minimal session-carried shape; the claim
501
+ // returns the full `User` (avatar is `string | null | undefined`). Normalize
502
+ // rather than widening the minimal shape to accept `null`.
503
+ const minimalUser = {
504
+ id: claimed.user.id,
505
+ username: claimed.user.username,
506
+ name: claimed.user.name,
507
+ avatar: claimed.user.avatar ?? undefined,
508
+ };
509
+ const refreshToken = readRefreshToken(claimed);
510
+ try {
511
+ await this.completeSignIn({
512
+ sessionId: claimed.sessionId || sessionId,
513
+ deviceId: claimed.deviceId ?? '',
514
+ expiresAt: claimed.expiresAt ?? '',
515
+ user: minimalUser,
516
+ accessToken: claimed.accessToken,
517
+ ...(refreshToken ? { refreshToken } : {}),
518
+ }, minimalUser);
519
+ }
520
+ catch (error) {
521
+ this.failSignIn(errorMessage(error));
522
+ }
523
+ }
524
+ /**
525
+ * Commit an authorized session, notify, and return to the account list. Shared
526
+ * by the shared-key, QR, and mint-switch paths so they cannot drift.
527
+ */
528
+ async completeSignIn(session, user) {
529
+ await this.commitAuthorizedSession(session, user);
530
+ this.signInToken = null;
531
+ this.clearPollTimer();
532
+ this.signIn = IDLE_SIGN_IN;
533
+ this.view = 'accounts';
534
+ this.emit();
535
+ this.onSignedIn?.(user);
536
+ await this.refresh();
537
+ }
538
+ /**
539
+ * Register a token-planted session into the device set. Prefers the
540
+ * consumer's `commitSession` (durable persist + hydration); falls back to
541
+ * `SessionClient.registerAndActivate` (registration + activation only).
542
+ */
543
+ async commitAuthorizedSession(session, user) {
544
+ if (this.commitSession) {
545
+ await this.commitSession(session);
546
+ }
547
+ else {
548
+ await this.sessionClient.registerAndActivate(user.id);
549
+ }
550
+ }
551
+ failSignIn(message) {
552
+ this.clearPollTimer();
553
+ this.signInToken = null;
554
+ this.setSignIn({ ...IDLE_SIGN_IN, phase: 'error', error: message });
555
+ }
556
+ clearPollTimer() {
557
+ if (this.pollTimer !== null) {
558
+ clearTimeout(this.pollTimer);
559
+ this.pollTimer = null;
560
+ }
561
+ }
562
+ // =========================================================================
563
+ // Snapshot plumbing
564
+ // =========================================================================
565
+ setSignIn(next) {
566
+ this.signIn = next;
567
+ this.emit();
568
+ }
569
+ computeSnapshot() {
570
+ const state = this.sessionClient.getState();
571
+ return {
572
+ view: this.view,
573
+ accounts: projectSwitchableAccounts({
574
+ state,
575
+ graph: this.graph,
576
+ profilesById: this.profilesById,
577
+ locale: this.locale,
578
+ resolveAvatarUrl: (avatar) => (avatar ? this.oxyServices.getFileDownloadUrl(avatar, 'thumb') : undefined),
579
+ }),
580
+ activeAccountId: state?.activeAccountId ?? null,
581
+ loading: this.loading,
582
+ error: this.error,
583
+ switchingAccountId: this.switchingAccountId,
584
+ signIn: this.signIn,
585
+ };
586
+ }
587
+ /** Recompute the snapshot and notify subscribers. */
588
+ emit() {
589
+ this.snapshot = this.computeSnapshot();
590
+ for (const listener of this.listeners) {
591
+ try {
592
+ listener(this.snapshot);
593
+ }
594
+ catch (error) {
595
+ logger.error('[AccountDialogController] subscriber threw', error);
596
+ }
597
+ }
598
+ }
599
+ }
600
+ /** Factory mirroring `createSessionClient`, for ergonomic wiring by consumers. */
601
+ export function createAccountDialogController(options) {
602
+ return new AccountDialogController(options);
603
+ }
604
+ // ---------------------------------------------------------------------------
605
+ // Local helpers
606
+ // ---------------------------------------------------------------------------
607
+ /**
608
+ * The rotating refresh-token family head is threaded on the runtime object by
609
+ * the trusted device-flow / switch lanes even though it is NOT on the typed
610
+ * return of `claimSessionByToken` / `switchToAccount`. Read it defensively so
611
+ * the commit funnel can persist a durable session.
612
+ */
613
+ function readRefreshToken(value) {
614
+ const token = value.refreshToken;
615
+ return typeof token === 'string' ? token : undefined;
616
+ }
617
+ /** Current document URL on web; empty string where `location` is absent (native/SSR). */
618
+ function currentLocationHref() {
619
+ const location = globalThis.location;
620
+ return typeof location?.href === 'string' ? location.href : '';
621
+ }