@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,488 @@
1
+ /**
2
+ * @fileoverview Aggregates and validates the full ReturningAI widget host configuration.
3
+ *
4
+ * Layer: configuration
5
+ * Role: Combines descriptor, content, endpoints, theme, callbacks, and display options;
6
+ * validates HTTPS/localhost rules, IDs, and allowlists; exposes defaults for runtime URL.
7
+ * Does not authenticate, render HTML, or talk to the WebView.
8
+ * Security: Rejects insecure production URLs; never accepts access IDs/keys as public inputs.
9
+ * See also: ReturningAIWidgetEndpoints.ts, ReturningAIWidgetDescriptor.ts, urls.ts
10
+ */
11
+
12
+ import {
13
+ validateReturningAIJsonValue,
14
+ jsonStableString,
15
+ type ReturningAIJsonValue,
16
+ } from "../errors/json";
17
+ import { invalidConfiguration } from "../errors/ReturningAIWidgetError";
18
+ import { type ReturningAIFirstPaintColors } from "./ReturningAIFirstPaintColors";
19
+ import { ReturningAIWidgetContent } from "./ReturningAIWidgetContent";
20
+ import { ReturningAIWidgetDescriptor } from "./ReturningAIWidgetDescriptor";
21
+ import { ReturningAIWidgetDisplayOptions } from "./ReturningAIWidgetDisplayOptions";
22
+ import {
23
+ domainKeyAttributeValue,
24
+ type ReturningAIWidgetDomainKey,
25
+ ReturningAIWidgetDomainKey as DomainKey,
26
+ } from "./ReturningAIWidgetDomainKey";
27
+ import { formatEndpointUrl, ReturningAIWidgetEndpoints } from "./ReturningAIWidgetEndpoints";
28
+ import { ReturningAIWidgetTheme } from "./ReturningAIWidgetTheme";
29
+ import {
30
+ argbToRadixString,
31
+ formatUrl,
32
+ isSecureUrl,
33
+ isValidHost,
34
+ normalizeHost,
35
+ parseUrl,
36
+ } from "./urls";
37
+
38
+ const WIDGET_ID_PATTERN = /^[A-Za-z0-9_\-=]+$/;
39
+ const CALLBACK_NAME_PATTERN = /^[A-Za-z0-9_.:-]+$/;
40
+ const USER_IDENTIFIER_PATTERN = /^data-[A-Za-z0-9_.:-]+$/;
41
+ const STORAGE_PREFIX_PATTERN = /^[A-Za-z0-9_.:-]+$/;
42
+
43
+ /**
44
+ * Default unpkg IIFE runtime URL for `@returningai/widget-sdk`.
45
+ * Hosts may pin a different version via `runtimeUrl`.
46
+ */
47
+ export const DEFAULT_RUNTIME_URL =
48
+ "https://unpkg.com/@returningai/widget-sdk/dist/rai-widget.iife.js";
49
+
50
+ /**
51
+ * Default host-callback allowlist names registered unless the host overrides `callbackNames`.
52
+ * Hosts must still provide handlers for callbacks they intend to serve.
53
+ */
54
+ export const DEFAULT_CALLBACK_NAMES = Object.freeze([
55
+ "callbackFieldOptions",
56
+ "storePurchaseSuccess",
57
+ "milestoneCtaClick",
58
+ ]);
59
+
60
+ /**
61
+ * Host-supplied fields used to construct {@link ReturningAIWidgetConfiguration}.
62
+ * Never includes access IDs/keys; embed tokens are supplied separately via the provider.
63
+ */
64
+ export type ReturningAIWidgetConfigurationInput = {
65
+ /** Custom widget descriptor (`rai-custom-widget` + widget id). */
66
+ widget: ReturningAIWidgetDescriptor;
67
+ /** Bundle or page content locator. */
68
+ content: ReturningAIWidgetContent;
69
+ /** HTTPS origin of the embedding host (no path/query/fragment). */
70
+ clientOrigin: string | URL;
71
+ /** Optional explicit endpoints; defaults from `domainKey`. */
72
+ endpoints?: ReturningAIWidgetEndpoints;
73
+ /** Environment key selecting endpoint presets and `domain-key` attribute. */
74
+ domainKey?: ReturningAIWidgetDomainKey;
75
+ /** Theme preference before platform resolution. */
76
+ theme?: (typeof ReturningAIWidgetTheme)[keyof typeof ReturningAIWidgetTheme];
77
+ /** BCP 47 locale; emitted as HTML `language` / `locale` attributes. */
78
+ locale?: string;
79
+ /** Shell display / auto-height preferences. */
80
+ display?: ReturningAIWidgetDisplayOptions;
81
+ /** Optional `data-*` user identifier attributes for auth without embed token. */
82
+ userIdentifiers?: Record<string, string>;
83
+ /** Optional JSON custom data attribute payload (never credentials). */
84
+ customData?: ReturningAIJsonValue;
85
+ /** Web storage prefix for the custom element. */
86
+ storagePrefix?: string;
87
+ /** Runtime retry count (0–10). */
88
+ maxRetries?: number;
89
+ /** Delay between retries in milliseconds. */
90
+ retryDelayMilliseconds?: number;
91
+ /** Height-change debounce in milliseconds. */
92
+ heightDebounceMilliseconds?: number;
93
+ /** Optional first-paint color overrides. */
94
+ firstPaintColors?: ReturningAIFirstPaintColors;
95
+ /** Optional first-paint font attribute. */
96
+ firstPaintFont?: string;
97
+ /** Widget runtime IIFE URL (defaults to {@link DEFAULT_RUNTIME_URL}). */
98
+ runtimeUrl?: string | URL;
99
+ /** Allowlisted host callback names (defaults to {@link DEFAULT_CALLBACK_NAMES}). */
100
+ callbackNames?: Iterable<string>;
101
+ /** Extra trusted navigation hostnames beyond derived endpoints. */
102
+ allowedNavigationHosts?: Iterable<string>;
103
+ /** Auth exchange timeout in milliseconds (1–120s). */
104
+ authenticationTimeoutMilliseconds?: number;
105
+ /** Host callback timeout in milliseconds (1–120s). */
106
+ callbackTimeoutMilliseconds?: number;
107
+ /** Ready timeout in milliseconds (1–300s). */
108
+ readyTimeoutMilliseconds?: number;
109
+ /** When true, allows localhost HTTP endpoints and expands originWhitelist. */
110
+ debug?: boolean;
111
+ };
112
+
113
+ /**
114
+ * Immutable validated host configuration for one widget session.
115
+ * Call {@link validated} before starting the coordinator; use {@link sessionFingerprint}
116
+ * to decide when a new session is required.
117
+ */
118
+ export class ReturningAIWidgetConfiguration {
119
+ /** Custom widget descriptor. */
120
+ readonly widget: ReturningAIWidgetDescriptor;
121
+ /** Bundle or page content. */
122
+ readonly content: ReturningAIWidgetContent;
123
+ /** Validated HTTPS client origin. */
124
+ readonly clientOrigin: URL;
125
+ /** Auth/API/socket endpoint set. */
126
+ readonly endpoints: ReturningAIWidgetEndpoints;
127
+ /** Environment domain key. */
128
+ readonly domainKey: ReturningAIWidgetDomainKey;
129
+ /** Theme preference. */
130
+ readonly theme: (typeof ReturningAIWidgetTheme)[keyof typeof ReturningAIWidgetTheme];
131
+ /** Optional locale string. */
132
+ readonly locale?: string;
133
+ /** Display options. */
134
+ readonly display: ReturningAIWidgetDisplayOptions;
135
+ /** Frozen `data-*` user identifiers. */
136
+ readonly userIdentifiers: Readonly<Record<string, string>>;
137
+ /** Optional JSON custom data. */
138
+ readonly customData?: ReturningAIJsonValue;
139
+ /** Web storage prefix. */
140
+ readonly storagePrefix: string;
141
+ /** Max runtime retries. */
142
+ readonly maxRetries: number;
143
+ /** Retry delay in ms. */
144
+ readonly retryDelayMilliseconds: number;
145
+ /** Height debounce in ms. */
146
+ readonly heightDebounceMilliseconds: number;
147
+ /** Optional first-paint colors. */
148
+ readonly firstPaintColors?: ReturningAIFirstPaintColors;
149
+ /** Optional first-paint font. */
150
+ readonly firstPaintFont?: string;
151
+ /** Runtime IIFE URL. */
152
+ readonly runtimeUrl: URL;
153
+ /** Allowlisted callback names. */
154
+ readonly callbackNames: ReadonlySet<string>;
155
+ /** Extra trusted navigation hosts. */
156
+ readonly allowedNavigationHosts: ReadonlySet<string>;
157
+ /** Auth timeout in ms. */
158
+ readonly authenticationTimeoutMilliseconds: number;
159
+ /** Callback timeout in ms. */
160
+ readonly callbackTimeoutMilliseconds: number;
161
+ /** Ready timeout in ms. */
162
+ readonly readyTimeoutMilliseconds: number;
163
+ /** Debug flag enabling localhost HTTP. */
164
+ readonly debug: boolean;
165
+
166
+ /** Parsed {@link DEFAULT_RUNTIME_URL}. */
167
+ static readonly defaultRuntimeUrl = new URL(DEFAULT_RUNTIME_URL);
168
+ /** Default callback allowlist as a mutable `Set` copy source. */
169
+ static readonly defaultCallbackNames = new Set(DEFAULT_CALLBACK_NAMES);
170
+
171
+ /**
172
+ * Builds configuration with SDK defaults applied.
173
+ * Does not fully validate; call {@link validated} before use.
174
+ * @param input - Host configuration fields
175
+ */
176
+ constructor(input: ReturningAIWidgetConfigurationInput) {
177
+ this.widget = input.widget;
178
+ this.content = input.content;
179
+ this.clientOrigin = parseUrl(input.clientOrigin);
180
+ this.domainKey = input.domainKey ?? DomainKey.prod;
181
+ this.endpoints = input.endpoints ?? endpointsForDomain(this.domainKey);
182
+ this.theme = input.theme ?? ReturningAIWidgetTheme.system;
183
+ this.locale = input.locale;
184
+ this.display = input.display ?? new ReturningAIWidgetDisplayOptions();
185
+ this.userIdentifiers = Object.freeze(normalizeUserIdentifiers(input.userIdentifiers ?? {}));
186
+ this.customData =
187
+ input.customData === undefined ? undefined : validateReturningAIJsonValue(input.customData);
188
+ this.storagePrefix = input.storagePrefix ?? "returning-ai-widget";
189
+ this.maxRetries = input.maxRetries ?? 3;
190
+ this.retryDelayMilliseconds = input.retryDelayMilliseconds ?? 500;
191
+ this.heightDebounceMilliseconds = input.heightDebounceMilliseconds ?? 100;
192
+ this.firstPaintColors = input.firstPaintColors;
193
+ this.firstPaintFont = input.firstPaintFont;
194
+ this.runtimeUrl = parseUrl(input.runtimeUrl ?? DEFAULT_RUNTIME_URL);
195
+ this.callbackNames = Object.freeze(new Set(input.callbackNames ?? DEFAULT_CALLBACK_NAMES));
196
+ this.allowedNavigationHosts = Object.freeze(
197
+ new Set([...(input.allowedNavigationHosts ?? [])].map((host) => normalizeHost(host))),
198
+ );
199
+ this.authenticationTimeoutMilliseconds = input.authenticationTimeoutMilliseconds ?? 15_000;
200
+ this.callbackTimeoutMilliseconds = input.callbackTimeoutMilliseconds ?? 15_000;
201
+ this.readyTimeoutMilliseconds = input.readyTimeoutMilliseconds ?? 30_000;
202
+ this.debug = input.debug ?? false;
203
+ }
204
+
205
+ /**
206
+ * Convenience factory for a custom product embed with a bundle URL.
207
+ * @param input - Configuration fields plus `widgetId` and `bundleUrl`
208
+ * @returns Configuration with {@link ReturningAIWidgetDescriptor.custom} + bundle content
209
+ */
210
+ static customBundle(
211
+ input: Omit<ReturningAIWidgetConfigurationInput, "widget" | "content"> & {
212
+ widgetId: string;
213
+ bundleUrl: string | URL;
214
+ },
215
+ ): ReturningAIWidgetConfiguration {
216
+ const { widgetId, bundleUrl, ...rest } = input;
217
+ return new ReturningAIWidgetConfiguration({
218
+ ...rest,
219
+ widget: ReturningAIWidgetDescriptor.custom(widgetId),
220
+ content: ReturningAIWidgetContent.bundle(bundleUrl),
221
+ });
222
+ }
223
+
224
+ /**
225
+ * Returns a new configuration with selected fields replaced.
226
+ * @param patch - Partial input fields to override
227
+ * @returns New configuration instance
228
+ */
229
+ copyWith(patch: Partial<ReturningAIWidgetConfigurationInput>): ReturningAIWidgetConfiguration {
230
+ return new ReturningAIWidgetConfiguration({
231
+ widget: patch.widget ?? this.widget,
232
+ content: patch.content ?? this.content,
233
+ clientOrigin: patch.clientOrigin ?? this.clientOrigin,
234
+ endpoints: patch.endpoints ?? this.endpoints,
235
+ domainKey: patch.domainKey ?? this.domainKey,
236
+ theme: patch.theme ?? this.theme,
237
+ locale: patch.locale === undefined ? this.locale : patch.locale,
238
+ display: patch.display ?? this.display,
239
+ userIdentifiers: patch.userIdentifiers ?? { ...this.userIdentifiers },
240
+ customData: patch.customData === undefined ? this.customData : patch.customData,
241
+ storagePrefix: patch.storagePrefix ?? this.storagePrefix,
242
+ maxRetries: patch.maxRetries ?? this.maxRetries,
243
+ retryDelayMilliseconds: patch.retryDelayMilliseconds ?? this.retryDelayMilliseconds,
244
+ heightDebounceMilliseconds:
245
+ patch.heightDebounceMilliseconds ?? this.heightDebounceMilliseconds,
246
+ firstPaintColors:
247
+ patch.firstPaintColors === undefined ? this.firstPaintColors : patch.firstPaintColors,
248
+ firstPaintFont:
249
+ patch.firstPaintFont === undefined ? this.firstPaintFont : patch.firstPaintFont,
250
+ runtimeUrl: patch.runtimeUrl ?? this.runtimeUrl,
251
+ callbackNames: patch.callbackNames ?? this.callbackNames,
252
+ allowedNavigationHosts: patch.allowedNavigationHosts ?? this.allowedNavigationHosts,
253
+ authenticationTimeoutMilliseconds:
254
+ patch.authenticationTimeoutMilliseconds ?? this.authenticationTimeoutMilliseconds,
255
+ callbackTimeoutMilliseconds:
256
+ patch.callbackTimeoutMilliseconds ?? this.callbackTimeoutMilliseconds,
257
+ readyTimeoutMilliseconds: patch.readyTimeoutMilliseconds ?? this.readyTimeoutMilliseconds,
258
+ debug: patch.debug ?? this.debug,
259
+ });
260
+ }
261
+
262
+ /**
263
+ * Validates HTTPS rules, IDs, allowlists, timeouts, and display bounds.
264
+ * @returns `this` when valid (for fluent use)
265
+ * @throws {ReturningAIWidgetError} with `invalidConfiguration` when validation fails
266
+ */
267
+ validated(): ReturningAIWidgetConfiguration {
268
+ this.validateClientOrigin();
269
+ for (const identifier of this.widget.identifiers) {
270
+ const trimmed = identifier.trim();
271
+ if (trimmed.length < 8 || !WIDGET_ID_PATTERN.test(trimmed)) {
272
+ throw invalidConfiguration(
273
+ "Widget identifiers must contain at least eight URL-safe characters.",
274
+ );
275
+ }
276
+ }
277
+ for (const url of [this.runtimeUrl, this.content.url, ...this.endpoints.allUrls]) {
278
+ if (!isSecureUrl(url, this.debug)) {
279
+ throw invalidConfiguration("Widget, runtime, and endpoint URLs must use HTTPS.");
280
+ }
281
+ }
282
+ if (this.locale !== undefined && this.locale.trim().length === 0) {
283
+ throw invalidConfiguration("Locale cannot be empty.");
284
+ }
285
+ for (const name of this.callbackNames) {
286
+ if (name.length === 0 || !CALLBACK_NAME_PATTERN.test(name)) {
287
+ throw invalidConfiguration(
288
+ "Callback names may contain letters, numbers, dots, colons, underscores, and hyphens.",
289
+ );
290
+ }
291
+ }
292
+ for (const [key, value] of Object.entries(this.userIdentifiers)) {
293
+ if (!USER_IDENTIFIER_PATTERN.test(key) || value.trim().length === 0) {
294
+ throw invalidConfiguration(
295
+ "User identifier keys must be data-* attributes with nonempty values.",
296
+ );
297
+ }
298
+ }
299
+ if (
300
+ this.storagePrefix.trim().length === 0 ||
301
+ !STORAGE_PREFIX_PATTERN.test(this.storagePrefix)
302
+ ) {
303
+ throw invalidConfiguration("Storage prefix must be a nonempty safe identifier.");
304
+ }
305
+ if (this.maxRetries < 0 || this.maxRetries > 10) {
306
+ throw invalidConfiguration("Maximum retries must be between 0 and 10.");
307
+ }
308
+ validateDelay("Retry delay", this.retryDelayMilliseconds, 0, 30_000);
309
+ validateDelay("Height debounce", this.heightDebounceMilliseconds, 0, 5_000);
310
+ for (const host of this.allowedNavigationHosts) {
311
+ if (!isValidHost(host)) {
312
+ throw invalidConfiguration("Trusted navigation hosts must be hostnames.");
313
+ }
314
+ }
315
+ validateTimeout("Authentication timeout", this.authenticationTimeoutMilliseconds, 1, 120);
316
+ validateTimeout("Callback timeout", this.callbackTimeoutMilliseconds, 1, 120);
317
+ validateTimeout("Ready timeout", this.readyTimeoutMilliseconds, 1, 300);
318
+ this.validateDisplay();
319
+ return this;
320
+ }
321
+
322
+ /**
323
+ * Union of configured allowed hosts plus hosts derived from origin/runtime/content/endpoints.
324
+ * @returns Frozen set of trusted navigation hostnames
325
+ */
326
+ get requiredNavigationHosts(): ReadonlySet<string> {
327
+ const urls = [this.clientOrigin, this.runtimeUrl, this.content.url, ...this.endpoints.allUrls];
328
+ const hosts = new Set(this.allowedNavigationHosts);
329
+ for (const url of urls) {
330
+ if (url.hostname.length > 0) {
331
+ hosts.add(normalizeHost(url.hostname));
332
+ }
333
+ }
334
+ return Object.freeze(hosts);
335
+ }
336
+
337
+ /**
338
+ * Stable identity string for deciding when the RN shell must start a new session.
339
+ * Theme alone is intentionally excluded so system brightness can update in place.
340
+ * @returns Unit-separator-joined fingerprint
341
+ */
342
+ get sessionFingerprint(): string {
343
+ const parts: string[] = [
344
+ this.widget.widgetType,
345
+ this.widget.authenticationWidgetId,
346
+ ...sortedMap(this.widget.attributes),
347
+ this.content.kind,
348
+ formatUrl(this.content.url),
349
+ formatUrl(this.clientOrigin),
350
+ domainKeyAttributeValue(this.domainKey),
351
+ formatUrl(this.runtimeUrl),
352
+ ...this.sortedEndpoints(),
353
+ this.locale ?? "",
354
+ argbToRadixString(this.display.backgroundColor),
355
+ this.display.loadingText,
356
+ String(this.display.autoRefresh),
357
+ String(this.display.autoHeight),
358
+ String(this.display.initialHeight),
359
+ String(this.display.minHeight),
360
+ String(this.display.maxHeight),
361
+ ...sortedMap(this.userIdentifiers),
362
+ jsonStableString(this.customData),
363
+ this.storagePrefix,
364
+ String(this.maxRetries),
365
+ String(this.retryDelayMilliseconds),
366
+ String(this.heightDebounceMilliseconds),
367
+ this.firstPaintColors?.fingerprint ?? "",
368
+ this.firstPaintFont ?? "",
369
+ ...[...this.callbackNames].sort(),
370
+ ...[...this.requiredNavigationHosts].sort(),
371
+ String(this.authenticationTimeoutMilliseconds),
372
+ String(this.callbackTimeoutMilliseconds),
373
+ String(this.readyTimeoutMilliseconds),
374
+ String(this.debug),
375
+ ];
376
+ return parts.join("\u001f");
377
+ }
378
+
379
+ /** Ensures clientOrigin is HTTPS with empty path and no userinfo/query/fragment. */
380
+ private validateClientOrigin(): void {
381
+ const scheme = this.clientOrigin.protocol.replace(/:$/, "").toLowerCase();
382
+ const host = this.clientOrigin.hostname;
383
+ const path = this.clientOrigin.pathname;
384
+ if (
385
+ scheme !== "https" ||
386
+ host.length === 0 ||
387
+ this.clientOrigin.search.length > 0 ||
388
+ this.clientOrigin.hash.length > 0 ||
389
+ this.clientOrigin.username.length > 0 ||
390
+ this.clientOrigin.password.length > 0 ||
391
+ !(path === "" || path === "/")
392
+ ) {
393
+ throw invalidConfiguration(
394
+ "Client origin must be an HTTPS origin without a path, query, or fragment.",
395
+ );
396
+ }
397
+ }
398
+
399
+ /** Ensures auto-height bounds are finite and ordered. */
400
+ private validateDisplay(): void {
401
+ const values = [this.display.initialHeight, this.display.minHeight, this.display.maxHeight];
402
+ if (
403
+ values.some((value) => !Number.isFinite(value) || value <= 0) ||
404
+ this.display.minHeight > this.display.maxHeight ||
405
+ this.display.initialHeight < this.display.minHeight ||
406
+ this.display.initialHeight > this.display.maxHeight
407
+ ) {
408
+ throw invalidConfiguration("Automatic height bounds must be valid.");
409
+ }
410
+ }
411
+
412
+ /** Sorted endpoint fingerprint fragments for {@link sessionFingerprint}. */
413
+ private sortedEndpoints(): string[] {
414
+ const entries = [
415
+ `widgetAuthUrl=${formatEndpointUrl(this.endpoints.widgetAuthUrl)}`,
416
+ `apiV2Url=${formatEndpointUrl(this.endpoints.apiV2Url)}`,
417
+ ];
418
+ if (this.endpoints.widgetPathV2Url) {
419
+ entries.push(`widgetPathV2Url=${formatEndpointUrl(this.endpoints.widgetPathV2Url)}`);
420
+ }
421
+ if (this.endpoints.baseUrl) {
422
+ entries.push(`baseUrl=${formatEndpointUrl(this.endpoints.baseUrl)}`);
423
+ }
424
+ if (this.endpoints.authApiUrl) {
425
+ entries.push(`authApiUrl=${formatEndpointUrl(this.endpoints.authApiUrl)}`);
426
+ }
427
+ if (this.endpoints.socketV2Url) {
428
+ entries.push(`socketV2Url=${formatEndpointUrl(this.endpoints.socketV2Url)}`);
429
+ }
430
+ if (this.endpoints.socketUrl) {
431
+ entries.push(`socketUrl=${formatEndpointUrl(this.endpoints.socketUrl)}`);
432
+ }
433
+ if (this.endpoints.channelApiUrl) {
434
+ entries.push(`channelApiUrl=${formatEndpointUrl(this.endpoints.channelApiUrl)}`);
435
+ }
436
+ if (this.endpoints.mfeUrl) {
437
+ entries.push(`mfeUrl=${formatEndpointUrl(this.endpoints.mfeUrl)}`);
438
+ }
439
+ return entries.sort();
440
+ }
441
+ }
442
+
443
+ /** Maps a domain key to the matching endpoint preset. */
444
+ function endpointsForDomain(key: ReturningAIWidgetDomainKey): ReturningAIWidgetEndpoints {
445
+ switch (key) {
446
+ case "sgtr":
447
+ return ReturningAIWidgetEndpoints.sgtr;
448
+ case "stg":
449
+ return ReturningAIWidgetEndpoints.staging;
450
+ case "prod":
451
+ return ReturningAIWidgetEndpoints.production;
452
+ case "local":
453
+ return ReturningAIWidgetEndpoints.local;
454
+ }
455
+ }
456
+
457
+ function validateTimeout(
458
+ label: string,
459
+ timeoutMs: number,
460
+ minSeconds: number,
461
+ maxSeconds: number,
462
+ ): void {
463
+ const seconds = timeoutMs / 1000;
464
+ if (seconds < minSeconds || seconds > maxSeconds) {
465
+ throw invalidConfiguration(`${label} must be between ${minSeconds} and ${maxSeconds} seconds.`);
466
+ }
467
+ }
468
+
469
+ function validateDelay(label: string, timeoutMs: number, minMs: number, maxMs: number): void {
470
+ if (timeoutMs < minMs || timeoutMs > maxMs) {
471
+ throw invalidConfiguration(`${label} must be between ${minMs} and ${maxMs} milliseconds.`);
472
+ }
473
+ }
474
+
475
+ function sortedMap(map: Record<string, string> | Readonly<Record<string, string>>): string[] {
476
+ return Object.entries(map)
477
+ .map(([key, value]) => `${key}=${value}`)
478
+ .sort();
479
+ }
480
+
481
+ /** Lowercases `data-*` user identifier keys for stable fingerprints. */
482
+ function normalizeUserIdentifiers(identifiers: Record<string, string>): Record<string, string> {
483
+ const normalized: Record<string, string> = {};
484
+ for (const [key, value] of Object.entries(identifiers)) {
485
+ normalized[key.toLowerCase()] = value;
486
+ }
487
+ return normalized;
488
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * @fileoverview Models widget content as either a custom-widget bundle URL or a hosted page URL.
3
+ *
4
+ * Layer: configuration
5
+ * Role: Typed factories for bundle vs page content and a normalized URL string accessor.
6
+ * Does not validate HTTPS policy (that lives on ReturningAIWidgetConfiguration).
7
+ * See also: ReturningAIWidgetConfiguration.ts, urls.ts
8
+ */
9
+
10
+ import { formatUrl, parseUrl } from "./urls";
11
+
12
+ /**
13
+ * Discriminator for how the custom element loads product UI.
14
+ * - `bundle`: `bundle-url` pointing at `/custom-widget/bundle/<kind>/widget.js`
15
+ * - `page`: `widget-url` pointing at a hosted page
16
+ */
17
+ export type ReturningAIWidgetContentKind = "bundle" | "page";
18
+
19
+ /**
20
+ * Immutable content locator for the custom widget element.
21
+ * Prefer {@link ReturningAIWidgetContent.bundle} for gallery-style product embeds.
22
+ */
23
+ export class ReturningAIWidgetContent {
24
+ /** Whether this content is a JS bundle or a hosted page. */
25
+ readonly kind: ReturningAIWidgetContentKind;
26
+ /** Absolute content URL (HTTPS in production; validated by configuration). */
27
+ readonly url: URL;
28
+
29
+ private constructor(kind: ReturningAIWidgetContentKind, url: string | URL) {
30
+ this.kind = kind;
31
+ this.url = parseUrl(url);
32
+ }
33
+
34
+ /**
35
+ * Content that loads a custom-widget JS bundle.
36
+ * @param url - Absolute `widget.js` (or equivalent) bundle URL
37
+ * @returns Bundle content descriptor
38
+ */
39
+ static bundle(url: string | URL): ReturningAIWidgetContent {
40
+ return new ReturningAIWidgetContent("bundle", url);
41
+ }
42
+
43
+ /**
44
+ * Content that loads a hosted widget page URL.
45
+ * @param url - Absolute page URL
46
+ * @returns Page content descriptor
47
+ */
48
+ static page(url: string | URL): ReturningAIWidgetContent {
49
+ return new ReturningAIWidgetContent("page", url);
50
+ }
51
+
52
+ /**
53
+ * Formats {@link url} with the SDK's HTTPS-origin-friendly string rules.
54
+ * @returns Canonical URL string for fingerprinting and HTML attributes
55
+ */
56
+ get urlString(): string {
57
+ return formatUrl(this.url);
58
+ }
59
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * @fileoverview Describes which custom widget element and attributes the shell should mount.
3
+ *
4
+ * Layer: configuration
5
+ * Role: Builds `rai-custom-widget` descriptors with widget-id and auth widget id;
6
+ * freezes attributes/identifiers. Does not map first-class web element types.
7
+ * See also: ReturningAIWidgetConfiguration.ts, rendering/htmlRenderer.ts
8
+ */
9
+
10
+ /**
11
+ * Descriptor for the custom element the HTML shell mounts.
12
+ * Flutter/RN hosts use custom product embeds only (`rai-custom-widget`), not first-class web tags.
13
+ */
14
+ export class ReturningAIWidgetDescriptor {
15
+ /** Logical widget type (`custom` for mobile product embeds). */
16
+ readonly widgetType: string;
17
+ /** Custom element tag written into the shell (`rai-custom-widget`). */
18
+ readonly elementTag: string;
19
+ /** Widget id used in the auth URL path segment (base64 Mongo `_id` for customs). */
20
+ readonly authenticationWidgetId: string;
21
+ /** HTML attributes applied to the custom element (includes `widget-id`). */
22
+ readonly attributes: Readonly<Record<string, string>>;
23
+ /** Identifier strings validated by configuration (typically the widget id). */
24
+ readonly identifiers: readonly string[];
25
+
26
+ private constructor(input: {
27
+ widgetType: string;
28
+ elementTag: string;
29
+ authenticationWidgetId: string;
30
+ attributes: Record<string, string>;
31
+ identifiers: string[];
32
+ }) {
33
+ this.widgetType = input.widgetType;
34
+ this.elementTag = input.elementTag;
35
+ this.authenticationWidgetId = input.authenticationWidgetId;
36
+ this.attributes = Object.freeze({ ...input.attributes });
37
+ this.identifiers = Object.freeze([...input.identifiers]);
38
+ }
39
+
40
+ /**
41
+ * Builds a custom-widget descriptor for a product embed.
42
+ * @param widgetId - Custom `widget-id` (base64 of Mongo `_id`); used for auth and attributes
43
+ * @returns Frozen custom descriptor
44
+ */
45
+ static custom(widgetId: string): ReturningAIWidgetDescriptor {
46
+ return new ReturningAIWidgetDescriptor({
47
+ widgetType: "custom",
48
+ elementTag: "rai-custom-widget",
49
+ authenticationWidgetId: widgetId,
50
+ attributes: { "widget-id": widgetId },
51
+ identifiers: [widgetId],
52
+ });
53
+ }
54
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * @fileoverview Host display preferences for shell background, copy, and auto-height behavior.
3
+ *
4
+ * Layer: configuration
5
+ * Role: Holds background color, loading text, autoRefresh/autoHeight, and height bounds.
6
+ * Does not resolve system theme or paint the React Native shell.
7
+ * See also: ReturningAIWidgetConfiguration.ts, rendering/theme.ts
8
+ */
9
+
10
+ /**
11
+ * Host display preferences for the native shell and auto-height behavior.
12
+ * Height bounds are validated by {@link ReturningAIWidgetConfiguration.validated}.
13
+ */
14
+ export class ReturningAIWidgetDisplayOptions {
15
+ /** ARGB shell background; alpha `0` means “use theme default”. */
16
+ readonly backgroundColor: number;
17
+ /** Optional loading copy forwarded to the custom element `loading-text` attribute. */
18
+ readonly loadingText: string;
19
+ /** Whether the custom element should auto-refresh (`auto-refresh` attribute). */
20
+ readonly autoRefresh: boolean;
21
+ /** When true, the RN shell resizes from `rai-height-change` within min/max bounds. */
22
+ readonly autoHeight: boolean;
23
+ /** Starting shell height in density-independent pixels. */
24
+ readonly initialHeight: number;
25
+ /** Minimum auto-height clamp. */
26
+ readonly minHeight: number;
27
+ /** Maximum auto-height clamp. */
28
+ readonly maxHeight: number;
29
+
30
+ /**
31
+ * Creates display options with SDK defaults.
32
+ * @param input.backgroundColor - ARGB color (default transparent → theme shell color)
33
+ * @param input.loadingText - Optional loading label
34
+ * @param input.autoRefresh - Default `true`
35
+ * @param input.autoHeight - Default `false`
36
+ * @param input.initialHeight - Default `320`
37
+ * @param input.minHeight - Default `1`
38
+ * @param input.maxHeight - Default `10000`
39
+ */
40
+ constructor(
41
+ input: {
42
+ backgroundColor?: number;
43
+ loadingText?: string;
44
+ autoRefresh?: boolean;
45
+ autoHeight?: boolean;
46
+ initialHeight?: number;
47
+ minHeight?: number;
48
+ maxHeight?: number;
49
+ } = {},
50
+ ) {
51
+ this.backgroundColor = input.backgroundColor ?? 0x00000000;
52
+ this.loadingText = input.loadingText ?? "";
53
+ this.autoRefresh = input.autoRefresh ?? true;
54
+ this.autoHeight = input.autoHeight ?? false;
55
+ this.initialHeight = input.initialHeight ?? 320;
56
+ this.minHeight = input.minHeight ?? 1;
57
+ this.maxHeight = input.maxHeight ?? 10000;
58
+ }
59
+ }