@returningai/react-native-widget-sdk 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.
Files changed (38) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/LICENSE +4 -0
  3. package/README.md +111 -0
  4. package/package.json +60 -0
  5. package/src/ReturningAIWidget.tsx +601 -0
  6. package/src/authentication/ReturningAIAccessTokenCache.ts +90 -0
  7. package/src/authentication/ReturningAIAuthenticationClient.ts +379 -0
  8. package/src/authentication/nonce.ts +26 -0
  9. package/src/authentication/sessionAuthClient.ts +35 -0
  10. package/src/authentication/types.ts +50 -0
  11. package/src/bridge/ReturningAIBridgeCodec.ts +452 -0
  12. package/src/bridge/ReturningAIBridgeIdentity.ts +87 -0
  13. package/src/configuration/ReturningAIFirstPaintColors.ts +46 -0
  14. package/src/configuration/ReturningAIWidgetConfiguration.ts +488 -0
  15. package/src/configuration/ReturningAIWidgetContent.ts +59 -0
  16. package/src/configuration/ReturningAIWidgetDescriptor.ts +54 -0
  17. package/src/configuration/ReturningAIWidgetDisplayOptions.ts +59 -0
  18. package/src/configuration/ReturningAIWidgetDomainKey.ts +44 -0
  19. package/src/configuration/ReturningAIWidgetEndpoints.ts +157 -0
  20. package/src/configuration/ReturningAIWidgetTheme.ts +25 -0
  21. package/src/configuration/urls.ts +133 -0
  22. package/src/controller/ReturningAIWidgetController.ts +149 -0
  23. package/src/controller/ReturningAIWidgetSessionSnapshot.ts +49 -0
  24. package/src/coordinator/ReturningAIWidgetCoordinator.ts +787 -0
  25. package/src/crypto/fillRandomBytes.ts +28 -0
  26. package/src/errors/ReturningAIWidgetError.ts +150 -0
  27. package/src/errors/json.ts +227 -0
  28. package/src/events/ReturningAIWidgetEvent.ts +131 -0
  29. package/src/index.ts +79 -0
  30. package/src/navigation/ReturningAINavigationPolicy.ts +89 -0
  31. package/src/packageInfo.ts +23 -0
  32. package/src/rendering/htmlRenderer.ts +351 -0
  33. package/src/rendering/theme.ts +57 -0
  34. package/src/webview/ReturningAIReactNativeWebViewDriver.ts +136 -0
  35. package/src/webview/ReturningAIWebViewDriver.ts +141 -0
  36. package/src/webview/bridgeBootstrap.ts +26 -0
  37. package/src/webview/errorPolicy.ts +27 -0
  38. package/src/webview/originWhitelist.ts +22 -0
