@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,141 @@
1
+ /**
2
+ * @fileoverview Abstract WebView driver contract plus helpers for document base URL and message origin gating.
3
+ *
4
+ * Layer: webview
5
+ * Role: Declares load/reload/JS/dispose APIs; computes secure document bases and whether a web
6
+ * message origin should be delivered. Does not wrap react-native-webview.
7
+ * Security: Message delivery requires main-frame expected origin (with about:blank RN iOS exception).
8
+ * See also: ReturningAIReactNativeWebViewDriver.ts, navigation/ReturningAINavigationPolicy.ts
9
+ */
10
+
11
+ import { type ReturningAIWidgetConfiguration } from "../configuration/ReturningAIWidgetConfiguration";
12
+ import { isSecureUrl } from "../configuration/urls";
13
+ import type { ReturningAINavigationAction } from "../navigation/ReturningAINavigationPolicy";
14
+ import type { ReturningAIWidgetError } from "../errors/ReturningAIWidgetError";
15
+
16
+ /**
17
+ * Platform-agnostic WebView driver used by the coordinator to load HTML and run JS.
18
+ */
19
+ export interface ReturningAIWebViewDriver {
20
+ /**
21
+ * Loads a local HTML shell string with an optional document base URL.
22
+ * @param html - Generated shell HTML (must not contain embed tokens)
23
+ * @param baseUrl - Optional secure content-origin base
24
+ */
25
+ loadHtmlString(html: string, baseUrl?: string): Promise<void>;
26
+ /** Reloads the current shell (platform-specific replay semantics). */
27
+ reload(): Promise<void>;
28
+ /**
29
+ * Evaluates JavaScript in the WebView (bridge replies, theme updates).
30
+ * @param source - Script source; must not embed credentials
31
+ */
32
+ runJavaScript(source: string): Promise<void>;
33
+ /** Releases native resources and drops queued scripts. */
34
+ dispose(): Promise<void>;
35
+ }
36
+
37
+ /** Handler for raw bridge message strings from the WebView. */
38
+ export type ReturningAIWebViewMessageHandler = (raw: string) => void;
39
+
40
+ /** Handler that applies navigation policy to a prospective load. */
41
+ export type ReturningAIWebViewNavigationHandler = (
42
+ uri: URL,
43
+ isMainFrame: boolean,
44
+ ) => ReturningAINavigationAction;
45
+
46
+ /** Handler for WebView load/resource errors with terminal classification. */
47
+ export type ReturningAIWebViewErrorHandler = (
48
+ error: ReturningAIWidgetError,
49
+ terminal: boolean,
50
+ ) => void;
51
+
52
+ /**
53
+ * Computes the document base URL from secure content origin for HTML loads.
54
+ * @param configuration - Widget configuration
55
+ * @returns `protocol://host[:port]/` or `undefined` when insecure/missing host
56
+ */
57
+ export function returningAIDocumentBaseUrl(
58
+ configuration: ReturningAIWidgetConfiguration,
59
+ ): string | undefined {
60
+ const url = configuration.content.url;
61
+ if (!isSecureUrl(url, configuration.debug) || url.hostname.length === 0) {
62
+ return undefined;
63
+ }
64
+ const port = url.port.length > 0 ? `:${url.port}` : "";
65
+ return `${url.protocol}//${url.hostname}${port}/`;
66
+ }
67
+
68
+ /**
69
+ * Expected web-message origin derived from the document base URL.
70
+ * @param configuration - Widget configuration
71
+ * @returns Normalized origin, or `undefined` when no secure base exists
72
+ */
73
+ export function returningAIWebMessageOrigin(
74
+ configuration: ReturningAIWidgetConfiguration,
75
+ ): string | undefined {
76
+ const baseUrl = returningAIDocumentBaseUrl(configuration);
77
+ if (baseUrl === undefined) {
78
+ return undefined;
79
+ }
80
+ return normalizeReturningAIOrigin(baseUrl);
81
+ }
82
+
83
+ /**
84
+ * Normalizes an origin string for case-insensitive comparison (trims trailing slashes).
85
+ * @param origin - Raw origin or base URL
86
+ * @returns Normalized origin
87
+ */
88
+ export function normalizeReturningAIOrigin(origin: string): string {
89
+ return origin.trim().replace(/\/+$/, "").toLowerCase();
90
+ }
91
+
92
+ /**
93
+ * Strict main-frame origin equality check for bridge message acceptance.
94
+ * @param isMainFrame - Must be true
95
+ * @param sourceOrigin - Message source origin
96
+ * @param expectedOrigin - Expected document origin
97
+ * @returns True when both origins match and the frame is main
98
+ */
99
+ export function shouldAcceptReturningAIWebMessage(
100
+ isMainFrame: boolean,
101
+ sourceOrigin: string,
102
+ expectedOrigin: string,
103
+ ): boolean {
104
+ if (!isMainFrame) {
105
+ return false;
106
+ }
107
+ const source = normalizeReturningAIOrigin(sourceOrigin);
108
+ const expected = normalizeReturningAIOrigin(expectedOrigin);
109
+ return source.length > 0 && source === expected;
110
+ }
111
+
112
+ /**
113
+ * RN-specific gate for delivering `onMessage` payloads to the coordinator.
114
+ * When no expected origin is configured, delivery is allowed (fail-open only then).
115
+ * iOS may report `about:blank` for HTML with a content-origin baseUrl; envelope identity still gates.
116
+ * @param input.sourceUrl - `nativeEvent.url` from react-native-webview
117
+ * @param input.expectedOrigin - Expected origin from configuration
118
+ * @returns True when the message should be decoded
119
+ */
120
+ export function shouldDeliverReturningAIWebMessage(input: {
121
+ sourceUrl: string | undefined;
122
+ expectedOrigin: string | undefined;
123
+ }): boolean {
124
+ if (input.expectedOrigin === undefined) {
125
+ return true;
126
+ }
127
+ const sourceUrl = input.sourceUrl;
128
+ if (sourceUrl === undefined || sourceUrl.length === 0) {
129
+ return false;
130
+ }
131
+ // react-native-webview on iOS reports about:blank for HTML loaded with a
132
+ // content-origin baseUrl. Envelope identity still gates the payload.
133
+ if (sourceUrl === "about:blank") {
134
+ return true;
135
+ }
136
+ try {
137
+ return shouldAcceptReturningAIWebMessage(true, new URL(sourceUrl).origin, input.expectedOrigin);
138
+ } catch {
139
+ return false;
140
+ }
141
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * @fileoverview Injected bootstrap that exposes ReturningAIReactNativeBridge.postMessage over ReactNativeWebView.
3
+ *
4
+ * Layer: webview
5
+ * Role: Installs a thin window bridge that forwards string messages to ReactNativeWebView.postMessage.
6
+ * Does not validate envelopes or handle host callbacks.
7
+ * See also: ReturningAIReactNativeWebViewDriver.ts, bridge/ReturningAIBridgeIdentity.ts
8
+ */
9
+
10
+ /**
11
+ * JavaScript injected before content loads to install `window.ReturningAIReactNativeBridge`.
12
+ * Forwards string messages to `ReactNativeWebView.postMessage`; does not validate envelopes.
13
+ * Trailing `true;` satisfies react-native-webview inject return requirements.
14
+ */
15
+ export const RETURNING_AI_REACT_NATIVE_BRIDGE_BOOTSTRAP = `(function() {
16
+ "use strict";
17
+ if (window.ReturningAIReactNativeBridge) return;
18
+ window.ReturningAIReactNativeBridge = {
19
+ postMessage: function(data) {
20
+ var webView = window.ReactNativeWebView;
21
+ if (!webView || typeof webView.postMessage !== "function") return;
22
+ webView.postMessage(typeof data === "string" ? data : String(data));
23
+ }
24
+ };
25
+ })();
26
+ true;`;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * @fileoverview Classifies WebView HTTP vs resource errors as terminal or non-terminal for the widget.
3
+ *
4
+ * Layer: webview
5
+ * Role: HTTP errors are never terminal; resource errors are terminal only for the main frame.
6
+ * Does not construct ReturningAIWidgetError instances or drive coordinator state.
7
+ * See also: ReturningAIWidget.tsx, coordinator/ReturningAIWidgetCoordinator.ts
8
+ */
9
+
10
+ /**
11
+ * Whether an HTTP error event should fail the widget session.
12
+ * Always non-terminal so subframe/status noise does not tear down the shell.
13
+ * @returns `false`
14
+ */
15
+ export function isReturningAIHttpErrorTerminal(): boolean {
16
+ return false;
17
+ }
18
+
19
+ /**
20
+ * Whether a resource/load error should fail the widget session.
21
+ * Terminal only for main-frame failures.
22
+ * @param isForMainFrame - Whether the error targeted the main frame
23
+ * @returns True when the coordinator should call `fail`
24
+ */
25
+ export function isReturningAIResourceErrorTerminal(isForMainFrame: boolean): boolean {
26
+ return isForMainFrame;
27
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * @fileoverview Builds the react-native-webview originWhitelist for production HTTPS or debug localhost.
3
+ *
4
+ * Layer: webview
5
+ * Role: Returns allowed origin patterns for the WebView; debug adds localhost/127.0.0.1 HTTP entries.
6
+ * Does not decide navigation allow/delegate/reject (navigation policy does).
7
+ * Security: Production whitelist is HTTPS + about:blank only.
8
+ * See also: navigation/ReturningAINavigationPolicy.ts, ReturningAIWidget.tsx
9
+ */
10
+
11
+ /**
12
+ * Builds the `originWhitelist` patterns for `react-native-webview`.
13
+ * Production allows HTTPS + `about:blank` only; debug also allows localhost HTTP.
14
+ * @param debug - Configuration debug flag
15
+ * @returns Origin pattern list for the WebView prop
16
+ */
17
+ export function returningAIOriginWhitelist(debug: boolean): string[] {
18
+ if (debug) {
19
+ return ["https://*", "http://localhost*", "http://127.0.0.1*", "about:blank"];
20
+ }
21
+ return ["https://*", "about:blank"];
22
+ }