@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,44 @@
1
+ /**
2
+ * @fileoverview Environment domain-key enum and HTML attribute value mapping (SGTR/STG/PROD/LOCAL).
3
+ *
4
+ * Layer: configuration
5
+ * Role: Defines domain keys and converts them to uppercase attribute values for the custom element.
6
+ * Does not select endpoint presets or enforce URL security.
7
+ * See also: ReturningAIWidgetEndpoints.ts, ReturningAIWidgetConfiguration.ts
8
+ */
9
+
10
+ /**
11
+ * Environment key selecting default endpoint presets and the `domain-key` HTML attribute.
12
+ */
13
+ export type ReturningAIWidgetDomainKey = "sgtr" | "stg" | "prod" | "local";
14
+
15
+ /**
16
+ * Const object mirroring {@link ReturningAIWidgetDomainKey} for ergonomic host usage.
17
+ */
18
+ export const ReturningAIWidgetDomainKey = {
19
+ /** SGTR / genesiv shared environment. */
20
+ sgtr: "sgtr",
21
+ /** Staging environment. */
22
+ stg: "stg",
23
+ /** Production ReturningAI environment (default). */
24
+ prod: "prod",
25
+ /** Local debug endpoints (HTTP localhost only when `debug: true`). */
26
+ local: "local",
27
+ } as const;
28
+
29
+ /** Maps lowercase domain keys to the uppercase values expected by the web custom element. */
30
+ const ATTRIBUTE_VALUES: Record<ReturningAIWidgetDomainKey, string> = {
31
+ sgtr: "SGTR",
32
+ stg: "STG",
33
+ prod: "PROD",
34
+ local: "LOCAL",
35
+ };
36
+
37
+ /**
38
+ * Converts a domain key to the uppercase HTML `domain-key` attribute value.
39
+ * @param key - Configuration domain key
40
+ * @returns Uppercase attribute value (`PROD`, `STG`, …)
41
+ */
42
+ export function domainKeyAttributeValue(key: ReturningAIWidgetDomainKey): string {
43
+ return ATTRIBUTE_VALUES[key];
44
+ }
@@ -0,0 +1,157 @@
1
+ /**
2
+ * @fileoverview Named ReturningAI service endpoint sets used for auth and widget JS globals.
3
+ *
4
+ * Layer: configuration
5
+ * Role: Parses/stores widget auth, API, socket, and MFE URLs; exposes production/staging/local
6
+ * presets and JavaScript global name mapping. Does not perform HTTP calls.
7
+ * Security: Production presets use HTTPS; local HTTP is for debug only when configuration allows.
8
+ * See also: ReturningAIWidgetConfiguration.ts, urls.ts
9
+ */
10
+
11
+ import { formatUrl, parseUrl } from "./urls";
12
+
13
+ /**
14
+ * Named ReturningAI service URLs used for auth POSTs and runtime JavaScript globals.
15
+ * Hosts may pass a custom set or rely on domain-key presets from configuration.
16
+ */
17
+ export class ReturningAIWidgetEndpoints {
18
+ /** Base URL for serverless widget authentication (`…/{widgetId}/auth/serverless`). */
19
+ readonly widgetAuthUrl: URL;
20
+ /** Primary API v2 base used as the `api_url` JS global / `v2-api-url` attribute. */
21
+ readonly apiV2Url: URL;
22
+ /** Optional widget path v2 base (`widget_path_v2` global). */
23
+ readonly widgetPathV2Url?: URL;
24
+ /** Optional product base URL (`base_url` global). */
25
+ readonly baseUrl?: URL;
26
+ /** Optional auth API base (`auth_api` global). */
27
+ readonly authApiUrl?: URL;
28
+ /** Optional socket v2 base (`socket_path_v2` global). */
29
+ readonly socketV2Url?: URL;
30
+ /** Optional legacy socket base (`socket_path` global). */
31
+ readonly socketUrl?: URL;
32
+ /** Optional channel API base (`channel_api` global). */
33
+ readonly channelApiUrl?: URL;
34
+ /** Optional MFE base (`mfe_url` global). */
35
+ readonly mfeUrl?: URL;
36
+
37
+ /**
38
+ * Parses and stores endpoint URLs.
39
+ * @param input.widgetAuthUrl - Required widget auth base (HTTPS in production)
40
+ * @param input.apiV2Url - Required API v2 base
41
+ * @param input.widgetPathV2Url - Optional widget path v2
42
+ * @param input.baseUrl - Optional product base
43
+ * @param input.authApiUrl - Optional auth API
44
+ * @param input.socketV2Url - Optional socket v2
45
+ * @param input.socketUrl - Optional legacy socket
46
+ * @param input.channelApiUrl - Optional channel API
47
+ * @param input.mfeUrl - Optional MFE base
48
+ */
49
+ constructor(input: {
50
+ widgetAuthUrl: string | URL;
51
+ apiV2Url: string | URL;
52
+ widgetPathV2Url?: string | URL;
53
+ baseUrl?: string | URL;
54
+ authApiUrl?: string | URL;
55
+ socketV2Url?: string | URL;
56
+ socketUrl?: string | URL;
57
+ channelApiUrl?: string | URL;
58
+ mfeUrl?: string | URL;
59
+ }) {
60
+ this.widgetAuthUrl = parseUrl(input.widgetAuthUrl);
61
+ this.apiV2Url = parseUrl(input.apiV2Url);
62
+ this.widgetPathV2Url = optionalUrl(input.widgetPathV2Url);
63
+ this.baseUrl = optionalUrl(input.baseUrl);
64
+ this.authApiUrl = optionalUrl(input.authApiUrl);
65
+ this.socketV2Url = optionalUrl(input.socketV2Url);
66
+ this.socketUrl = optionalUrl(input.socketUrl);
67
+ this.channelApiUrl = optionalUrl(input.channelApiUrl);
68
+ this.mfeUrl = optionalUrl(input.mfeUrl);
69
+ }
70
+
71
+ /**
72
+ * Every defined endpoint URL (for HTTPS validation and navigation host derivation).
73
+ * @returns Non-undefined endpoint URLs
74
+ */
75
+ get allUrls(): URL[] {
76
+ return [
77
+ this.widgetAuthUrl,
78
+ this.apiV2Url,
79
+ this.widgetPathV2Url,
80
+ this.baseUrl,
81
+ this.authApiUrl,
82
+ this.socketV2Url,
83
+ this.socketUrl,
84
+ this.channelApiUrl,
85
+ this.mfeUrl,
86
+ ].filter((url): url is URL => url !== undefined);
87
+ }
88
+
89
+ /**
90
+ * Maps endpoint fields to the window globals expected by the widget runtime.
91
+ * @returns Record of global name → absolute URL
92
+ */
93
+ get javaScriptGlobals(): Record<string, URL> {
94
+ const globals: Record<string, URL> = { api_url: this.apiV2Url };
95
+ if (this.widgetPathV2Url) globals.widget_path_v2 = this.widgetPathV2Url;
96
+ if (this.baseUrl) globals.base_url = this.baseUrl;
97
+ if (this.authApiUrl) globals.auth_api = this.authApiUrl;
98
+ if (this.socketV2Url) globals.socket_path_v2 = this.socketV2Url;
99
+ if (this.socketUrl) globals.socket_path = this.socketUrl;
100
+ if (this.channelApiUrl) globals.channel_api = this.channelApiUrl;
101
+ if (this.mfeUrl) globals.mfe_url = this.mfeUrl;
102
+ return globals;
103
+ }
104
+
105
+ /** Production ReturningAI endpoints (HTTPS). */
106
+ static readonly production = new ReturningAIWidgetEndpoints({
107
+ widgetAuthUrl: "https://prod-widgets.returning.ai",
108
+ apiV2Url: "https://api-v2.returning.ai",
109
+ });
110
+
111
+ /** SGTR / genesiv shared endpoints (HTTPS). */
112
+ static readonly sgtr = new ReturningAIWidgetEndpoints({
113
+ widgetAuthUrl: "https://sgtr-eks-widgets.genesiv.org",
114
+ apiV2Url: "https://api-v2.genesiv.org",
115
+ });
116
+
117
+ /** Staging endpoints (HTTPS). */
118
+ static readonly staging = new ReturningAIWidgetEndpoints({
119
+ widgetAuthUrl: "https://staging-widgets.genesiv.org",
120
+ apiV2Url: "https://staging-api-v2.genesiv.org",
121
+ });
122
+
123
+ /**
124
+ * Localhost HTTP endpoints for debug-only hosts.
125
+ * Allowed only when configuration `debug: true` (see `isSecureUrl`).
126
+ */
127
+ static readonly local = new ReturningAIWidgetEndpoints({
128
+ widgetAuthUrl: "http://localhost:1333",
129
+ apiV2Url: "http://localhost:1335",
130
+ });
131
+
132
+ /** ADSS production multi-service endpoint set (HTTPS). */
133
+ static readonly adssProduction = new ReturningAIWidgetEndpoints({
134
+ widgetAuthUrl: "https://adss-prod-widgets.returning.ai",
135
+ apiV2Url: "https://adss-api-v2.returning.ai",
136
+ widgetPathV2Url: "https://adss-prod-widgets.returning.ai",
137
+ baseUrl: "https://returning.ai",
138
+ authApiUrl: "https://adss-auth.returning.ai",
139
+ socketV2Url: "https://adss-socket-v2.returning.ai",
140
+ socketUrl: "https://adss-socket.returning.ai",
141
+ channelApiUrl: "https://adss-channels.returning.ai",
142
+ mfeUrl: "https://adss-production.returning.ai",
143
+ });
144
+ }
145
+
146
+ function optionalUrl(value: string | URL | undefined): URL | undefined {
147
+ return value === undefined ? undefined : parseUrl(value);
148
+ }
149
+
150
+ /**
151
+ * Formats an endpoint URL with the SDK's origin-friendly string rules.
152
+ * @param url - Endpoint URL
153
+ * @returns Canonical string form
154
+ */
155
+ export function formatEndpointUrl(url: URL): string {
156
+ return formatUrl(url);
157
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * @fileoverview Widget theme preference constants: light, dark, or follow system.
3
+ *
4
+ * Layer: configuration
5
+ * Role: Declares the theme union and const object hosts pass into configuration/controller.
6
+ * Does not resolve system brightness (see rendering/theme.ts).
7
+ * See also: rendering/theme.ts, ReturningAIWidgetConfiguration.ts
8
+ */
9
+
10
+ /**
11
+ * Host theme preference before platform brightness resolution.
12
+ */
13
+ export type ReturningAIWidgetTheme = "light" | "dark" | "system";
14
+
15
+ /**
16
+ * Const object for theme preference values passed to configuration and the controller.
17
+ */
18
+ export const ReturningAIWidgetTheme = {
19
+ /** Force light shell and element theme. */
20
+ light: "light",
21
+ /** Force dark shell and element theme. */
22
+ dark: "dark",
23
+ /** Follow the host OS / React Native color scheme. */
24
+ system: "system",
25
+ } as const;
@@ -0,0 +1,133 @@
1
+ /**
2
+ * @fileoverview URL parsing, HTTPS/localhost security helpers, and HTML attribute escaping utilities.
3
+ *
4
+ * Layer: configuration
5
+ * Role: parse/format URLs, secure-URL and host checks, origin extraction, sibling resource paths,
6
+ * ARGB formatting, and attribute escaping. Does not own endpoint presets or full config validation.
7
+ * Security: isSecureUrl allows HTTP only for explicit debug + localhost.
8
+ * See also: ReturningAIWidgetConfiguration.ts, ReturningAIWidgetEndpoints.ts
9
+ */
10
+
11
+ /**
12
+ * Parses a string into a `URL`, or returns the existing `URL` instance.
13
+ * @param value - Absolute URL string or `URL`
14
+ * @returns Parsed `URL`
15
+ */
16
+ export function parseUrl(value: string | URL): URL {
17
+ return value instanceof URL ? value : new URL(value);
18
+ }
19
+
20
+ /**
21
+ * Formats a URL similarly to Java `URI.toString()` for HTTPS origins (no forced trailing slash).
22
+ * @param url - URL to format
23
+ * @returns Canonical string without a lone `/` pathname
24
+ */
25
+ export function formatUrl(url: URL): string {
26
+ const pathname = url.pathname === "/" ? "" : url.pathname;
27
+ return `${url.protocol}//${url.host}${pathname}${url.search}${url.hash}`;
28
+ }
29
+
30
+ /**
31
+ * Whether a hostname is a localhost loopback name.
32
+ * @param host - Hostname (case-insensitive)
33
+ * @returns True for localhost / 127.0.0.1 / ::1
34
+ */
35
+ export function isLocalhost(host: string): boolean {
36
+ const normalized = normalizeHost(host);
37
+ return (
38
+ normalized === "localhost" ||
39
+ normalized === "127.0.0.1" ||
40
+ normalized === "::1" ||
41
+ normalized === "[::1]"
42
+ );
43
+ }
44
+
45
+ /**
46
+ * Returns whether a URL is allowed under production HTTPS rules.
47
+ * HTTP is permitted only when `debug` is true and the host is localhost.
48
+ * @param url - Candidate URL
49
+ * @param debug - Host configuration debug flag
50
+ * @returns True when the URL may be used for widget/runtime/auth endpoints
51
+ */
52
+ export function isSecureUrl(url: URL, debug: boolean): boolean {
53
+ const scheme = url.protocol.replace(/:$/, "").toLowerCase();
54
+ const host = url.hostname;
55
+ if (scheme === "https" && host.length > 0) {
56
+ return true;
57
+ }
58
+ return debug && scheme === "http" && isLocalhost(host);
59
+ }
60
+
61
+ /**
62
+ * Lowercases a hostname for allowlist comparisons.
63
+ * @param host - Raw hostname
64
+ * @returns Lowercased hostname
65
+ */
66
+ export function normalizeHost(host: string): string {
67
+ return host.toLowerCase();
68
+ }
69
+
70
+ /**
71
+ * Validates a trusted navigation hostname (no path/port except IPv6 loopback forms).
72
+ * @param host - Candidate host
73
+ * @returns True when the host may appear in `allowedNavigationHosts`
74
+ */
75
+ export function isValidHost(host: string): boolean {
76
+ if (host.length === 0 || host.includes("/") || host.includes(":")) {
77
+ return host === "::1" || host === "[::1]";
78
+ }
79
+ return /^[A-Za-z0-9.-]+$/.test(host);
80
+ }
81
+
82
+ /**
83
+ * Extracts `protocol//host` origin from a URL when both parts are present.
84
+ * @param url - Source URL
85
+ * @returns Origin string, or `undefined` when incomplete
86
+ */
87
+ export function originOf(url: URL): string | undefined {
88
+ if (!url.protocol || !url.host) {
89
+ return undefined;
90
+ }
91
+ return `${url.protocol}//${url.host}`;
92
+ }
93
+
94
+ /**
95
+ * Replaces the final path segment of a bundle URL with a sibling file name.
96
+ * Used for preloading `app.js` / `style.css` next to `widget.js`.
97
+ * @param bundle - Bundle URL
98
+ * @param fileName - Sibling file name
99
+ * @returns Absolute sibling URL string
100
+ */
101
+ export function siblingResource(bundle: URL, fileName: string): string {
102
+ const segments = bundle.pathname.split("/").filter((part) => part.length > 0);
103
+ if (segments.length === 0) {
104
+ return formatUrl(bundle);
105
+ }
106
+ segments[segments.length - 1] = fileName;
107
+ const next = new URL(bundle.href);
108
+ next.pathname = `/${segments.join("/")}`;
109
+ return formatUrl(next);
110
+ }
111
+
112
+ /**
113
+ * Formats an ARGB color as an unsigned hex string for fingerprints.
114
+ * @param color - 32-bit ARGB integer
115
+ * @returns Hex without `0x` prefix
116
+ */
117
+ export function argbToRadixString(color: number): string {
118
+ return (color >>> 0).toString(16);
119
+ }
120
+
121
+ /**
122
+ * Escapes a string for safe inclusion in double-quoted HTML attributes.
123
+ * @param value - Raw attribute value
124
+ * @returns Escaped attribute text
125
+ */
126
+ export function escapeAttribute(value: string): string {
127
+ return value
128
+ .replace(/&/g, "&amp;")
129
+ .replace(/"/g, "&quot;")
130
+ .replace(/'/g, "&#39;")
131
+ .replace(/</g, "&lt;")
132
+ .replace(/>/g, "&gt;");
133
+ }
@@ -0,0 +1,149 @@
1
+ /**
2
+ * @fileoverview Imperative host controller for reload, retry, theme, logout, session query, and invalidate.
3
+ *
4
+ * Layer: controller
5
+ * Role: Single-attach proxy that forwards host commands to the mounted widget target.
6
+ * Does not own auth, bridge, or WebView lifecycle itself.
7
+ * See also: ReturningAIWidget.tsx, coordinator/ReturningAIWidgetCoordinator.ts,
8
+ * ReturningAIWidgetSessionSnapshot.ts
9
+ */
10
+
11
+ import { type ReturningAIWidgetTheme } from "../configuration/ReturningAIWidgetTheme";
12
+ import { ReturningAIWidgetError } from "../errors/ReturningAIWidgetError";
13
+ import {
14
+ ReturningAIWidgetSessionSnapshotDetached,
15
+ type ReturningAIWidgetSessionSnapshot,
16
+ } from "./ReturningAIWidgetSessionSnapshot";
17
+
18
+ /**
19
+ * Imperative surface the widget component attaches for host-driven commands.
20
+ */
21
+ export interface ReturningAIWidgetControllerTarget {
22
+ /** Reloads the current WebView session shell. */
23
+ reload(): Promise<void>;
24
+ /** Clears error UI and restarts the coordinator session. */
25
+ retry(): Promise<void>;
26
+ /** Pushes a resolved theme into the WebView shell. */
27
+ updateTheme(
28
+ theme: (typeof ReturningAIWidgetTheme)[keyof typeof ReturningAIWidgetTheme],
29
+ ): Promise<void>;
30
+ /** Soft-logs out: clears native access-token cache and asks the runtime to logout. */
31
+ logout(): Promise<void>;
32
+ /** Whether a usable cached access token remains (30s skew). Detached targets return false. */
33
+ readonly isAuthenticated: boolean;
34
+ /** Redacted session phase + auth presence. Never includes token values. */
35
+ readonly sessionSnapshot: ReturningAIWidgetSessionSnapshot;
36
+ /** Invalidates the active coordinator session. */
37
+ invalidate(): Promise<void>;
38
+ }
39
+
40
+ /**
41
+ * Host-held controller that proxies reload/retry/theme/logout/session query/invalidate.
42
+ * Only one target may be attached at a time. Session query is safe when detached.
43
+ */
44
+ export class ReturningAIWidgetController {
45
+ private target: ReturningAIWidgetControllerTarget | undefined;
46
+
47
+ /**
48
+ * Whether a widget instance is currently attached.
49
+ * @returns True when commands can be forwarded
50
+ */
51
+ get isAttached(): boolean {
52
+ return this.target !== undefined;
53
+ }
54
+
55
+ /**
56
+ * Reloads the attached widget WebView shell.
57
+ * @throws {ReturningAIWidgetError} with `invalidControllerState` when detached
58
+ */
59
+ async reload(): Promise<void> {
60
+ await this.requireTarget().reload();
61
+ }
62
+
63
+ /**
64
+ * Retries after a terminal error by restarting the session.
65
+ * @throws {ReturningAIWidgetError} with `invalidControllerState` when detached
66
+ */
67
+ async retry(): Promise<void> {
68
+ await this.requireTarget().retry();
69
+ }
70
+
71
+ /**
72
+ * Updates the widget theme preference on the attached target.
73
+ * @param theme - Light, dark, or system preference
74
+ * @throws {ReturningAIWidgetError} with `invalidControllerState` when detached
75
+ */
76
+ async updateTheme(
77
+ theme: (typeof ReturningAIWidgetTheme)[keyof typeof ReturningAIWidgetTheme],
78
+ ): Promise<void> {
79
+ await this.requireTarget().updateTheme(theme);
80
+ }
81
+
82
+ /**
83
+ * Soft-logs out the attached widget without disposing the WebView.
84
+ * @throws {ReturningAIWidgetError} with `invalidControllerState` when detached
85
+ */
86
+ async logout(): Promise<void> {
87
+ await this.requireTarget().logout();
88
+ }
89
+
90
+ /**
91
+ * Whether a usable cached access token remains. `false` when detached.
92
+ */
93
+ get isAuthenticated(): boolean {
94
+ return this.target?.isAuthenticated ?? false;
95
+ }
96
+
97
+ /**
98
+ * Redacted session snapshot. Detached controllers return the detached snapshot.
99
+ */
100
+ get sessionSnapshot(): ReturningAIWidgetSessionSnapshot {
101
+ return this.target?.sessionSnapshot ?? ReturningAIWidgetSessionSnapshotDetached;
102
+ }
103
+
104
+ /**
105
+ * Invalidates the attached widget session (cancels auth and drops the driver when configured).
106
+ * @throws {ReturningAIWidgetError} with `invalidControllerState` when detached
107
+ */
108
+ async invalidate(): Promise<void> {
109
+ await this.requireTarget().invalidate();
110
+ }
111
+
112
+ /**
113
+ * Attaches a mounted widget target. Fails if another distinct target is already attached.
114
+ * @param target - Widget-provided command surface
115
+ * @throws {ReturningAIWidgetError} with `invalidControllerState` on double-attach
116
+ */
117
+ attach(target: ReturningAIWidgetControllerTarget): void {
118
+ const current = this.target;
119
+ if (current !== undefined && current !== target) {
120
+ throw new ReturningAIWidgetError({
121
+ code: "invalidControllerState",
122
+ message: "A ReturningAIWidgetController is already attached.",
123
+ });
124
+ }
125
+ this.target = target;
126
+ }
127
+
128
+ /**
129
+ * Detaches a target when it matches the current attachment.
130
+ * @param target - Target previously passed to {@link attach}
131
+ */
132
+ detach(target: ReturningAIWidgetControllerTarget): void {
133
+ if (this.target === target) {
134
+ this.target = undefined;
135
+ }
136
+ }
137
+
138
+ /** Returns the attached target or throws when the controller is idle. */
139
+ private requireTarget(): ReturningAIWidgetControllerTarget {
140
+ const target = this.target;
141
+ if (target === undefined) {
142
+ throw new ReturningAIWidgetError({
143
+ code: "invalidControllerState",
144
+ message: "A ReturningAIWidgetController is not attached.",
145
+ });
146
+ }
147
+ return target;
148
+ }
149
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * @fileoverview Public session phase + snapshot for controller session query (MOB-23).
3
+ *
4
+ * Layer: controller
5
+ * Role: Host-safe view of widget session lifecycle and auth cache presence.
6
+ * Never includes access, refresh, or embed token values.
7
+ * See also: ReturningAIWidgetController.ts, ReturningAIWidgetCoordinator.ts
8
+ */
9
+
10
+ /** Lifecycle phase visible to hosts via {@link ReturningAIWidgetSessionSnapshot}. */
11
+ export const ReturningAIWidgetSessionPhase = {
12
+ /** Controller has no attached widget target. */
13
+ detached: "detached",
14
+ /** Session created but not started. */
15
+ idle: "idle",
16
+ /** Shell loading; waiting for ready / mounted. */
17
+ loading: "loading",
18
+ /** Widget reported ready or mounted. */
19
+ ready: "ready",
20
+ /** Terminal failure (ready timeout or main-frame load error). */
21
+ failed: "failed",
22
+ /** Session invalidated; cannot restart on the same coordinator. */
23
+ invalidated: "invalidated",
24
+ } as const;
25
+
26
+ /** Union of {@link ReturningAIWidgetSessionPhase} values. */
27
+ export type ReturningAIWidgetSessionPhase =
28
+ (typeof ReturningAIWidgetSessionPhase)[keyof typeof ReturningAIWidgetSessionPhase];
29
+
30
+ /**
31
+ * Redacted session query result for hosts.
32
+ *
33
+ * `accessTokenExpiresAt` is wall-clock expiry of the cached access token when known.
34
+ * It never includes the token string.
35
+ */
36
+ export type ReturningAIWidgetSessionSnapshot = {
37
+ /** Current lifecycle phase. */
38
+ phase: ReturningAIWidgetSessionPhase;
39
+ /** Whether a usable cached access token remains (30s skew). */
40
+ isAuthenticated: boolean;
41
+ /** Cached access-token expiry when known; never a token value. */
42
+ accessTokenExpiresAt?: Date;
43
+ };
44
+
45
+ /** Detached controller snapshot. */
46
+ export const ReturningAIWidgetSessionSnapshotDetached: ReturningAIWidgetSessionSnapshot = {
47
+ phase: ReturningAIWidgetSessionPhase.detached,
48
+ isAuthenticated: false,
49
+ };