@@ -0,0 +1,787 @@
1
+ /**
2
+ * @fileoverview Orchestrates auth, HTML render, bridge handling, navigation, and widget lifecycle state.
3
+ *
4
+ * Layer: coordinator
5
+ * Role: Drives idle→loading→ready/failed states; exchanges tokens, loads shell HTML, decodes bridge
6
+ * messages, invokes hostCallbacks, and applies navigation policy. Does not render React UI.
7
+ * Security: Embed token stays in JS memory + HTTPS body; WebView receives access token only;
8
+ * bridge identity and callback allowlists gate inbound messages.
9
+ * See also: ReturningAIWidget.tsx, bridge/ReturningAIBridgeCodec.ts, authentication/*
10
+ */
11
+
12
+ import { ReturningAIAccessTokenCache } from "../authentication/ReturningAIAccessTokenCache";
13
+ import {
14
+ ReturningAIAuthenticationClient,
15
+ type ReturningAIFetch,
16
+ } from "../authentication/ReturningAIAuthenticationClient";
17
+ import type {
18
+ ReturningAIAccessToken,
19
+ ReturningAIAuthenticationOperation,
20
+ ReturningAIClock,
21
+ ReturningAIEmbedTokenProvider,
22
+ } from "../authentication/types";
23
+ import {
24
+ ReturningAIAuthenticateRequest,
25
+ ReturningAIBridgeCodec,
26
+ ReturningAIEventBridgeMessage,
27
+ ReturningAIHostCallbackBridgeRequest,
28
+ } from "../bridge/ReturningAIBridgeCodec";
29
+ import { ReturningAIBridgeIdentity } from "../bridge/ReturningAIBridgeIdentity";
30
+ import { type ReturningAIWidgetConfiguration } from "../configuration/ReturningAIWidgetConfiguration";
31
+ import { ReturningAIWidgetTheme } from "../configuration/ReturningAIWidgetTheme";
32
+ import {
33
+ ReturningAIWidgetSessionPhase,
34
+ type ReturningAIWidgetSessionSnapshot,
35
+ } from "../controller/ReturningAIWidgetSessionSnapshot";
36
+ import { validateReturningAIJsonValue } from "../errors/json";
37
+ import { ReturningAIWidgetError } from "../errors/ReturningAIWidgetError";
38
+ import {
39
+ type ReturningAIHostCallbackHandler,
40
+ ReturningAIWidgetErrorEvent,
41
+ type ReturningAIWidgetEvent,
42
+ ReturningAIWidgetExternalNavigationRequested,
43
+ ReturningAIWidgetLoading,
44
+ ReturningAIWidgetLoggedOut,
45
+ ReturningAIWidgetMounted,
46
+ ReturningAIWidgetReady,
47
+ ReturningAIWidgetSessionExpired,
48
+ } from "../events/ReturningAIWidgetEvent";
49
+ import {
50
+ ReturningAINavigationAction,
51
+ ReturningAINavigationPolicy,
52
+ } from "../navigation/ReturningAINavigationPolicy";
53
+ import { renderReturningAIHtml } from "../rendering/htmlRenderer";
54
+ import type { ReturningAIResolvedTheme } from "../rendering/theme";
55
+ import {
56
+ returningAIDocumentBaseUrl,
57
+ type ReturningAIWebViewDriver,
58
+ } from "../webview/ReturningAIWebViewDriver";
59
+
60
+ /**
61
+ * Cancelable timer handle used for ready timeouts and tests.
62
+ */
63
+ export type ReturningAITimerHandle = {
64
+ /** Cancels the pending timer. */
65
+ cancel(): void;
66
+ };
67
+
68
+ /**
69
+ * Factory that schedules a one-shot timer and returns a cancel handle.
70
+ * @param delayMilliseconds - Delay before invoking `callback`
71
+ * @param callback - Zero-arg callback
72
+ * @returns Cancelable handle
73
+ */
74
+ export type ReturningAITimerFactory = (
75
+ delayMilliseconds: number,
76
+ callback: () => void,
77
+ ) => ReturningAITimerHandle;
78
+
79
+ /**
80
+ * Lifecycle states for {@link ReturningAIWidgetCoordinator}.
81
+ */
82
+ export const ReturningAIWidgetCoordinatorState = {
83
+ /** Constructed but not started. */
84
+ idle: "idle",
85
+ /** Shell loading / waiting for ready. */
86
+ loading: "loading",
87
+ /** Widget reported mounted/ready. */
88
+ ready: "ready",
89
+ /** Terminal failure (ready timeout or main-frame load error). */
90
+ failed: "failed",
91
+ /** Session torn down; cannot restart this instance. */
92
+ invalidated: "invalidated",
93
+ } as const;
94
+
95
+ /** Union of {@link ReturningAIWidgetCoordinatorState} values. */
96
+ export type ReturningAIWidgetCoordinatorState =
97
+ (typeof ReturningAIWidgetCoordinatorState)[keyof typeof ReturningAIWidgetCoordinatorState];
98
+
99
+ /** Injectable HTML renderer (defaults to {@link renderReturningAIHtml}). */
100
+ export type ReturningAIHtmlRenderFn = typeof renderReturningAIHtml;
101
+
102
+ /**
103
+ * Orchestrates auth, HTML render, bridge handling, navigation, and lifecycle for one session.
104
+ * Security: embed tokens stay in JS + HTTPS bodies; WebView receives access tokens only;
105
+ * invalidate cancels in-flight auth and drops the driver.
106
+ */
107
+ export class ReturningAIWidgetCoordinator {
108
+ private configuration: ReturningAIWidgetConfiguration;
109
+ private embedTokenProvider: ReturningAIEmbedTokenProvider | undefined;
110
+ private hostCallbacks: Record<string, ReturningAIHostCallbackHandler>;
111
+ private readonly onEvent: ((event: ReturningAIWidgetEvent) => void) | undefined;
112
+ private readonly onError: ((error: ReturningAIWidgetError) => void) | undefined;
113
+ private readonly onTerminalError: ((error: ReturningAIWidgetError) => void) | undefined;
114
+ private readonly onExternalNavigation: ((uri: URL) => void) | undefined;
115
+ private readonly clock: ReturningAIClock;
116
+ private readonly timerFactory: ReturningAITimerFactory;
117
+ private readonly renderer: ReturningAIHtmlRenderFn;
118
+ private readonly identityFactory: () => ReturningAIBridgeIdentity;
119
+ private identity: ReturningAIBridgeIdentity;
120
+ private readonly authenticationClient: ReturningAIAuthenticationClient;
121
+ private readonly tokenCache: ReturningAIAccessTokenCache;
122
+ private readonly sessionKey: string;
123
+
124
+ /** Current lifecycle state. */
125
+ state: ReturningAIWidgetCoordinatorState = ReturningAIWidgetCoordinatorState.idle;
126
+
127
+ private codec: ReturningAIBridgeCodec;
128
+ private driver: ReturningAIWebViewDriver | undefined;
129
+ private inFlightAuthentication: Promise<ReturningAIAccessToken> | undefined;
130
+ private activeAuthentication: ReturningAIAuthenticationOperation | undefined;
131
+ private readyTimer: ReturningAITimerHandle | undefined;
132
+ private documentLoadTail: Promise<void> = Promise.resolve();
133
+ private generation = 0;
134
+ private authenticationEpoch = 0;
135
+
136
+ /**
137
+ * Creates a coordinator for one widget session.
138
+ * @param input.configuration - Host configuration (validated on construct)
139
+ * @param input.embedTokenProvider - Optional host mint; embed token never enters HTML/bridge
140
+ * @param input.hostCallbacks - Name → handler map for allowlisted callbacks
141
+ * @param input.fetch - Optional auth transport
142
+ * @param input.onEvent - Lifecycle/event sink
143
+ * @param input.onError - Non-terminal error sink
144
+ * @param input.onTerminalError - Terminal failure sink (UI error state)
145
+ * @param input.onExternalNavigation - Host opens delegated URLs
146
+ * @param input.clock - Injectable clock
147
+ * @param input.timerFactory - Injectable timer
148
+ * @param input.renderer - Injectable HTML renderer
149
+ * @param input.identityFactory - Injectable bridge identity factory
150
+ * @param input.authenticationClient - Injectable auth client
151
+ */
152
+ constructor(input: {
153
+ configuration: ReturningAIWidgetConfiguration;
154
+ embedTokenProvider?: ReturningAIEmbedTokenProvider;
155
+ hostCallbacks?: Record<string, ReturningAIHostCallbackHandler>;
156
+ fetch?: ReturningAIFetch;
157
+ onEvent?: (event: ReturningAIWidgetEvent) => void;
158
+ onError?: (error: ReturningAIWidgetError) => void;
159
+ onTerminalError?: (error: ReturningAIWidgetError) => void;
160
+ onExternalNavigation?: (uri: URL) => void;
161
+ clock?: ReturningAIClock;
162
+ timerFactory?: ReturningAITimerFactory;
163
+ renderer?: ReturningAIHtmlRenderFn;
164
+ identityFactory?: () => ReturningAIBridgeIdentity;
165
+ authenticationClient?: ReturningAIAuthenticationClient;
166
+ }) {
167
+ this.configuration = input.configuration.validated();
168
+ this.embedTokenProvider = input.embedTokenProvider;
169
+ this.hostCallbacks = { ...(input.hostCallbacks ?? {}) };
170
+ this.onEvent = input.onEvent;
171
+ this.onError = input.onError;
172
+ this.onTerminalError = input.onTerminalError;
173
+ this.onExternalNavigation = input.onExternalNavigation;
174
+ this.clock = input.clock ?? (() => Date.now());
175
+ this.timerFactory =
176
+ input.timerFactory ??
177
+ ((delayMilliseconds, callback) => {
178
+ const handle = setTimeout(callback, Math.max(0, delayMilliseconds));
179
+ unrefTimer(handle);
180
+ return { cancel: () => clearTimeout(handle) };
181
+ });
182
+ this.renderer = input.renderer ?? renderReturningAIHtml;
183
+ this.identityFactory = input.identityFactory ?? (() => ReturningAIBridgeIdentity.generate());
184
+ this.identity = input.identityFactory?.() ?? ReturningAIBridgeIdentity.generate();
185
+ this.authenticationClient =
186
+ input.authenticationClient ??
187
+ new ReturningAIAuthenticationClient({
188
+ fetch: input.fetch,
189
+ clock: this.clock,
190
+ });
191
+ this.tokenCache = new ReturningAIAccessTokenCache({ clock: this.clock });
192
+ this.sessionKey = this.identity.instanceId;
193
+ this.codec = new ReturningAIBridgeCodec({
194
+ identity: this.identity,
195
+ callbackNames: this.registeredCallbackNames,
196
+ });
197
+ }
198
+
199
+ /** Union of config allowlist and currently registered host callback names. */
200
+ private get registeredCallbackNames(): Set<string> {
201
+ return new Set([...this.configuration.callbackNames, ...Object.keys(this.hostCallbacks)]);
202
+ }
203
+
204
+ /**
205
+ * Starts (or restarts) loading: emits loading, prefetches auth, renders HTML, loads the driver.
206
+ * @param driver - WebView driver for this session
207
+ * @throws {ReturningAIWidgetError} when the coordinator was already invalidated
208
+ */
209
+ async start(driver: ReturningAIWebViewDriver): Promise<void> {
210
+ await this.serializeDocumentLoad(() => this.startDocument(driver));
211
+ }
212
+
213
+ private serializeDocumentLoad(operation: () => Promise<void>): Promise<void> {
214
+ const task = this.documentLoadTail.then(operation);
215
+ this.documentLoadTail = task.catch(() => undefined);
216
+ return task;
217
+ }
218
+
219
+ private async startDocument(driver: ReturningAIWebViewDriver): Promise<void> {
220
+ if (this.state === ReturningAIWidgetCoordinatorState.invalidated) {
221
+ throw new ReturningAIWidgetError({
222
+ code: "invalidControllerState",
223
+ message: "An invalidated widget coordinator cannot be restarted.",
224
+ });
225
+ }
226
+ this.driver = driver;
227
+ if (this.generation > 0) {
228
+ this.identity = this.identityFactory();
229
+ }
230
+ this.generation += 1;
231
+ this.state = ReturningAIWidgetCoordinatorState.loading;
232
+ this.codec = new ReturningAIBridgeCodec({
233
+ identity: this.identity,
234
+ callbackNames: this.registeredCallbackNames,
235
+ });
236
+ this.emit(new ReturningAIWidgetLoading());
237
+ this.readyTimer?.cancel();
238
+ const startGeneration = this.generation;
239
+ this.readyTimer = this.timerFactory(this.configuration.readyTimeoutMilliseconds, () => {
240
+ if (
241
+ this.generation !== startGeneration ||
242
+ this.state !== ReturningAIWidgetCoordinatorState.loading
243
+ ) {
244
+ return;
245
+ }
246
+ this.fail(
247
+ new ReturningAIWidgetError({
248
+ code: "webViewLoadFailed",
249
+ message: "The widget did not become ready before the timeout.",
250
+ }),
251
+ );
252
+ });
253
+ void this.prefetchAuthentication(startGeneration);
254
+ const html = this.renderer({
255
+ configuration: this.configuration,
256
+ resolvedTheme: resolvedTheme(this.configuration.theme),
257
+ callbackNames: this.registeredCallbackNames,
258
+ bridgeIdentity: this.identity,
259
+ });
260
+ await driver.loadHtmlString(html, returningAIDocumentBaseUrl(this.configuration));
261
+ }
262
+
263
+ /**
264
+ * Decodes and dispatches one inbound bridge message (auth, callback, or event).
265
+ * @param raw - JSON string from the WebView
266
+ */
267
+ async handleBridgeMessage(raw: string): Promise<void> {
268
+ if (this.state === ReturningAIWidgetCoordinatorState.invalidated) {
269
+ return;
270
+ }
271
+ const generation = this.generation;
272
+ try {
273
+ const message = this.codec.decode(raw);
274
+ if (message === undefined) {
275
+ return;
276
+ }
277
+ if (message instanceof ReturningAIAuthenticateRequest) {
278
+ await this.handleAuthentication(message, generation);
279
+ return;
280
+ }
281
+ if (message instanceof ReturningAIHostCallbackBridgeRequest) {
282
+ await this.handleCallback(message, generation);
283
+ return;
284
+ }
285
+ if (message instanceof ReturningAIEventBridgeMessage) {
286
+ this.handleEvent(message.event);
287
+ }
288
+ } catch (error) {
289
+ if (error instanceof ReturningAIWidgetError) {
290
+ this.emitError(error);
291
+ return;
292
+ }
293
+ throw error;
294
+ }
295
+ }
296
+
297
+ /**
298
+ * Restarts the document with fresh bridge identity on the existing WebView.
299
+ * @throws {ReturningAIWidgetError} when invalidated
300
+ */
301
+ async reload(): Promise<void> {
302
+ await this.retry();
303
+ }
304
+
305
+ /**
306
+ * Clears session work and restarts against the same driver after a failure.
307
+ * @throws {ReturningAIWidgetError} when invalidated
308
+ */
309
+ async retry(): Promise<void> {
310
+ await this.serializeDocumentLoad(async () => {
311
+ this.requireLive();
312
+ const driver = this.driver;
313
+ if (driver === undefined) return;
314
+ this.clearSessionWork();
315
+ await this.startDocument(driver);
316
+ });
317
+ }
318
+
319
+ /**
320
+ * Pushes a theme update into the live WebView shell.
321
+ * @param theme - Preference (system treated as light here; RN resolves before call)
322
+ * @throws {ReturningAIWidgetError} when invalidated
323
+ */
324
+ async updateTheme(
325
+ theme: (typeof ReturningAIWidgetTheme)[keyof typeof ReturningAIWidgetTheme],
326
+ ): Promise<void> {
327
+ this.requireLive();
328
+ const resolved = resolvedTheme(theme);
329
+ await this.driver?.runJavaScript(`window.__returningAIUpdateTheme("${resolved}");`);
330
+ }
331
+
332
+ /**
333
+ * Soft-logs out: clears the native access-token cache and asks the runtime to logout.
334
+ * Does not dispose the WebView. The shell helper prefers element `logoutPublic`,
335
+ * then `window.ReturningAIWidget.logout`, else dispatches `rai-logout`.
336
+ * @throws {ReturningAIWidgetError} when invalidated
337
+ */
338
+ async logout(): Promise<void> {
339
+ this.requireLive();
340
+ this.clearAuthentication();
341
+ const driver = this.driver;
342
+ if (driver === undefined) {
343
+ this.emit(new ReturningAIWidgetLoggedOut());
344
+ return;
345
+ }
346
+ await driver.runJavaScript(
347
+ "void (window.__returningAILogout && window.__returningAILogout());",
348
+ );
349
+ }
350
+
351
+ /** Whether a usable cached access token remains (more than 30s until expiry). */
352
+ get isAuthenticated(): boolean {
353
+ return this.tokenCache.get(this.sessionKey) !== undefined;
354
+ }
355
+
356
+ /** Redacted session phase + auth presence for hosts. Never includes token values. */
357
+ get sessionSnapshot(): ReturningAIWidgetSessionSnapshot {
358
+ const expiresAtMillis = this.tokenCache.expiresAtMillis(this.sessionKey);
359
+ return {
360
+ phase: sessionPhaseFor(this.state),
361
+ isAuthenticated: this.isAuthenticated,
362
+ accessTokenExpiresAt: expiresAtMillis === undefined ? undefined : new Date(expiresAtMillis),
363
+ };
364
+ }
365
+
366
+ /**
367
+ * Hot-updates embed-token provider and/or host callback map without a new session.
368
+ * @param input.embedTokenProvider - Replacement provider (may be `undefined`)
369
+ * @param input.hostCallbacks - Replacement handler map
370
+ */
371
+ updateHandlers(
372
+ input: {
373
+ embedTokenProvider?: ReturningAIEmbedTokenProvider;
374
+ hostCallbacks?: Record<string, ReturningAIHostCallbackHandler>;
375
+ } = {},
376
+ ): void {
377
+ if (Object.prototype.hasOwnProperty.call(input, "embedTokenProvider")) {
378
+ this.embedTokenProvider = input.embedTokenProvider;
379
+ }
380
+ if (input.hostCallbacks !== undefined) {
381
+ this.hostCallbacks = { ...input.hostCallbacks };
382
+ }
383
+ }
384
+
385
+ /**
386
+ * Whether a configuration/callback change requires tearing down the session.
387
+ * @param configuration - Candidate configuration
388
+ * @param callbackNames - Candidate host callback names
389
+ * @returns True when fingerprints or callback sets differ
390
+ */
391
+ requiresNewSession(
392
+ configuration: ReturningAIWidgetConfiguration,
393
+ callbackNames: Iterable<string>,
394
+ ): boolean {
395
+ const next = configuration.validated();
396
+ const nextNames = new Set(callbackNames);
397
+ const currentNames = new Set(Object.keys(this.hostCallbacks));
398
+ return (
399
+ next.sessionFingerprint !== this.configuration.sessionFingerprint ||
400
+ !sameSet(nextNames, currentNames)
401
+ );
402
+ }
403
+
404
+ /**
405
+ * Replaces configuration in place when a new session is not required.
406
+ * @param configuration - Next configuration (validated)
407
+ */
408
+ updateConfiguration(configuration: ReturningAIWidgetConfiguration): void {
409
+ this.configuration = configuration.validated();
410
+ }
411
+
412
+ /**
413
+ * Applies navigation policy and emits delegate/reject side effects.
414
+ * @param uri - Absolute navigation URL
415
+ * @param isMainFrame - Main-frame vs subframe
416
+ * @returns Policy action for the WebView gate
417
+ */
418
+ handleNavigation(uri: URL, isMainFrame: boolean): ReturningAINavigationAction {
419
+ const action = new ReturningAINavigationPolicy(this.configuration).decide(uri, isMainFrame);
420
+ switch (action) {
421
+ case ReturningAINavigationAction.allow:
422
+ break;
423
+ case ReturningAINavigationAction.delegate:
424
+ this.emit(new ReturningAIWidgetExternalNavigationRequested(uri));
425
+ this.onExternalNavigation?.(uri);
426
+ break;
427
+ case ReturningAINavigationAction.reject:
428
+ if (isMainFrame) {
429
+ this.emitError(
430
+ new ReturningAIWidgetError({
431
+ code: "navigationRejected",
432
+ message: "Navigation was rejected by the widget policy.",
433
+ }),
434
+ );
435
+ }
436
+ break;
437
+ }
438
+ return action;
439
+ }
440
+
441
+ /**
442
+ * Forwards a WebView error as terminal `fail` or non-terminal `emitError`.
443
+ * @param error - Typed load error
444
+ * @param terminal - Whether the session should fail
445
+ */
446
+ handleWebViewError(error: ReturningAIWidgetError, terminal: boolean): void {
447
+ if (terminal) {
448
+ this.fail(error);
449
+ } else {
450
+ this.emitError(error);
451
+ }
452
+ }
453
+
454
+ /**
455
+ * Tears down the session: bumps generation, cancels auth, clears token cache, optionally disposes the driver.
456
+ * Safe to call repeatedly; subsequent starts on this instance throw.
457
+ * @param disposeDriver - When true, disposes the attached driver
458
+ */
459
+ invalidate(disposeDriver = true): void {
460
+ if (this.state === ReturningAIWidgetCoordinatorState.invalidated) {
461
+ return;
462
+ }
463
+ this.state = ReturningAIWidgetCoordinatorState.invalidated;
464
+ this.generation += 1;
465
+ this.clearSessionWork();
466
+ const driver = this.driver;
467
+ this.driver = undefined;
468
+ if (disposeDriver && driver !== undefined) {
469
+ void driver.dispose();
470
+ }
471
+ }
472
+
473
+ /**
474
+ * Answers an authenticate bridge request with `{ token, expiresIn }` (access token only).
475
+ * Drops replies from stale generations after invalidate.
476
+ */
477
+ private async handleAuthentication(
478
+ message: ReturningAIAuthenticateRequest,
479
+ generation: number,
480
+ ): Promise<void> {
481
+ const requestId = message.requestId;
482
+ const authenticationEpoch = this.authenticationEpoch;
483
+ if (requestId === undefined) {
484
+ return;
485
+ }
486
+ try {
487
+ const token = await this.authenticate();
488
+ if (
489
+ this.generation !== generation ||
490
+ this.state === ReturningAIWidgetCoordinatorState.invalidated
491
+ ) {
492
+ return;
493
+ }
494
+ if (this.authenticationEpoch !== authenticationEpoch) {
495
+ throw new ReturningAIWidgetError({
496
+ code: "cancelled",
497
+ message: "Authentication was cancelled.",
498
+ });
499
+ }
500
+ await this.driver?.runJavaScript(
501
+ this.codec.successResponseScript(requestId, {
502
+ token: token.value,
503
+ expiresIn: token.expiresIn,
504
+ }),
505
+ );
506
+ } catch (error) {
507
+ if (error instanceof ReturningAIWidgetError && this.generation === generation) {
508
+ await this.driver?.runJavaScript(this.codec.errorResponseScript(requestId, error));
509
+ this.emitError(error);
510
+ this.stopWaitingForReady();
511
+ }
512
+ } finally {
513
+ this.codec.releaseRequestId(requestId);
514
+ }
515
+ }
516
+
517
+ /** Returns a cached access token or starts/joins an in-flight exchange. */
518
+ private authenticate(): Promise<ReturningAIAccessToken> {
519
+ const cached = this.tokenCache.get(this.sessionKey);
520
+ if (cached !== undefined) {
521
+ return Promise.resolve(cached);
522
+ }
523
+ if (this.inFlightAuthentication !== undefined) {
524
+ return this.inFlightAuthentication;
525
+ }
526
+ return this.startAuthentication();
527
+ }
528
+
529
+ /** Starts a new auth exchange and caches the resulting access token. */
530
+ private startAuthentication(): Promise<ReturningAIAccessToken> {
531
+ const operation = this.authenticationClient.authenticate(
532
+ this.configuration,
533
+ this.embedTokenProvider,
534
+ );
535
+ this.activeAuthentication = operation;
536
+ const authenticationGeneration = this.generation;
537
+ const future = operation.result
538
+ .then((token) => {
539
+ if (
540
+ this.generation !== authenticationGeneration ||
541
+ this.state === ReturningAIWidgetCoordinatorState.invalidated ||
542
+ this.activeAuthentication !== operation
543
+ ) {
544
+ throw new ReturningAIWidgetError({
545
+ code: "cancelled",
546
+ message: "Authentication was cancelled.",
547
+ });
548
+ }
549
+ this.tokenCache.put(this.sessionKey, token);
550
+ return token;
551
+ })
552
+ .finally(() => {
553
+ if (this.inFlightAuthentication === future) {
554
+ this.inFlightAuthentication = undefined;
555
+ }
556
+ if (this.activeAuthentication === operation) {
557
+ this.activeAuthentication = undefined;
558
+ }
559
+ });
560
+ this.inFlightAuthentication = future;
561
+ return future;
562
+ }
563
+
564
+ /**
565
+ * Warm-starts auth while HTML loads so the bridge authenticate request can hit cache.
566
+ * Ignores failures from superseded generations.
567
+ */
568
+ private async prefetchAuthentication(generation: number): Promise<void> {
569
+ try {
570
+ await this.authenticate();
571
+ } catch (error) {
572
+ if (
573
+ error instanceof ReturningAIWidgetError &&
574
+ (this.generation !== generation ||
575
+ this.state === ReturningAIWidgetCoordinatorState.invalidated)
576
+ ) {
577
+ return;
578
+ }
579
+ }
580
+ }
581
+
582
+ /** Invokes an allowlisted host callback and replies over the bridge. */
583
+ private async handleCallback(
584
+ message: ReturningAIHostCallbackBridgeRequest,
585
+ generation: number,
586
+ ): Promise<void> {
587
+ const requestId = message.requestId;
588
+ if (requestId === undefined) {
589
+ return;
590
+ }
591
+ try {
592
+ const handler = this.hostCallbacks[message.request.name];
593
+ if (handler === undefined) {
594
+ throw new ReturningAIWidgetError({
595
+ code: "callbackFailed",
596
+ message: "The widget requested a callback that is not allowlisted.",
597
+ });
598
+ }
599
+ const value = await withTimeout(
600
+ Promise.resolve()
601
+ .then(() => handler(message.request))
602
+ .catch(() => {
603
+ throw new ReturningAIWidgetError({
604
+ code: "callbackFailed",
605
+ message: "Host callback failed.",
606
+ });
607
+ }),
608
+ this.configuration.callbackTimeoutMilliseconds,
609
+ );
610
+ if (
611
+ this.generation !== generation ||
612
+ this.state === ReturningAIWidgetCoordinatorState.invalidated
613
+ ) {
614
+ return;
615
+ }
616
+ await this.driver?.runJavaScript(
617
+ this.codec.successResponseScript(
618
+ requestId,
619
+ validateReturningAIJsonValue(value === undefined ? null : value),
620
+ ),
621
+ );
622
+ } catch (error) {
623
+ const widgetError =
624
+ error instanceof ReturningAIWidgetError
625
+ ? error
626
+ : new ReturningAIWidgetError({
627
+ code: "callbackFailed",
628
+ message: "Host callback failed.",
629
+ });
630
+ if (this.generation === generation) {
631
+ await this.driver?.runJavaScript(this.codec.errorResponseScript(requestId, widgetError));
632
+ this.emitError(widgetError);
633
+ }
634
+ } finally {
635
+ this.codec.releaseRequestId(requestId);
636
+ }
637
+ }
638
+
639
+ /**
640
+ * Handles typed events: ready clears the timer; logout / session-expired clear the access-token cache.
641
+ */
642
+ private handleEvent(event: ReturningAIWidgetEvent): void {
643
+ if (event instanceof ReturningAIWidgetReady || event instanceof ReturningAIWidgetMounted) {
644
+ this.readyTimer?.cancel();
645
+ this.state = ReturningAIWidgetCoordinatorState.ready;
646
+ } else if (event instanceof ReturningAIWidgetErrorEvent) {
647
+ this.stopWaitingForReady();
648
+ this.emitError(event.error);
649
+ return;
650
+ } else if (
651
+ event instanceof ReturningAIWidgetSessionExpired ||
652
+ event instanceof ReturningAIWidgetLoggedOut
653
+ ) {
654
+ this.clearAuthentication();
655
+ } else if (event instanceof ReturningAIWidgetExternalNavigationRequested) {
656
+ const action = new ReturningAINavigationPolicy(this.configuration).decide(event.uri, true);
657
+ if (action === ReturningAINavigationAction.reject) {
658
+ this.emitError(
659
+ new ReturningAIWidgetError({
660
+ code: "navigationRejected",
661
+ message: "External navigation was rejected by the widget policy.",
662
+ }),
663
+ );
664
+ return;
665
+ }
666
+ this.onExternalNavigation?.(event.uri);
667
+ }
668
+ this.emit(event);
669
+ }
670
+
671
+ private stopWaitingForReady(): void {
672
+ this.readyTimer?.cancel();
673
+ if (this.state === ReturningAIWidgetCoordinatorState.loading) {
674
+ this.state = ReturningAIWidgetCoordinatorState.failed;
675
+ }
676
+ }
677
+
678
+ private emit(event: ReturningAIWidgetEvent): void {
679
+ this.onEvent?.(event);
680
+ }
681
+
682
+ private emitError(error: ReturningAIWidgetError): void {
683
+ this.onError?.(error);
684
+ this.emit(new ReturningAIWidgetErrorEvent(error));
685
+ }
686
+
687
+ /** Marks the session failed and notifies terminal + non-terminal error sinks. */
688
+ private fail(error: ReturningAIWidgetError): void {
689
+ if (this.state === ReturningAIWidgetCoordinatorState.invalidated) {
690
+ return;
691
+ }
692
+ this.state = ReturningAIWidgetCoordinatorState.failed;
693
+ this.readyTimer?.cancel();
694
+ this.emitError(error);
695
+ this.onTerminalError?.(error);
696
+ }
697
+
698
+ private requireLive(): void {
699
+ if (this.state === ReturningAIWidgetCoordinatorState.invalidated) {
700
+ throw new ReturningAIWidgetError({
701
+ code: "invalidControllerState",
702
+ message: "The widget session has been invalidated.",
703
+ });
704
+ }
705
+ }
706
+
707
+ private clearAuthentication(): void {
708
+ this.authenticationEpoch += 1;
709
+ this.activeAuthentication?.cancel();
710
+ this.activeAuthentication = undefined;
711
+ this.inFlightAuthentication = undefined;
712
+ this.tokenCache.clear(this.sessionKey);
713
+ }
714
+
715
+ /** Cancels ready timer + in-flight auth and clears the session access-token cache. */
716
+ private clearSessionWork(): void {
717
+ this.readyTimer?.cancel();
718
+ this.clearAuthentication();
719
+ }
720
+ }
721
+
722
+ /** Maps theme preference to a concrete light/dark value for HTML first paint. */
723
+ function resolvedTheme(
724
+ theme: (typeof ReturningAIWidgetTheme)[keyof typeof ReturningAIWidgetTheme],
725
+ ): ReturningAIResolvedTheme {
726
+ return theme === ReturningAIWidgetTheme.dark ? "dark" : "light";
727
+ }
728
+
729
+ /** Maps coordinator state to the public session phase enum. */
730
+ function sessionPhaseFor(state: ReturningAIWidgetCoordinatorState): ReturningAIWidgetSessionPhase {
731
+ switch (state) {
732
+ case ReturningAIWidgetCoordinatorState.idle:
733
+ return ReturningAIWidgetSessionPhase.idle;
734
+ case ReturningAIWidgetCoordinatorState.loading:
735
+ return ReturningAIWidgetSessionPhase.loading;
736
+ case ReturningAIWidgetCoordinatorState.ready:
737
+ return ReturningAIWidgetSessionPhase.ready;
738
+ case ReturningAIWidgetCoordinatorState.failed:
739
+ return ReturningAIWidgetSessionPhase.failed;
740
+ case ReturningAIWidgetCoordinatorState.invalidated:
741
+ return ReturningAIWidgetSessionPhase.invalidated;
742
+ }
743
+ }
744
+
745
+ /** Best-effort `unref` so Node-style timers do not keep processes alive in tests. */
746
+ function unrefTimer(handle: ReturnType<typeof setTimeout>): void {
747
+ if (typeof handle === "object" && handle !== null && "unref" in handle) {
748
+ (handle as { unref: () => void }).unref();
749
+ }
750
+ }
751
+
752
+ function sameSet(left: Set<string>, right: Set<string>): boolean {
753
+ if (left.size !== right.size) {
754
+ return false;
755
+ }
756
+ for (const value of left) {
757
+ if (!right.has(value)) {
758
+ return false;
759
+ }
760
+ }
761
+ return true;
762
+ }
763
+
764
+ /** Races a promise against a callback timeout error. */
765
+ async function withTimeout<T>(promise: Promise<T>, timeoutMilliseconds: number): Promise<T> {
766
+ let timeoutHandle: ReturnType<typeof setTimeout> | undefined;
767
+ try {
768
+ return await Promise.race([
769
+ promise,
770
+ new Promise<T>((_, reject) => {
771
+ timeoutHandle = setTimeout(() => {
772
+ reject(
773
+ new ReturningAIWidgetError({
774
+ code: "callbackTimeout",
775
+ message: "Host callback timed out.",
776
+ }),
777
+ );
778
+ }, timeoutMilliseconds);
779
+ unrefTimer(timeoutHandle);
780
+ }),
781
+ ]);
782
+ } finally {
783
+ if (timeoutHandle !== undefined) {
784
+ clearTimeout(timeoutHandle);
785
+ }
786
+ }
787
+ }