@oxvo/ai-live-assist 7.5.26 → 7.5.27

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 (51) hide show
  1. package/cjs/AiLiveAssist.d.ts +1 -1
  2. package/cjs/client.d.ts +7 -0
  3. package/cjs/client.js +12 -0
  4. package/cjs/guideMeasurement.d.ts +1 -1
  5. package/cjs/guideMeasurement.js +1 -1
  6. package/cjs/liveControlChannel.d.ts +3 -1
  7. package/cjs/liveControlChannel.js +4 -1
  8. package/cjs/liveGuideWidget.d.ts +20 -2
  9. package/cjs/liveGuideWidget.js +39 -8
  10. package/cjs/merchantPreview.d.ts +5 -0
  11. package/cjs/merchantPreview.js +148 -0
  12. package/cjs/merchantPreviewAdmission.d.ts +32 -0
  13. package/cjs/merchantPreviewAdmission.js +184 -0
  14. package/cjs/merchantPreviewOrigins.d.ts +6 -0
  15. package/cjs/merchantPreviewOrigins.js +24 -0
  16. package/cjs/merchantPreviewStorage.d.ts +9 -0
  17. package/cjs/merchantPreviewStorage.js +56 -0
  18. package/cjs/merchantPreviewTypes.d.ts +57 -0
  19. package/cjs/merchantPreviewTypes.js +2 -0
  20. package/cjs/standalone.d.ts +2 -0
  21. package/cjs/standalone.js +3 -1
  22. package/cjs/ui.d.ts +1 -0
  23. package/cjs/ui.js +8 -0
  24. package/cjs/version.d.ts +1 -1
  25. package/cjs/version.js +1 -1
  26. package/lib/AiLiveAssist.d.ts +1 -1
  27. package/lib/client.d.ts +7 -0
  28. package/lib/client.js +12 -0
  29. package/lib/guideMeasurement.d.ts +1 -1
  30. package/lib/guideMeasurement.js +1 -1
  31. package/lib/liveControlChannel.d.ts +3 -1
  32. package/lib/liveControlChannel.js +4 -1
  33. package/lib/liveGuideWidget.d.ts +20 -2
  34. package/lib/liveGuideWidget.js +39 -8
  35. package/lib/merchantPreview.d.ts +5 -0
  36. package/lib/merchantPreview.js +144 -0
  37. package/lib/merchantPreviewAdmission.d.ts +32 -0
  38. package/lib/merchantPreviewAdmission.js +179 -0
  39. package/lib/merchantPreviewOrigins.d.ts +6 -0
  40. package/lib/merchantPreviewOrigins.js +18 -0
  41. package/lib/merchantPreviewStorage.d.ts +9 -0
  42. package/lib/merchantPreviewStorage.js +50 -0
  43. package/lib/merchantPreviewTypes.d.ts +57 -0
  44. package/lib/merchantPreviewTypes.js +1 -0
  45. package/lib/standalone.d.ts +2 -0
  46. package/lib/standalone.js +1 -0
  47. package/lib/ui.d.ts +1 -0
  48. package/lib/ui.js +8 -0
  49. package/lib/version.d.ts +1 -1
  50. package/lib/version.js +1 -1
  51. package/package.json +1 -1
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isLoopbackHostname = void 0;
4
+ exports.isLocalConsoleOrigin = isLocalConsoleOrigin;
5
+ exports.isPreviewRuntimeOrigin = isPreviewRuntimeOrigin;
6
+ const isLoopbackHostname = (hostname) => hostname === 'localhost' ||
7
+ hostname.endsWith('.localhost') || /^127(?:\.\d{1,3}){3}$/.test(hostname) || hostname === '[::1]';
8
+ exports.isLoopbackHostname = isLoopbackHostname;
9
+ function isLocalConsoleOrigin(value) {
10
+ try {
11
+ const url = new URL(value);
12
+ return value === url.origin && ['http:', 'https:'].includes(url.protocol) &&
13
+ !url.username && !url.password && (0, exports.isLoopbackHostname)(url.hostname);
14
+ }
15
+ catch {
16
+ return false;
17
+ }
18
+ }
19
+ // The dev alias is accepted only for a preview whose installed loader pinned a local Console.
20
+ function isPreviewRuntimeOrigin(url, policy = {}) {
21
+ return url.protocol === 'https:' || (url.protocol === 'http:' && ((0, exports.isLoopbackHostname)(url.hostname) ||
22
+ (url.hostname === 'oxvosessions.local' && typeof policy.developmentConsoleOrigin === 'string' &&
23
+ isLocalConsoleOrigin(policy.developmentConsoleOrigin))));
24
+ }
@@ -0,0 +1,9 @@
1
+ import type { MerchantPreviewBootstrap, MerchantPreviewOptions } from './merchantPreviewTypes.js';
2
+ export declare function merchantPreviewNamespace(origin: string, previewId: string): string;
3
+ export declare function merchantPreviewStorageKeys(preview: Pick<MerchantPreviewOptions, 'targetOrigin' | 'previewId'>): {
4
+ namespace: string;
5
+ original: string;
6
+ recovery: string;
7
+ };
8
+ export declare function saveMerchantPreviewRecovery(preview: MerchantPreviewOptions, bootstrap: MerchantPreviewBootstrap, storage: Storage): void;
9
+ export declare function readMerchantPreviewRecovery(preview: MerchantPreviewOptions, storage: Storage): MerchantPreviewBootstrap | null;
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.merchantPreviewNamespace = merchantPreviewNamespace;
4
+ exports.merchantPreviewStorageKeys = merchantPreviewStorageKeys;
5
+ exports.saveMerchantPreviewRecovery = saveMerchantPreviewRecovery;
6
+ exports.readMerchantPreviewRecovery = readMerchantPreviewRecovery;
7
+ const guideTypes_js_1 = require("./guideTypes.js");
8
+ const invalid = () => new Error('The previous preview could not be recovered. Return to the original Console tab to check its status or wait for it to expire.');
9
+ const PREVIEW_FIELDS = ['previewId', 'projectId', 'guideId', 'configurationVersionId', 'configurationRevision',
10
+ 'configurationChecksum', 'targetOrigin', 'targetPath', 'launchExpiresAt', 'expiresAt', 'runtimeUrl', 'widgetVersion'];
11
+ const BOOTSTRAP_FIELDS = ['schemaVersion', 'projectId', 'guideId', 'installKey', 'protocol', 'available', 'configRevision',
12
+ 'configChecksum', 'providerProtocol', 'providerModel', 'liveCapabilities', 'liveAssets', 'widgetVersion',
13
+ 'experienceMode', 'replayRecordingEnabled', 'capabilities', 'consent', 'cache', 'merchantPreview'];
14
+ const APPEARANCE_FIELDS = ['brandName', 'launcherLabel', 'accent', 'position', 'panelWidth', 'glassEffect',
15
+ 'hideLauncherWhenVisitorLimited', 'theme', 'welcomeMessage', 'compactEntryEnabled'];
16
+ function merchantPreviewNamespace(origin, previewId) {
17
+ if (new URL(origin).origin !== origin || !guideTypes_js_1.GUIDE_UUID_PATTERN.test(previewId))
18
+ throw invalid();
19
+ return `merchant_preview_v1_${encodeURIComponent(origin)}_${previewId}`;
20
+ }
21
+ function merchantPreviewStorageKeys(preview) {
22
+ const namespace = merchantPreviewNamespace(preview.targetOrigin, preview.previewId);
23
+ return { namespace, original: `__oxvo_ai_guide_preview_launch_${namespace}`, recovery: `__oxvo_ai_guide_preview_recovery_${namespace}` };
24
+ }
25
+ const pick = (value, fields) => Object.fromEntries(fields.filter(key => key in value)
26
+ .map(key => [key, value[key]]));
27
+ function saveMerchantPreviewRecovery(preview, bootstrap, storage) {
28
+ const presentation = { ...pick(bootstrap, BOOTSTRAP_FIELDS),
29
+ ...(bootstrap.appearance ? { appearance: pick(bootstrap.appearance, APPEARANCE_FIELDS) } : {}) };
30
+ const raw = JSON.stringify({ v: 1, preview: pick(preview, PREVIEW_FIELDS), bootstrap: presentation });
31
+ if (raw.length > 65536 || /"(?:previewGrant|admissionGrant|controlCredential|subjectCredential)"\s*:/.test(raw))
32
+ throw invalid();
33
+ const key = merchantPreviewStorageKeys(preview).recovery;
34
+ storage.setItem(key, raw);
35
+ if (storage.getItem(key) !== raw)
36
+ throw invalid();
37
+ }
38
+ function readMerchantPreviewRecovery(preview, storage) {
39
+ const keys = merchantPreviewStorageKeys(preview);
40
+ if (storage.getItem(keys.original) === null)
41
+ return null;
42
+ const raw = storage.getItem(keys.recovery);
43
+ if (!raw || raw.length > 65536)
44
+ throw invalid();
45
+ let value;
46
+ try {
47
+ value = JSON.parse(raw);
48
+ }
49
+ catch {
50
+ throw invalid();
51
+ }
52
+ if (value?.v !== 1 || !value.preview || !value.bootstrap ||
53
+ JSON.stringify(value.preview) !== JSON.stringify(pick(preview, PREVIEW_FIELDS)))
54
+ throw invalid();
55
+ return value.bootstrap;
56
+ }
@@ -0,0 +1,57 @@
1
+ import type { GuideAdmissionResult, GuideBootstrapConfig, GuideLaunchRecoveryInput } from './guideTypes.js';
2
+ import type { LiveGuideLaunchIntent } from './liveGuideAdmission.js';
3
+ import type { AiGuideControllerState } from './types.js';
4
+ export type MerchantPreviewOptions = {
5
+ previewId: string;
6
+ projectId: number;
7
+ guideId: string;
8
+ configurationVersionId: number;
9
+ configurationRevision: number;
10
+ configurationChecksum: string;
11
+ targetOrigin: string;
12
+ targetPath: string;
13
+ launchExpiresAt: string;
14
+ expiresAt: string;
15
+ runtimeUrl: string;
16
+ widgetVersion: string;
17
+ previewGrant: string;
18
+ developmentConsoleOrigin?: string;
19
+ onState?(state: AiGuideControllerState): void;
20
+ onError?(code: string): void;
21
+ };
22
+ export type MerchantPreviewBootstrapInput = {
23
+ schemaVersion: 1;
24
+ previewId: string;
25
+ previewGrant: string;
26
+ path: string;
27
+ requestedLocale?: string;
28
+ };
29
+ export type MerchantPreviewBootstrap = GuideBootstrapConfig & {
30
+ providerProtocol: 'live';
31
+ merchantPreview: {
32
+ previewId: string;
33
+ configurationVersionId: number;
34
+ targetOrigin: string;
35
+ targetPath: string;
36
+ expiresAt: string;
37
+ };
38
+ };
39
+ export type MerchantPreviewLaunchIntent = Omit<LiveGuideLaunchIntent, 'guideMeasurement'> & {
40
+ previewId: string;
41
+ };
42
+ export type MerchantPreviewAdmissionResult = GuideAdmissionResult & {
43
+ providerProtocol: 'live';
44
+ previewId: string;
45
+ };
46
+ export type MerchantPreviewEndInput = GuideLaunchRecoveryInput & {
47
+ previewId: string;
48
+ action: 'end';
49
+ };
50
+ export type MerchantPreviewEndResult = {
51
+ schemaVersion: 3;
52
+ protocolVersion: 2;
53
+ providerProtocol: 'live';
54
+ status: 'end_requested';
55
+ launchRequestId: string;
56
+ previewId: string;
57
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -4,3 +4,5 @@ export { createGuideRecordingNetworkCapture, observeGuideRecording, } from "./gu
4
4
  export type { GuideRecordingObserver, GuideRecordingSource, GuideRecordingLink, } from "./guideRecording.js";
5
5
  /** Install a Guide without importing, initializing or consulting a recorder. */
6
6
  export declare function installAiGuide(options: StandaloneGuideOptions): Promise<AiGuideController | undefined>;
7
+ export { installMerchantGuidePreview } from './merchantPreview.js';
8
+ export type { MerchantPreviewOptions } from './merchantPreviewTypes.js';
package/cjs/standalone.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.observeGuideRecording = exports.createGuideRecordingNetworkCapture = void 0;
3
+ exports.installMerchantGuidePreview = exports.observeGuideRecording = exports.createGuideRecordingNetworkCapture = void 0;
4
4
  exports.installAiGuide = installAiGuide;
5
5
  const guideInstaller_js_1 = require("./guideInstaller.js");
6
6
  var guideRecording_js_1 = require("./guideRecording.js");
@@ -10,3 +10,5 @@ Object.defineProperty(exports, "observeGuideRecording", { enumerable: true, get:
10
10
  function installAiGuide(options) {
11
11
  return (0, guideInstaller_js_1.installGuide)(options);
12
12
  }
13
+ var merchantPreview_js_1 = require("./merchantPreview.js");
14
+ Object.defineProperty(exports, "installMerchantGuidePreview", { enumerable: true, get: function () { return merchantPreview_js_1.installMerchantGuidePreview; } });
package/cjs/ui.d.ts CHANGED
@@ -60,6 +60,7 @@ export type WidgetCallbacks = {
60
60
  onOpenChange?: (open: boolean) => void;
61
61
  };
62
62
  export type WidgetViewOptions = {
63
+ contextNotice?: string;
63
64
  persistentState?: boolean;
64
65
  storageNamespace?: string;
65
66
  initialPanelView?: "compact" | "expanded";
package/cjs/ui.js CHANGED
@@ -4868,6 +4868,14 @@ class WidgetView {
4868
4868
  this.shadow.append(this.build());
4869
4869
  document.documentElement.append(this.host);
4870
4870
  this.panel = this.require(".panel");
4871
+ if (options.contextNotice) {
4872
+ const notice = document.createElement("p");
4873
+ notice.dataset.role = "context-notice";
4874
+ notice.textContent = options.contextNotice.slice(0, 240);
4875
+ notice.style.cssText = "margin:0;padding:4px 0;font-size:12px;line-height:1.4;color:var(--assist-muted)";
4876
+ this.require(".header .identity").append(notice);
4877
+ this.require('[data-role="intro-entry"]').prepend(notice.cloneNode(true));
4878
+ }
4871
4879
  this.body = this.require(".body");
4872
4880
  this.status = this.require('[data-role="status"]');
4873
4881
  this.duration = this.require('[data-role="duration"]');
package/cjs/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "7.5.26";
1
+ export declare const VERSION = "7.5.27";
package/cjs/version.js CHANGED
@@ -1,4 +1,4 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.VERSION = void 0;
4
- exports.VERSION = '7.5.26';
4
+ exports.VERSION = '7.5.27';
@@ -34,7 +34,7 @@ export declare const normalizeAiGuideOpenInput: (input?: AiGuideOpenInput) => Re
34
34
  export declare const resolveAiGuideProtocolVersion: (bootstrap: Pick<BootstrapConfig, "experienceMode" | "minimumProtocolVersion" | "protocol">) => 1 | 2;
35
35
  export default class AiLiveAssist {
36
36
  private readonly options;
37
- readonly version = "7.5.26";
37
+ readonly version = "7.5.27";
38
38
  private readonly host;
39
39
  private readonly guideAdmission;
40
40
  private readonly standaloneAdmissionPending;
package/lib/client.d.ts CHANGED
@@ -2,6 +2,7 @@ import type { AssistMode, AiGuideCompanionState, BootstrapConfig, ConsentScope,
2
2
  import { type GuideAdmissionResult, type GuideLaunchIntent, type GuideLaunchRecoveryInput, type GuideLaunchRecoveryResult, type GuideLaunchResult, type GuideRecordingLinkInput, type GuideRecordingLinkResult, type GuideMeasurementBridge } from "./guideTypes.js";
3
3
  import type { LiveControlAuthorization } from "./liveControlChannel.js";
4
4
  import type { LiveGuideLaunchIntent } from "./liveGuideAdmission.js";
5
+ import type { MerchantPreviewBootstrapInput, MerchantPreviewBootstrap, MerchantPreviewLaunchIntent, MerchantPreviewAdmissionResult, MerchantPreviewEndInput, MerchantPreviewEndResult } from './merchantPreviewTypes.js';
5
6
  export declare class RuntimeClientError extends Error {
6
7
  readonly code: string;
7
8
  readonly retryable: boolean;
@@ -104,6 +105,12 @@ export declare class RuntimeClient {
104
105
  status: "end_requested";
105
106
  launchRequestId: string;
106
107
  }>;
108
+ bootstrapMerchantPreview(input: MerchantPreviewBootstrapInput, signal: AbortSignal): Promise<MerchantPreviewBootstrap>;
109
+ admitMerchantPreview(intent: MerchantPreviewLaunchIntent, previewGrant: string, subjectCredential: string | undefined, signal?: AbortSignal): Promise<MerchantPreviewAdmissionResult>;
110
+ launchMerchantPreview(intent: MerchantPreviewLaunchIntent, admissionGrant: string, signal: AbortSignal): Promise<LiveControlAuthorization & {
111
+ previewId: string;
112
+ }>;
113
+ endMerchantPreview(input: MerchantPreviewEndInput, signal?: AbortSignal): Promise<MerchantPreviewEndResult>;
107
114
  launchGuide(intent: GuideLaunchIntent, admissionGrant: string, signal: AbortSignal, measurementBridge?: GuideMeasurementBridge): Promise<GuideLaunchResult>;
108
115
  recoverGuideLaunch(input: GuideLaunchRecoveryInput, signal?: AbortSignal, keepalive?: boolean): Promise<GuideLaunchRecoveryResult>;
109
116
  linkGuideRecording(sessionId: string, input: GuideRecordingLinkInput, signal: AbortSignal): Promise<GuideRecordingLinkResult>;
package/lib/client.js CHANGED
@@ -189,6 +189,18 @@ export class RuntimeClient {
189
189
  async endLiveGuide(input, signal) {
190
190
  return this.postJson("/ai-live-assist/v1/public/live/launches/end", input, {}, signal, true);
191
191
  }
192
+ async bootstrapMerchantPreview(input, signal) {
193
+ return this.postRawJson('/ai-live-assist/v1/merchant-previews/bootstrap', JSON.stringify(input), {}, signal, false, false, true);
194
+ }
195
+ async admitMerchantPreview(intent, previewGrant, subjectCredential, signal) {
196
+ return this.postRawJson('/ai-live-assist/v1/merchant-previews/live/admissions', JSON.stringify({ ...intent, previewGrant, ...(subjectCredential ? { subjectCredential } : {}) }), {}, signal, false, false, true);
197
+ }
198
+ async launchMerchantPreview(intent, admissionGrant, signal) {
199
+ return this.postRawJson('/ai-live-assist/v1/merchant-previews/live/launch', JSON.stringify({ ...intent, admissionGrant }), { 'Idempotency-Key': intent.launchRequestId }, signal, false, false, true);
200
+ }
201
+ async endMerchantPreview(input, signal) {
202
+ return this.postRawJson('/ai-live-assist/v1/merchant-previews/live/launches/end', JSON.stringify(input), {}, signal, true, false, true);
203
+ }
192
204
  async launchGuide(intent, admissionGrant, signal, measurementBridge) {
193
205
  return this.postGuideLaunch("/ai-live-assist/v1/public/launch", intent, admissionGrant, signal, measurementBridge);
194
206
  }
@@ -1,5 +1,5 @@
1
1
  import type { GuideMeasurementBridge, GuideMeasurementIntent } from './guideTypes.js';
2
- export declare const GUIDE_MEASUREMENT_CLIENT_VERSION = "7.5.26";
2
+ export declare const GUIDE_MEASUREMENT_CLIENT_VERSION = "7.5.27";
3
3
  export declare function isGuideMeasurementIntent(value: unknown): value is GuideMeasurementIntent;
4
4
  /** The managed analytics owner supplies possession; this check grants no authority. */
5
5
  export declare function currentGuideMeasurementBridge(value: unknown): value is GuideMeasurementBridge;
@@ -1,4 +1,4 @@
1
- export const GUIDE_MEASUREMENT_CLIENT_VERSION = '7.5.26';
1
+ export const GUIDE_MEASUREMENT_CLIENT_VERSION = '7.5.27';
2
2
  export function isGuideMeasurementIntent(value) {
3
3
  if (!value || typeof value !== 'object' || Array.isArray(value))
4
4
  return false;
@@ -1,6 +1,7 @@
1
+ import { type MerchantPreviewRuntimePolicy } from './merchantPreviewOrigins.js';
1
2
  import { type LiveDuplexMediaOptions, type LiveDuplexMediaDependencies } from './liveDuplexMedia.js';
2
3
  import { type CommerceBootstrap, type CommerceContext, type CommerceCartSelection, type CommerceProduct, type CommerceContextClear, type LiveCommerceCatalog, type LiveCommerceDisplayed } from './commerce/contracts.js';
3
- export declare const LIVE_CONTROL_CLIENT_VERSION = "7.5.26";
4
+ export declare const LIVE_CONTROL_CLIENT_VERSION = "7.5.27";
4
5
  export declare const LIVE_CONTROL_CLIENT_CAPABILITIES: readonly ["live_duplex_v1", "live_local_wake_v1", "live_fragment_captions_v1"];
5
6
  declare const phases: readonly ["voice_off", "local_listening", "wake_buffering", "starting", "active", "tentative_idle", "closing", "uncertain", "muted", "suspended", "budget_blocked", "ended"];
6
7
  export type LiveControlState = {
@@ -41,6 +42,7 @@ export interface LiveControlChannelOptions {
41
42
  tabId: string;
42
43
  media: MediaOptions;
43
44
  clock?: LiveControlClock;
45
+ previewRuntimePolicy?: MerchantPreviewRuntimePolicy;
44
46
  createWebSocket?: (url: string, protocols: string[]) => WebSocket;
45
47
  randomUUID?: () => string;
46
48
  onState(state: LiveControlState): void;
@@ -1,3 +1,4 @@
1
+ import { isPreviewRuntimeOrigin } from './merchantPreviewOrigins.js';
1
2
  import { LiveDuplexMedia } from './liveDuplexMedia.js';
2
3
  import { VERSION } from './version.js';
3
4
  import { parseLiveCommerceCatalog, displayedCommerceProducts, isDisplayedCommerceProducts, commerceCartSelection, liveCommerceDisplayedReceipt } from './commerce/contracts.js';
@@ -91,7 +92,9 @@ export class LiveControlChannel {
91
92
  if (!['https:', 'http:'].includes(trusted.protocol) || trusted.origin !== options.trustedRuntimeOrigin ||
92
93
  trusted.username || trusted.password || target.username || target.password || target.search || target.hash || target.pathname !== path ||
93
94
  target.protocol !== (trusted.protocol === 'https:' ? 'wss:' : 'ws:') || target.host !== trusted.host ||
94
- (trusted.protocol === 'http:' && !['localhost', '127.0.0.1', '[::1]'].includes(trusted.hostname)))
95
+ (trusted.protocol === 'http:' && !(options.previewRuntimePolicy
96
+ ? isPreviewRuntimeOrigin(trusted, options.previewRuntimePolicy)
97
+ : ['localhost', '127.0.0.1', '[::1]'].includes(trusted.hostname))))
95
98
  throw unavailable();
96
99
  target.searchParams.set('session', String(value.sessionId));
97
100
  this.url = target.href;
@@ -2,19 +2,37 @@ import { WidgetView, type WidgetViewOptions } from './ui.js';
2
2
  import type { AiGuideControllerState, AiGuideOpenInput, BootstrapConfig, PluginOptions } from './types.js';
3
3
  import type { GuideAdmission } from './guideAdmission.js';
4
4
  import { RuntimeClient } from './client.js';
5
+ import { type LiveGuideLaunchIntent } from './liveGuideAdmission.js';
6
+ import { type LiveControlChannelOptions, type LiveControlAuthorization } from './liveControlChannel.js';
7
+ export type LiveGuideStartIntent = Omit<LiveGuideLaunchIntent, 'installKey' | 'guideMeasurement'>;
8
+ export type LiveGuideSessionAdmission = {
9
+ readonly recoveryOnly?: boolean;
10
+ readonly endMessage?: string;
11
+ canStart?(): boolean;
12
+ hasPendingLaunch(): boolean;
13
+ pendingLaunchId(): string | null;
14
+ launch(intent: LiveGuideStartIntent, signal: AbortSignal): Promise<LiveControlAuthorization>;
15
+ end(signal?: AbortSignal, expectedLaunchRequestId?: string): Promise<void>;
16
+ };
5
17
  type Options = {
6
18
  bootstrap: BootstrapConfig;
7
- admission: GuideAdmission;
8
19
  runtime: RuntimeClient;
9
20
  tabId: string;
10
21
  locale: string;
22
+ previewRuntimePolicy?: LiveControlChannelOptions['previewRuntimePolicy'];
11
23
  messages: PluginOptions['messages'];
12
24
  viewOptions: WidgetViewOptions;
13
25
  acquire(): boolean;
14
26
  ownsActivity?(): boolean;
15
27
  release(): void;
16
28
  onState(): void;
17
- };
29
+ } & ({
30
+ admission: GuideAdmission;
31
+ sessionAdmission?: never;
32
+ } | {
33
+ sessionAdmission: LiveGuideSessionAdmission;
34
+ admission?: never;
35
+ });
18
36
  /** Actual widget protocol branch. Reuses WidgetView, visitor possession storage,
19
37
  * local detector/media and authenticated runtime; never constructs a Realtime
20
38
  * transport or grants model/provider authority on the browser's behalf. */
@@ -1,4 +1,5 @@
1
1
  import { WidgetView } from './ui.js';
2
+ import { RuntimeClientError } from './client.js';
2
3
  import { LiveGuideAdmission } from './liveGuideAdmission.js';
3
4
  import { LiveControlChannel, LIVE_CONTROL_CLIENT_VERSION, LIVE_CONTROL_CLIENT_CAPABILITIES } from './liveControlChannel.js';
4
5
  import { createLiveBrowserDetector, validateLiveBrowserAssets } from './liveBrowserDetector.js';
@@ -59,10 +60,21 @@ export class LiveGuideWidget {
59
60
  JSON.stringify(config.liveCapabilities) !== JSON.stringify(LIVE_CONTROL_CLIENT_CAPABILITIES))
60
61
  throw new Error('AI Guide Live is unavailable.');
61
62
  validateLiveBrowserAssets(config.liveAssets);
62
- this.admission = new LiveGuideAdmission(options.admission.identity, options.admission.store, options.runtime, options.admission);
63
+ if (options.sessionAdmission)
64
+ this.admission = options.sessionAdmission;
65
+ else {
66
+ const publicAdmission = options.admission;
67
+ const live = new LiveGuideAdmission(publicAdmission.identity, publicAdmission.store, options.runtime, publicAdmission);
68
+ this.admission = {
69
+ hasPendingLaunch: () => live.hasPendingLaunch(),
70
+ pendingLaunchId: () => live.pendingLaunchId(),
71
+ launch: (intent, signal) => live.launch({ ...intent, installKey: publicAdmission.identity.installKey }, signal),
72
+ end: (signal, expectedLaunchRequestId) => live.end(signal, expectedLaunchRequestId),
73
+ };
74
+ }
63
75
  const callbacks = {
64
76
  onStart: (mode, scopes, question) => this.start(mode, scopes, question),
65
- onRestart: () => !this.active && !this.starting && !this.ending && !this.admission.hasPendingLaunch(),
77
+ onRestart: () => !this.active && !this.starting && !this.ending && !this.admission.hasPendingLaunch() && this.admission.canStart?.() !== false,
66
78
  onEnd: () => { void this.end().catch(() => undefined); },
67
79
  onMute: muted => { if (muted)
68
80
  this.privacy('mute');
@@ -125,6 +137,10 @@ export class LiveGuideWidget {
125
137
  void this.end().catch(() => undefined);
126
138
  }
127
139
  }
140
+ else if (this.admission.recoveryOnly) {
141
+ this.phase = 'ended';
142
+ this.view.showLaunchUnavailable(this.admission.endMessage ?? this.view.message('ended'));
143
+ }
128
144
  // Capture runs before TabActivityLock releases cross-tab ownership.
129
145
  window.addEventListener('pagehide', this.pagehide, true);
130
146
  window.addEventListener('focus', this.refreshOwnership);
@@ -157,7 +173,7 @@ export class LiveGuideWidget {
157
173
  companion: false, pendingQuestion: this.pendingQuestions.length > 0 };
158
174
  }
159
175
  start(mode, scopes, question) {
160
- if (this.destroyed || this.starting || this.active || this.ending ||
176
+ if (this.destroyed || this.starting || this.active || this.ending || this.admission.canStart?.() === false ||
161
177
  (question && (!question.trim() || question.length > 4000)) || !this.acquireLock())
162
178
  return false;
163
179
  // Recover abandoned intent only after acquiring the actual activity lock;
@@ -175,7 +191,7 @@ export class LiveGuideWidget {
175
191
  this.operation = operation;
176
192
  const timeout = setTimeout(() => operation.abort(), 20000);
177
193
  const config = this.options.bootstrap;
178
- const intent = { schemaVersion: 3, protocolVersion: 2, installKey: this.options.admission.identity.installKey,
194
+ const intent = { schemaVersion: 3, protocolVersion: 2,
179
195
  launchRequestId: crypto.randomUUID(), clientVersion: LIVE_CONTROL_CLIENT_VERSION, liveCapabilities: LIVE_CONTROL_CLIENT_CAPABILITIES,
180
196
  configRevision: config.configRevision, path: location.pathname, tabId: this.options.tabId, mode, experienceMode: 'standard',
181
197
  consent: { disclosureChecksum: config.consent.disclosureChecksum, scopes: [...scopes], locale: this.options.locale },
@@ -195,6 +211,7 @@ export class LiveGuideWidget {
195
211
  throw new Error('Cancelled.');
196
212
  const audio = this.view.livePlaybackElement();
197
213
  const channel = new LiveControlChannel({ authorization, trustedRuntimeOrigin: new URL(this.options.runtime.baseUrl).origin,
214
+ ...(this.options.previewRuntimePolicy ? { previewRuntimePolicy: this.options.previewRuntimePolicy } : {}),
198
215
  tabId: this.options.tabId, onState: state => this.onControlState(state),
199
216
  onClose: reason => {
200
217
  if (this.channel === channel && !this.ending && !this.destroyed) {
@@ -577,11 +594,25 @@ export class LiveGuideWidget {
577
594
  this.ownedLaunchId = null;
578
595
  this.phase = 'ended';
579
596
  this.releaseLock();
580
- if (!this.destroyed)
581
- this.view.showResumeStopped();
597
+ if (!this.destroyed) {
598
+ if (this.admission.endMessage)
599
+ this.view.showLaunchUnavailable(this.admission.endMessage);
600
+ else
601
+ this.view.showResumeStopped();
602
+ }
603
+ this.options.onState();
604
+ }).catch(error => {
605
+ this.phase = 'error';
606
+ if (!this.destroyed) {
607
+ if (this.admission.recoveryOnly && error instanceof RuntimeClientError && error.code === 'MERCHANT_PREVIEW_END_UNRESOLVED') {
608
+ this.view.showLaunchUnavailable(error.message);
609
+ }
610
+ else
611
+ this.view.showError(this.view.message('error'), true);
612
+ }
582
613
  this.options.onState();
583
- }).catch(error => { this.phase = 'error'; if (!this.destroyed)
584
- this.view.showError(this.view.message('error'), true); throw error; })
614
+ throw error;
615
+ })
585
616
  .finally(() => { if (this.ending === pending)
586
617
  this.ending = null; });
587
618
  this.ending = pending;
@@ -0,0 +1,5 @@
1
+ import { type AiGuideController } from './guideTypes.js';
2
+ import type { MerchantPreviewBootstrap, MerchantPreviewOptions } from './merchantPreviewTypes.js';
3
+ export type { MerchantPreviewOptions } from './merchantPreviewTypes.js';
4
+ export declare function validateMerchantPreviewBootstrap(value: MerchantPreviewBootstrap, preview: MerchantPreviewOptions): MerchantPreviewBootstrap;
5
+ export declare function installMerchantGuidePreview(input: MerchantPreviewOptions): Promise<AiGuideController>;
@@ -0,0 +1,144 @@
1
+ import { RuntimeClient, RuntimeClientError } from './client.js';
2
+ import { isLocalConsoleOrigin, isPreviewRuntimeOrigin } from './merchantPreviewOrigins.js';
3
+ import { validateGuideBootstrap } from './guideAdmission.js';
4
+ import { GUIDE_INSTALL_KEY_PATTERN, GUIDE_UUID_PATTERN } from './guideTypes.js';
5
+ import { mountedGuide, PendingGuideMount } from './guideMount.js';
6
+ import { LiveGuideWidget } from './liveGuideWidget.js';
7
+ import { MerchantPreviewAdmission, merchantPreviewNamespace } from './merchantPreviewAdmission.js';
8
+ import { readMerchantPreviewRecovery } from './merchantPreviewStorage.js';
9
+ import { TabActivityLock } from './tabLock.js';
10
+ import { VERSION } from './version.js';
11
+ const invalid = () => new RuntimeClientError('MERCHANT_PREVIEW_INVALID', 'This preview could not be opened. Open it again from OXVO.', false, null, 409);
12
+ const positive = (value) => Number.isSafeInteger(value) && value > 0;
13
+ const timestamp = (value) => typeof value === 'string' ? Date.parse(value) : NaN;
14
+ function captureOptions(input) {
15
+ if (!input || !GUIDE_UUID_PATTERN.test(input.previewId) || !GUIDE_UUID_PATTERN.test(input.guideId) ||
16
+ !positive(input.projectId) || !positive(input.configurationVersionId) || !positive(input.configurationRevision) ||
17
+ !/^[a-f0-9]{64}$/.test(input.configurationChecksum) || input.targetOrigin !== location.origin ||
18
+ input.targetPath !== location.pathname || !/^\/(?!\/)[^\x00-\x20\\?#]*$/.test(input.targetPath) || input.targetPath.length > 2048 ||
19
+ input.widgetVersion !== VERSION || typeof input.previewGrant !== 'string' ||
20
+ input.previewGrant.length > 4096 || !/^[\x21-\x7e]*$/.test(input.previewGrant) ||
21
+ !Number.isFinite(timestamp(input.launchExpiresAt)) ||
22
+ !Number.isFinite(timestamp(input.expiresAt)) || timestamp(input.expiresAt) < timestamp(input.launchExpiresAt))
23
+ throw invalid();
24
+ if (input.developmentConsoleOrigin !== undefined && !isLocalConsoleOrigin(input.developmentConsoleOrigin))
25
+ throw invalid();
26
+ const runtime = new URL(input.runtimeUrl);
27
+ if (runtime.username || runtime.password || runtime.search || runtime.hash || runtime.pathname !== '/' ||
28
+ !isPreviewRuntimeOrigin(runtime, input))
29
+ throw invalid();
30
+ return { previewId: input.previewId, projectId: input.projectId, guideId: input.guideId,
31
+ configurationVersionId: input.configurationVersionId, configurationRevision: input.configurationRevision,
32
+ configurationChecksum: input.configurationChecksum, targetOrigin: input.targetOrigin, targetPath: input.targetPath,
33
+ launchExpiresAt: input.launchExpiresAt, expiresAt: input.expiresAt, runtimeUrl: runtime.href,
34
+ widgetVersion: input.widgetVersion, previewGrant: input.previewGrant,
35
+ ...(input.developmentConsoleOrigin ? { developmentConsoleOrigin: input.developmentConsoleOrigin } : {}),
36
+ ...(typeof input.onState === 'function' ? { onState: input.onState } : {}),
37
+ ...(typeof input.onError === 'function' ? { onError: input.onError } : {}) };
38
+ }
39
+ export function validateMerchantPreviewBootstrap(value, preview) {
40
+ const config = validateGuideBootstrap(value, value?.installKey);
41
+ const metadata = value?.merchantPreview;
42
+ if (!GUIDE_INSTALL_KEY_PATTERN.test(config.installKey) || config.projectId !== preview.projectId || config.guideId !== preview.guideId ||
43
+ config.configRevision !== preview.configurationRevision || config.configChecksum !== `sha256:${preview.configurationChecksum}` ||
44
+ value.providerProtocol !== 'live' || value.widgetVersion !== preview.widgetVersion || value.experienceMode !== 'standard' ||
45
+ value.capabilities?.guideMeasurementV1 === true || value.replayRecordingEnabled === true ||
46
+ !metadata || metadata.previewId !== preview.previewId || metadata.configurationVersionId !== preview.configurationVersionId ||
47
+ metadata.targetOrigin !== preview.targetOrigin || metadata.targetPath !== preview.targetPath ||
48
+ timestamp(metadata.expiresAt) !== timestamp(preview.expiresAt))
49
+ throw invalid();
50
+ return value;
51
+ }
52
+ export function installMerchantGuidePreview(input) {
53
+ try {
54
+ if (window.self !== window.top || window.location.origin === 'null')
55
+ throw invalid();
56
+ const preview = captureOptions(input);
57
+ const recovery = readMerchantPreviewRecovery(preview, sessionStorage);
58
+ if (!recovery && (!preview.previewGrant || timestamp(preview.launchExpiresAt) <= Date.now()))
59
+ throw invalid();
60
+ const namespace = merchantPreviewNamespace(preview.targetOrigin, preview.previewId);
61
+ const mountIdentity = `merchant-preview:${namespace}`;
62
+ const current = mountedGuide(document, mountIdentity);
63
+ if (current)
64
+ return Promise.resolve(current);
65
+ const mount = new PendingGuideMount(document, mountIdentity);
66
+ void (async () => {
67
+ let lock;
68
+ let widget;
69
+ let admission;
70
+ const operation = new AbortController();
71
+ const timeout = window.setTimeout(() => operation.abort(), 15000);
72
+ try {
73
+ const runtime = new RuntimeClient(preview.runtimeUrl, VERSION);
74
+ const locale = (navigator.language || 'en').slice(0, 32);
75
+ const bootstrap = validateMerchantPreviewBootstrap(recovery ?? await runtime.bootstrapMerchantPreview({ schemaVersion: 1,
76
+ previewId: preview.previewId, previewGrant: preview.previewGrant, path: preview.targetPath, requestedLocale: locale }, operation.signal), preview);
77
+ if (operation.signal.aborted || location.origin !== preview.targetOrigin || location.pathname !== preview.targetPath)
78
+ throw invalid();
79
+ admission = new MerchantPreviewAdmission(preview, bootstrap, runtime, sessionStorage, recovery !== null);
80
+ const ownerId = `preview:${crypto.randomUUID()}`;
81
+ const tabKey = `__oxvo_ai_guide_preview_tab_${namespace}`;
82
+ let tabId = sessionStorage.getItem(tabKey);
83
+ if (!tabId || !/^[A-Za-z0-9_.:/-]{1,128}$/.test(tabId)) {
84
+ tabId = `preview:${crypto.randomUUID()}`;
85
+ sessionStorage.setItem(tabKey, tabId);
86
+ if (sessionStorage.getItem(tabKey) !== tabId)
87
+ throw invalid();
88
+ }
89
+ const reportState = () => {
90
+ if (!widget)
91
+ return;
92
+ const state = widget.getState();
93
+ try {
94
+ preview.onState?.(state);
95
+ }
96
+ catch { /* A host observer cannot interrupt session cleanup. */ }
97
+ window.dispatchEvent(new CustomEvent('oxvo-ai-guide:state', { detail: state }));
98
+ };
99
+ lock = new TabActivityLock(namespace, ownerId, active => widget?.onTabActivityChange(active), undefined, undefined, {
100
+ onBeforePageHideRelease: () => { void widget?.end().catch(() => undefined); },
101
+ });
102
+ const activity = lock;
103
+ widget = new LiveGuideWidget({ bootstrap, sessionAdmission: admission, runtime, tabId, locale, messages: {},
104
+ previewRuntimePolicy: preview.developmentConsoleOrigin ? { developmentConsoleOrigin: preview.developmentConsoleOrigin } : {},
105
+ viewOptions: { storageNamespace: namespace, initialPanelView: 'expanded',
106
+ contextNotice: recovery ? 'Finishing your previous preview. If it cannot finish here, check its status in the original Console tab or wait for it to expire.'
107
+ : `Saved draft · Revision ${preview.configurationRevision}. This preview uses OXVO Credits.` },
108
+ acquire: () => activity.acquire(), ownsActivity: () => activity.ownsActivity(), release: () => activity.release(), onState: reportState });
109
+ const live = widget;
110
+ const session = admission;
111
+ let destroyed = false;
112
+ const controller = {
113
+ version: VERSION,
114
+ open: value => live.open(value), close: () => live.close(), getState: () => live.getState(), end: () => live.end(),
115
+ destroy: () => {
116
+ if (destroyed)
117
+ return;
118
+ destroyed = true;
119
+ const ended = live.end();
120
+ live.destroy();
121
+ void ended.catch(() => undefined).finally(() => { session.destroy(); activity.destroy(); mount.release(); });
122
+ },
123
+ };
124
+ mount.promote(document, mountIdentity, controller);
125
+ mount.resolve(controller);
126
+ reportState();
127
+ }
128
+ catch (error) {
129
+ widget?.destroy();
130
+ admission?.destroy();
131
+ lock?.destroy();
132
+ mount.release();
133
+ mount.reject(error);
134
+ }
135
+ finally {
136
+ window.clearTimeout(timeout);
137
+ }
138
+ })();
139
+ return mount.promise;
140
+ }
141
+ catch (error) {
142
+ return Promise.reject(error);
143
+ }
144
+ }
@@ -0,0 +1,32 @@
1
+ import { RuntimeClient } from './client.js';
2
+ import type { LiveControlAuthorization } from './liveControlChannel.js';
3
+ import type { LiveGuideSessionAdmission, LiveGuideStartIntent } from './liveGuideWidget.js';
4
+ import type { MerchantPreviewBootstrap, MerchantPreviewOptions } from './merchantPreviewTypes.js';
5
+ export { merchantPreviewNamespace } from './merchantPreviewStorage.js';
6
+ export declare class MerchantPreviewAdmission implements LiveGuideSessionAdmission {
7
+ private readonly preview;
8
+ private readonly bootstrap;
9
+ private readonly runtime;
10
+ private readonly storage;
11
+ readonly recoveryOnly: boolean;
12
+ readonly endMessage = "Preview ended. Return to Console to open another preview.";
13
+ private readonly store;
14
+ private readonly originalKey;
15
+ private admission;
16
+ private admitting;
17
+ private ending;
18
+ private grant;
19
+ constructor(preview: MerchantPreviewOptions, bootstrap: MerchantPreviewBootstrap, runtime: RuntimeClient, storage?: Storage, recoveryOnly?: boolean);
20
+ canStart(): boolean;
21
+ hasPendingLaunch(): boolean;
22
+ pendingLaunchId(): string | null;
23
+ destroy(): void;
24
+ launch(input: LiveGuideStartIntent, signal: AbortSignal): Promise<LiveControlAuthorization>;
25
+ private reportError;
26
+ private start;
27
+ end(signal?: AbortSignal, expectedLaunchRequestId?: string): Promise<void>;
28
+ private finish;
29
+ private admit;
30
+ private original;
31
+ private writeOriginal;
32
+ }