@oxvo/ai-live-assist 7.5.26 → 7.5.28

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 (73) hide show
  1. package/cjs/AiLiveAssist.d.ts +3 -1
  2. package/cjs/AiLiveAssist.js +24 -0
  3. package/cjs/client.d.ts +12 -0
  4. package/cjs/client.js +18 -0
  5. package/cjs/commerce/cartRecovery.d.ts +26 -0
  6. package/cjs/commerce/cartRecovery.js +96 -0
  7. package/cjs/commerce/cartSession.d.ts +7 -1
  8. package/cjs/commerce/cartSession.js +61 -5
  9. package/cjs/commerce/realtimeCommerce.d.ts +1 -0
  10. package/cjs/commerce/realtimeCommerce.js +1 -0
  11. package/cjs/commerce/shopifyCart.d.ts +3 -0
  12. package/cjs/commerce/shopifyCart.js +26 -0
  13. package/cjs/guideAdmission.d.ts +1 -0
  14. package/cjs/guideAdmission.js +3 -0
  15. package/cjs/guideMeasurement.d.ts +1 -1
  16. package/cjs/guideMeasurement.js +1 -1
  17. package/cjs/liveControlChannel.d.ts +3 -1
  18. package/cjs/liveControlChannel.js +4 -1
  19. package/cjs/liveGuideWidget.d.ts +22 -2
  20. package/cjs/liveGuideWidget.js +45 -8
  21. package/cjs/merchantPreview.d.ts +5 -0
  22. package/cjs/merchantPreview.js +148 -0
  23. package/cjs/merchantPreviewAdmission.d.ts +33 -0
  24. package/cjs/merchantPreviewAdmission.js +186 -0
  25. package/cjs/merchantPreviewOrigins.d.ts +6 -0
  26. package/cjs/merchantPreviewOrigins.js +24 -0
  27. package/cjs/merchantPreviewStorage.d.ts +9 -0
  28. package/cjs/merchantPreviewStorage.js +68 -0
  29. package/cjs/merchantPreviewTypes.d.ts +57 -0
  30. package/cjs/merchantPreviewTypes.js +2 -0
  31. package/cjs/standalone.d.ts +2 -0
  32. package/cjs/standalone.js +3 -1
  33. package/cjs/ui.d.ts +4 -1
  34. package/cjs/ui.js +13 -4
  35. package/cjs/version.d.ts +1 -1
  36. package/cjs/version.js +1 -1
  37. package/lib/AiLiveAssist.d.ts +3 -1
  38. package/lib/AiLiveAssist.js +24 -0
  39. package/lib/client.d.ts +12 -0
  40. package/lib/client.js +18 -0
  41. package/lib/commerce/cartRecovery.d.ts +26 -0
  42. package/lib/commerce/cartRecovery.js +93 -0
  43. package/lib/commerce/cartSession.d.ts +7 -1
  44. package/lib/commerce/cartSession.js +61 -5
  45. package/lib/commerce/realtimeCommerce.d.ts +1 -0
  46. package/lib/commerce/realtimeCommerce.js +1 -0
  47. package/lib/commerce/shopifyCart.d.ts +3 -0
  48. package/lib/commerce/shopifyCart.js +26 -0
  49. package/lib/guideAdmission.d.ts +1 -0
  50. package/lib/guideAdmission.js +3 -0
  51. package/lib/guideMeasurement.d.ts +1 -1
  52. package/lib/guideMeasurement.js +1 -1
  53. package/lib/liveControlChannel.d.ts +3 -1
  54. package/lib/liveControlChannel.js +4 -1
  55. package/lib/liveGuideWidget.d.ts +22 -2
  56. package/lib/liveGuideWidget.js +45 -8
  57. package/lib/merchantPreview.d.ts +5 -0
  58. package/lib/merchantPreview.js +144 -0
  59. package/lib/merchantPreviewAdmission.d.ts +33 -0
  60. package/lib/merchantPreviewAdmission.js +181 -0
  61. package/lib/merchantPreviewOrigins.d.ts +6 -0
  62. package/lib/merchantPreviewOrigins.js +18 -0
  63. package/lib/merchantPreviewStorage.d.ts +9 -0
  64. package/lib/merchantPreviewStorage.js +62 -0
  65. package/lib/merchantPreviewTypes.d.ts +57 -0
  66. package/lib/merchantPreviewTypes.js +1 -0
  67. package/lib/standalone.d.ts +2 -0
  68. package/lib/standalone.js +1 -0
  69. package/lib/ui.d.ts +4 -1
  70. package/lib/ui.js +13 -4
  71. package/lib/version.d.ts +1 -1
  72. package/lib/version.js +1 -1
  73. package/package.json +1 -1
@@ -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";
@@ -283,7 +284,9 @@ export declare class WidgetView {
283
284
  setCommerceCartActionHandler(handler: CommerceAddHandler | null, canAdd?: CommerceCanAdd): void;
284
285
  showCommerceCartConfirmation(value: CommerceCartConfirmationView, onDecision: (approved: boolean) => void): void;
285
286
  clearCommerceCartConfirmation(operationId?: string): void;
286
- setCommerceCartStatus(outcome: ShopifyCartOutcome, cartUrl: string, onCheck?: () => void | Promise<void>): void;
287
+ setCommerceCartStatus(outcome: ShopifyCartOutcome, cartUrl: string, onCheck?: () => void | Promise<void>, options?: {
288
+ readOnlyRecovery?: boolean;
289
+ }): void;
287
290
  clearCommerceCartStatus(): void;
288
291
  setAdvancedSessionControlsVisible(visible: boolean): void;
289
292
  open(mode?: AssistMode): void;
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"]');
@@ -5773,9 +5781,10 @@ class WidgetView {
5773
5781
  if (current?.onDecision && (!operationId || current.actionId === operationId))
5774
5782
  this.resolveConfirmation(false);
5775
5783
  }
5776
- setCommerceCartStatus(outcome, cartUrl, onCheck) {
5784
+ setCommerceCartStatus(outcome, cartUrl, onCheck, options = {}) {
5777
5785
  this.clearCommerceCartStatus();
5778
- if (this.destroyed || !this.active)
5786
+ const available = () => !this.destroyed && (this.active || options.readOnlyRecovery === true);
5787
+ if (!available())
5779
5788
  return;
5780
5789
  if (this.semanticStatus === this.messages.commerceCartChecking && !this.currentConfirmation &&
5781
5790
  !this.currentVisualRequest && !this.currentHandoffContextRequest && !this.currentPageAssistanceRequest) {
@@ -5807,7 +5816,7 @@ class WidgetView {
5807
5816
  check.type = "button";
5808
5817
  check.textContent = this.messages.commerceCartRecheck;
5809
5818
  check.addEventListener("click", async () => {
5810
- if (check.disabled || this.destroyed || !this.active || this.commerceCartStatus !== status)
5819
+ if (check.disabled || !available() || this.commerceCartStatus !== status)
5811
5820
  return;
5812
5821
  check.disabled = true;
5813
5822
  check.setAttribute("aria-busy", "true");
@@ -5816,7 +5825,7 @@ class WidgetView {
5816
5825
  }
5817
5826
  catch { /* Keep the uncertain result available for another read-only check. */ }
5818
5827
  finally {
5819
- if (this.commerceCartStatus === status && check.isConnected && !this.destroyed && this.active) {
5828
+ if (this.commerceCartStatus === status && check.isConnected && available()) {
5820
5829
  check.disabled = false;
5821
5830
  check.removeAttribute("aria-busy");
5822
5831
  }
package/cjs/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "7.5.26";
1
+ export declare const VERSION = "7.5.28";
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.28';
@@ -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.28";
38
38
  private readonly host;
39
39
  private readonly guideAdmission;
40
40
  private readonly standaloneAdmissionPending;
@@ -128,6 +128,7 @@ export default class AiLiveAssist {
128
128
  private media;
129
129
  private context;
130
130
  private commerce;
131
+ private idleCartRecovery;
131
132
  private commerceReadyChannel;
132
133
  private pendingCommerceGeneration;
133
134
  private presentation;
@@ -453,6 +454,7 @@ export default class AiLiveAssist {
453
454
  private waitForPendingContextNavigationAcknowledgements;
454
455
  private commerceBootstrap;
455
456
  private commerceCartEnabled;
457
+ private refreshIdleCartRecovery;
456
458
  private startRealtimeCommerce;
457
459
  private startContext;
458
460
  private startPresentation;
@@ -1,3 +1,4 @@
1
+ import { CartSession } from './commerce/cartSession.js';
1
2
  import { guideMountIdentity, guideStorageNamespace, resolveGuideHost, } from "./guideHost.js";
2
3
  import { claimGuideMount } from "./guideMount.js";
3
4
  import { RuntimeClient, RuntimeClientError, idempotencyKey, isValidAssistSessionGrant, isValidReplaySessionId, } from "./client.js";
@@ -1419,6 +1420,7 @@ export default class AiLiveAssist {
1419
1420
  this.media = null;
1420
1421
  this.context = null;
1421
1422
  this.commerce = null;
1423
+ this.idleCartRecovery = null;
1422
1424
  this.commerceReadyChannel = null;
1423
1425
  this.pendingCommerceGeneration = null;
1424
1426
  this.presentation = null;
@@ -2052,6 +2054,8 @@ export default class AiLiveAssist {
2052
2054
  this.clearReconnectTimer();
2053
2055
  if (this.destroyed)
2054
2056
  return;
2057
+ this.idleCartRecovery?.destroy();
2058
+ this.idleCartRecovery = null;
2055
2059
  this.commerce?.destroy();
2056
2060
  this.commerce = null;
2057
2061
  this.liveWidget?.destroy();
@@ -2242,6 +2246,7 @@ export default class AiLiveAssist {
2242
2246
  this.view = voicePresenceView
2243
2247
  ? new VoicePresenceView(effectiveBootstrap, this.options.messages ?? {}, callbacks, this.tabId, (fallback) => void this.activateFallback(fallback), this.options.visualTestMode === true)
2244
2248
  : new WidgetView(effectiveBootstrap, this.options.messages ?? {}, callbacks, this.standardWidgetViewOptions(effectiveBootstrap));
2249
+ this.refreshIdleCartRecovery();
2245
2250
  this.syncCompanionView();
2246
2251
  this.initializePageAssistancePreference(effectiveBootstrap);
2247
2252
  this.startMessengerIntegration(effectiveBootstrap);
@@ -8343,6 +8348,19 @@ export default class AiLiveAssist {
8343
8348
  commerceCartEnabled(bootstrap = this.bootstrap) {
8344
8349
  return bootstrap?.capabilities?.commerceCart === true && parseCommerceBootstrap(bootstrap.commerce, bootstrap.guideId, window.location.origin)?.cartEnabled === true;
8345
8350
  }
8351
+ refreshIdleCartRecovery() {
8352
+ this.idleCartRecovery?.destroy();
8353
+ this.idleCartRecovery = null;
8354
+ const bootstrap = this.commerceBootstrap();
8355
+ if (this.destroyed || this.liveWidget || this.commerce || !this.guideAdmission || !bootstrap?.cartEnabled || !(this.view instanceof WidgetView))
8356
+ return;
8357
+ this.idleCartRecovery = new CartSession({ bootstrap, recovery: this.guideAdmission.cartRecovery(),
8358
+ view: () => !this.destroyed && this.view instanceof WidgetView ? this.view : null,
8359
+ current: () => null, selection: () => null,
8360
+ send: () => { throw new Error('Cart recovery has no mutation transport.'); },
8361
+ });
8362
+ this.idleCartRecovery.refreshControls();
8363
+ }
8346
8364
  startRealtimeCommerce(preserveProvider = false) {
8347
8365
  const authority = this.commerceBootstrap();
8348
8366
  const sessionId = this.result?.sessionId;
@@ -8353,7 +8371,10 @@ export default class AiLiveAssist {
8353
8371
  }
8354
8372
  if (this.commerce?.sessionId !== sessionId) {
8355
8373
  this.commerce?.destroy();
8374
+ this.idleCartRecovery?.destroy();
8375
+ this.idleCartRecovery = null;
8356
8376
  this.commerce = new RealtimeCommerce(sessionId, authority, {
8377
+ ...(this.guideAdmission ? { recovery: this.guideAdmission.cartRecovery() } : {}),
8357
8378
  channel: () => this.channel,
8358
8379
  view: () => this.view instanceof WidgetView ? this.view : null,
8359
8380
  isCurrent: () => this.result?.sessionId === sessionId && !this.ended && !this.destroyed &&
@@ -15449,6 +15470,7 @@ export default class AiLiveAssist {
15449
15470
  else {
15450
15471
  this.view?.showResumeStopped?.();
15451
15472
  }
15473
+ this.refreshIdleCartRecovery();
15452
15474
  this.state("ended");
15453
15475
  }
15454
15476
  captureTerminalAuthorizedResult(result, sourceRecord = null) {
@@ -15747,6 +15769,7 @@ export default class AiLiveAssist {
15747
15769
  else {
15748
15770
  this.view?.showResumeStopped?.();
15749
15771
  }
15772
+ this.refreshIdleCartRecovery();
15750
15773
  this.state("ended");
15751
15774
  }
15752
15775
  presentTerminalEnding(error) {
@@ -15968,6 +15991,7 @@ export default class AiLiveAssist {
15968
15991
  quiesceLocalEffectsForTerminalRequest() {
15969
15992
  this.commerce?.destroy();
15970
15993
  this.commerce = null;
15994
+ this.refreshIdleCartRecovery();
15971
15995
  this.clearCtaAuthority();
15972
15996
  this.queuedLaunchToken = null;
15973
15997
  this.launchGeneration += 1;
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;
@@ -97,6 +98,11 @@ export declare class RuntimeClient {
97
98
  providerProtocol: "live";
98
99
  }>;
99
100
  launchLiveGuide(intent: LiveGuideLaunchIntent, admissionGrant: string, signal: AbortSignal, measurementBridge?: GuideMeasurementBridge): Promise<LiveControlAuthorization>;
101
+ inspectCartRecovery(input: import('./commerce/cartRecovery.js').CartRecoveryInput, signal: AbortSignal): Promise<unknown>;
102
+ reportCartRecovery(input: import('./commerce/cartRecovery.js').CartRecoveryInput & {
103
+ recoveryReceipt: string;
104
+ result: import('./commerce/cartContracts.js').CommerceCartExecutionResult;
105
+ }, signal: AbortSignal): Promise<unknown>;
100
106
  endLiveGuide(input: GuideLaunchRecoveryInput, signal?: AbortSignal): Promise<{
101
107
  schemaVersion: 3;
102
108
  protocolVersion: 2;
@@ -104,6 +110,12 @@ export declare class RuntimeClient {
104
110
  status: "end_requested";
105
111
  launchRequestId: string;
106
112
  }>;
113
+ bootstrapMerchantPreview(input: MerchantPreviewBootstrapInput, signal: AbortSignal): Promise<MerchantPreviewBootstrap>;
114
+ admitMerchantPreview(intent: MerchantPreviewLaunchIntent, previewGrant: string, subjectCredential: string | undefined, signal?: AbortSignal): Promise<MerchantPreviewAdmissionResult>;
115
+ launchMerchantPreview(intent: MerchantPreviewLaunchIntent, admissionGrant: string, signal: AbortSignal): Promise<LiveControlAuthorization & {
116
+ previewId: string;
117
+ }>;
118
+ endMerchantPreview(input: MerchantPreviewEndInput, signal?: AbortSignal): Promise<MerchantPreviewEndResult>;
107
119
  launchGuide(intent: GuideLaunchIntent, admissionGrant: string, signal: AbortSignal, measurementBridge?: GuideMeasurementBridge): Promise<GuideLaunchResult>;
108
120
  recoverGuideLaunch(input: GuideLaunchRecoveryInput, signal?: AbortSignal, keepalive?: boolean): Promise<GuideLaunchRecoveryResult>;
109
121
  linkGuideRecording(sessionId: string, input: GuideRecordingLinkInput, signal: AbortSignal): Promise<GuideRecordingLinkResult>;
package/lib/client.js CHANGED
@@ -186,9 +186,27 @@ export class RuntimeClient {
186
186
  async launchLiveGuide(intent, admissionGrant, signal, measurementBridge) {
187
187
  return this.postGuideLaunch("/ai-live-assist/v1/public/live/launch", intent, admissionGrant, signal, measurementBridge);
188
188
  }
189
+ async inspectCartRecovery(input, signal) {
190
+ return this.postRawJson('/ai-live-assist/v1/public/cart/recovery/inspect', JSON.stringify(input), {}, signal, false, false, true);
191
+ }
192
+ async reportCartRecovery(input, signal) {
193
+ return this.postRawJson('/ai-live-assist/v1/public/cart/recovery/report', JSON.stringify(input), {}, signal, false, false, true);
194
+ }
189
195
  async endLiveGuide(input, signal) {
190
196
  return this.postJson("/ai-live-assist/v1/public/live/launches/end", input, {}, signal, true);
191
197
  }
198
+ async bootstrapMerchantPreview(input, signal) {
199
+ return this.postRawJson('/ai-live-assist/v1/merchant-previews/bootstrap', JSON.stringify(input), {}, signal, false, false, true);
200
+ }
201
+ async admitMerchantPreview(intent, previewGrant, subjectCredential, signal) {
202
+ return this.postRawJson('/ai-live-assist/v1/merchant-previews/live/admissions', JSON.stringify({ ...intent, previewGrant, ...(subjectCredential ? { subjectCredential } : {}) }), {}, signal, false, false, true);
203
+ }
204
+ async launchMerchantPreview(intent, admissionGrant, signal) {
205
+ return this.postRawJson('/ai-live-assist/v1/merchant-previews/live/launch', JSON.stringify({ ...intent, admissionGrant }), { 'Idempotency-Key': intent.launchRequestId }, signal, false, false, true);
206
+ }
207
+ async endMerchantPreview(input, signal) {
208
+ return this.postRawJson('/ai-live-assist/v1/merchant-previews/live/launches/end', JSON.stringify(input), {}, signal, true, false, true);
209
+ }
192
210
  async launchGuide(intent, admissionGrant, signal, measurementBridge) {
193
211
  return this.postGuideLaunch("/ai-live-assist/v1/public/launch", intent, admissionGrant, signal, measurementBridge);
194
212
  }
@@ -0,0 +1,26 @@
1
+ import type { RuntimeClient } from '../client.js';
2
+ import type { GuideSubjectStore } from '../guideSubjectStore.js';
3
+ import { type CommerceCartExecutionResult } from './cartContracts.js';
4
+ import type { PreparedShopifyCartAddition, ShopifyCartExecutionEvidence } from './shopifyCart.js';
5
+ export type CartRecoveryInput = {
6
+ schemaVersion: 1;
7
+ installKey: string;
8
+ subjectCredential: string;
9
+ originalSessionId: string;
10
+ operationId: string;
11
+ executionId: string;
12
+ cartDigest: string;
13
+ };
14
+ export type CartRecoveryInspection = {
15
+ recoveryReceipt: string;
16
+ expiresAt: string;
17
+ executionResult: CommerceCartExecutionResult | null;
18
+ };
19
+ export type CartRecovery = {
20
+ available(): boolean;
21
+ inspect(prepared: PreparedShopifyCartAddition, execution: ShopifyCartExecutionEvidence): Promise<CartRecoveryInspection>;
22
+ report(prepared: PreparedShopifyCartAddition, inspection: CartRecoveryInspection, result: CommerceCartExecutionResult): Promise<boolean>;
23
+ };
24
+ /** One possession adapter for Live, Realtime and the isolated preview store.
25
+ * It cannot create a visitor, launch, grant, provider or paid session. */
26
+ export declare function createCartRecovery(runtime: RuntimeClient, installKey: string, store: GuideSubjectStore): CartRecovery;
@@ -0,0 +1,93 @@
1
+ import { commerceUuid } from './contracts.js';
2
+ import { parseCommerceCartResult } from './cartContracts.js';
3
+ const commerceObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
4
+ const stable = (value) => JSON.stringify(value, (_key, item) => commerceObject(item)
5
+ ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
6
+ const same = (a, b) => stable(a) === stable(b);
7
+ const unavailable = () => new Error('The original cart addition could not be checked.');
8
+ async function bounded(work, ms = 5000) {
9
+ const controller = new AbortController();
10
+ const timer = setTimeout(() => controller.abort(), ms);
11
+ try {
12
+ return await work(controller.signal);
13
+ }
14
+ finally {
15
+ clearTimeout(timer);
16
+ }
17
+ }
18
+ /** One possession adapter for Live, Realtime and the isolated preview store.
19
+ * It cannot create a visitor, launch, grant, provider or paid session. */
20
+ export function createCartRecovery(runtime, installKey, store) {
21
+ const subject = () => {
22
+ const value = store.readSubject();
23
+ return value && value.origin === location.origin && Date.parse(value.expiresAt) > Date.now() ? value : null;
24
+ };
25
+ const input = (prepared, execution) => {
26
+ const owner = subject();
27
+ if (!owner || !prepared.reportScope || !commerceUuid(prepared.reportSessionId) || prepared.guideId !== owner.guideId ||
28
+ prepared.store.origin !== location.origin)
29
+ throw unavailable();
30
+ return { schemaVersion: 1, installKey, subjectCredential: owner.credential, originalSessionId: prepared.reportSessionId,
31
+ operationId: prepared.operationId, executionId: execution.executionId, cartDigest: execution.cartDigest };
32
+ };
33
+ const possessions = new WeakMap();
34
+ return {
35
+ available: () => subject() !== null,
36
+ async inspect(prepared, execution) {
37
+ const body = input(prepared, execution);
38
+ const value = await bounded(signal => runtime.inspectCartRecovery(body, signal));
39
+ if (!commerceObject(value) || Object.keys(value).length !== 5 || value.schemaVersion !== 1 ||
40
+ !commerceObject(value.descriptor) || typeof value.recoveryReceipt !== 'string' ||
41
+ !/^\d{13}\.\d{13}\.[A-Za-z0-9_-]{32,86}$/u.test(value.recoveryReceipt) || typeof value.expiresAt !== 'string' ||
42
+ !Number.isFinite(Date.parse(value.expiresAt)) || Date.parse(value.expiresAt) <= Date.now() || Date.parse(value.expiresAt) > Date.now() + 8000 ||
43
+ input(prepared, execution).subjectCredential !== body.subjectCredential)
44
+ throw unavailable();
45
+ const descriptor = value.descriptor;
46
+ if (!commerceObject(descriptor.item) || typeof descriptor.item.title !== 'string' || descriptor.item.title.length > 1000)
47
+ throw unavailable();
48
+ const { title: _title, ...item } = descriptor.item;
49
+ void _title;
50
+ const expected = { schemaVersion: 1, originalSessionId: prepared.reportSessionId, guideId: prepared.guideId,
51
+ scope: prepared.reportScope, store: prepared.store, market: prepared.market, operationMarker: prepared.operationMarker,
52
+ executionId: execution.executionId, cartDigest: execution.cartDigest, expiresAt: prepared.expiresAt,
53
+ item: { productRef: prepared.productRef, variantRef: prepared.variantRef, shopifyVariantId: prepared.shopifyVariantId,
54
+ productUrl: prepared.productUrl, selectedOptions: prepared.selectedOptions, quantity: prepared.quantity,
55
+ unitPrice: prepared.unitPrice, quantityRule: prepared.quantityRule, requiresSellingPlan: false, requiresComponents: false } };
56
+ if (!same({ ...descriptor, item }, expected))
57
+ throw unavailable();
58
+ let known = null;
59
+ if (value.executionResult !== null) {
60
+ const result = value.executionResult;
61
+ if (!commerceObject(result))
62
+ throw unavailable();
63
+ const { request, observation, ...correlation } = result;
64
+ if (!same(correlation, { ...prepared.reportScope, executionId: execution.executionId, cartDigest: execution.cartDigest }) ||
65
+ !commerceObject(request) || (request.outcome === 'response'
66
+ ? Object.keys(request).length !== 2 || !Number.isInteger(request.httpStatus) || Number(request.httpStatus) < 100 || Number(request.httpStatus) > 599
67
+ : Object.keys(request).length !== 1 || !['unknown', 'timeout', 'aborted', 'network_error'].includes(String(request.outcome))))
68
+ throw unavailable();
69
+ if (observation !== null) {
70
+ if (!commerceObject(observation) || !parseCommerceCartResult({ schemaVersion: 1, requestId: prepared.reportScope.requestId,
71
+ operationId: prepared.operationId, executionId: execution.executionId, status: Number(observation.quantity) > 0 ? 'observed' : 'unconfirmed',
72
+ code: Number(observation.quantity) > 0 ? 'observed' : 'unconfirmed', observation }) || observation.operationMarker !== prepared.operationMarker ||
73
+ observation.shopifyVariantId !== prepared.shopifyVariantId || observation.currency !== prepared.unitPrice.currency ||
74
+ Number(observation.quantity) > prepared.quantity)
75
+ throw unavailable();
76
+ }
77
+ known = result;
78
+ }
79
+ const inspection = { recoveryReceipt: value.recoveryReceipt, expiresAt: value.expiresAt, executionResult: known };
80
+ possessions.set(inspection, body.subjectCredential);
81
+ return inspection;
82
+ },
83
+ async report(prepared, inspection, result) {
84
+ const body = input(prepared, result);
85
+ if (possessions.get(inspection) !== body.subjectCredential || Date.parse(inspection.expiresAt) <= Date.now())
86
+ return false;
87
+ const response = parseCommerceCartResult(await bounded(signal => runtime.reportCartRecovery({ ...body, recoveryReceipt: inspection.recoveryReceipt, result }, signal), Math.max(1, Math.min(5000, Date.parse(inspection.expiresAt) - Date.now()))));
88
+ return response !== null && response.requestId === result.requestId && response.operationId === result.operationId &&
89
+ response.executionId === result.executionId && ['observed', 'partial', 'unconfirmed'].includes(response.status) &&
90
+ (response.status === 'unconfirmed' || same(response.observation, result.observation)) && subject()?.credential === body.subjectCredential;
91
+ },
92
+ };
93
+ }
@@ -3,6 +3,7 @@ import type { CommerceAddHandler, CommerceCanAdd } from './productPanel.js';
3
3
  import type { CommerceBootstrap, CommerceCartSelection, CommerceContext, CommerceProduct, LiveCommerceDisplayed, RealtimeCommerceDisplayed } from './contracts.js';
4
4
  import { type CommerceCartProvider } from './cartContracts.js';
5
5
  import { type ShopifyCartOutcome } from './shopifyCart.js';
6
+ import type { CartRecovery } from './cartRecovery.js';
6
7
  export type CartSessionSnapshot = {
7
8
  sessionId: string;
8
9
  context: CommerceContext;
@@ -23,11 +24,14 @@ export type CommerceCartView = {
23
24
  setCommerceCartActionHandler(handler: CommerceAddHandler | null, canAdd?: CommerceCanAdd): void;
24
25
  showCommerceCartConfirmation(value: CommerceCartConfirmationView, onDecision: (approved: boolean) => void): void;
25
26
  clearCommerceCartConfirmation(operationId?: string): void;
26
- setCommerceCartStatus(outcome: ShopifyCartOutcome, cartUrl: string, onCheck?: () => void | Promise<void>): void;
27
+ setCommerceCartStatus(outcome: ShopifyCartOutcome, cartUrl: string, onCheck?: () => void | Promise<void>, options?: {
28
+ readOnlyRecovery?: boolean;
29
+ }): void;
27
30
  clearCommerceCartStatus(): void;
28
31
  };
29
32
  export type CartSessionOptions = {
30
33
  bootstrap: CommerceBootstrap;
34
+ recovery?: CartRecovery;
31
35
  view: () => CommerceCartView | null;
32
36
  /** Null unless disclosure, dedicated cart consent, cart negotiation and the
33
37
  * current session/provider fence are all effective. */
@@ -50,6 +54,7 @@ export declare class CartSession {
50
54
  private readonly retiredRequests;
51
55
  private recoveryOutcome;
52
56
  private recoveryInFlight;
57
+ private recoveryEpoch;
53
58
  private recoveryGrant;
54
59
  private recoveryBegin;
55
60
  private pendingReport;
@@ -76,6 +81,7 @@ export declare class CartSession {
76
81
  private report;
77
82
  private showRecovery;
78
83
  private checkCart;
84
+ private checkRetainedCart;
79
85
  private recoveryHandle;
80
86
  private beginRecovery;
81
87
  private begin;
@@ -35,6 +35,7 @@ export class CartSession {
35
35
  this.retiredRequests = new Set();
36
36
  this.recoveryOutcome = null;
37
37
  this.recoveryInFlight = null;
38
+ this.recoveryEpoch = 0;
38
39
  // At most one original grant, held only by this live instance. The public
39
40
  // recovery ledger deliberately contains no mutation credentials.
40
41
  this.recoveryGrant = null;
@@ -77,6 +78,16 @@ export class CartSession {
77
78
  this.checkCart = () => {
78
79
  if (this.recoveryInFlight)
79
80
  return this.recoveryInFlight;
81
+ if (this.options.recovery?.available() && !this.destroyed && !this.pending) {
82
+ // Assign before work begins, including synchronous early returns. Every
83
+ // simultaneous Check shares this promise and one inspect/read/report.
84
+ this.recoveryInFlight = Promise.resolve().then(() => this.checkRetainedCart()).catch(() => this.showRecovery()).finally(() => {
85
+ this.recoveryInFlight = null;
86
+ if (!this.destroyed)
87
+ this.refreshControls();
88
+ });
89
+ return this.recoveryInFlight;
90
+ }
80
91
  const current = this.options.current();
81
92
  if (this.destroyed || this.pending || !current)
82
93
  return Promise.resolve();
@@ -138,13 +149,13 @@ export class CartSession {
138
149
  this.refreshControls();
139
150
  }
140
151
  };
141
- this.recoveryInFlight = work();
152
+ this.recoveryInFlight = Promise.resolve().then(work);
142
153
  return this.recoveryInFlight;
143
154
  };
144
155
  }
145
156
  /** A catalog replaces the panel; install again after its visible receipt. */
146
157
  refreshControls() {
147
- if (!this.destroyed && !this.pending && this.options.current() && this.hasUnresolved())
158
+ if (!this.destroyed && !this.pending && (this.options.current() || this.options.recovery?.available()) && this.hasUnresolved())
148
159
  this.showRecovery();
149
160
  this.options.view()?.setCommerceCartActionHandler(this.destroyed || !this.options.bootstrap.cartEnabled ||
150
161
  !this.options.current() ? null : this.add, this.canAdd);
@@ -166,6 +177,7 @@ export class CartSession {
166
177
  this.result(payload);
167
178
  }
168
179
  cut() {
180
+ this.recoveryEpoch++;
169
181
  this.recoveryGrant = null;
170
182
  this.recoveryBegin?.resolve(null);
171
183
  this.pendingReport?.resolve(false);
@@ -394,9 +406,53 @@ export class CartSession {
394
406
  const observed = outcome.receipt && (outcome.status === 'confirmed' || outcome.status === 'partial');
395
407
  const current = this.options.current();
396
408
  const prepared = retained?.prepared;
397
- const canRecover = current && prepared && prepared.reportSessionId === current.sessionId &&
398
- (observed && prepared.reportScope || this.recoveryHandle(current, prepared));
399
- this.options.view()?.setCommerceCartStatus(observed ? outcome : { ...outcome, status: 'uncertain' }, this.cartUrl(), canRecover ? this.checkCart : undefined);
409
+ const canRecover = prepared && (this.options.recovery?.available() || current && prepared.reportSessionId === current.sessionId &&
410
+ (observed && prepared.reportScope || this.recoveryHandle(current, prepared)));
411
+ const readOnly = this.options.recovery?.available() ? [{ readOnlyRecovery: true }] : [];
412
+ this.options.view()?.setCommerceCartStatus(observed ? outcome : { ...outcome, status: 'uncertain' }, this.cartUrl(), canRecover ? this.checkCart : undefined, ...readOnly);
413
+ }
414
+ async checkRetainedCart() {
415
+ const recovery = this.options.recovery;
416
+ const epoch = this.recoveryEpoch;
417
+ const stillCurrent = () => !this.destroyed && !this.pending && this.recoveryEpoch === epoch && recovery?.available() === true;
418
+ const executor = this.recoveryExecutor(stillCurrent);
419
+ const retained = executor.peekPending(this.recoveryScope());
420
+ const prepared = retained?.prepared;
421
+ if (!recovery || !prepared?.reportScope || !prepared.reportSessionId || !retained?.outcome?.execution || !stillCurrent())
422
+ return;
423
+ const inspection = await recovery.inspect(prepared, retained.outcome.execution);
424
+ if (!stillCurrent() || Date.parse(inspection.expiresAt) <= Date.now())
425
+ return;
426
+ const known = inspection.executionResult;
427
+ let outcome = retained.outcome;
428
+ let report;
429
+ if (known?.observation && known.observation.quantity > 0) {
430
+ report = known;
431
+ }
432
+ else {
433
+ const read = this.recoveryExecutor(() => stillCurrent() && Date.now() < Date.parse(inspection.expiresAt));
434
+ outcome = await read.reconcile(prepared, retained.outcome.execution.executionId, { state: 'already_started',
435
+ executionId: retained.outcome.execution.executionId, cartDigest: retained.outcome.execution.cartDigest,
436
+ expiresAt: inspection.expiresAt }, { refreshObservation: true });
437
+ if (!outcome.execution || !stillCurrent())
438
+ return;
439
+ report = { ...scopeOf(prepared.reportScope), ...outcome.execution,
440
+ ...(known ? { request: known.request } : {}) };
441
+ }
442
+ if (!stillCurrent() || !await recovery.report(prepared, inspection, report) || !stillCurrent())
443
+ return;
444
+ const accepted = await executor.acceptRecoveryReport(prepared, report);
445
+ if (!stillCurrent())
446
+ return;
447
+ if (accepted)
448
+ outcome = { ...accepted, local: outcome.local };
449
+ this.recoveryOutcome = outcome;
450
+ if (this.hasUnresolved())
451
+ this.showRecovery();
452
+ else {
453
+ this.recoveryOutcome = null;
454
+ this.options.view()?.setCommerceCartStatus(outcome, this.cartUrl(), undefined, { readOnlyRecovery: true });
455
+ }
400
456
  }
401
457
  recoveryHandle(snapshot, prepared) {
402
458
  const retained = this.recoveryGrant;
@@ -47,6 +47,7 @@ export declare class RealtimeCommerce {
47
47
  isCurrent: () => boolean;
48
48
  sharePage: () => boolean;
49
49
  cartConsent?: () => boolean;
50
+ recovery?: import('./cartRecovery.js').CartRecovery;
50
51
  submit: (text: string) => boolean;
51
52
  });
52
53
  /** Called only after media.connect and the real provider's fence proof. */
@@ -35,6 +35,7 @@ export class RealtimeCommerce {
35
35
  this.publishContext();
36
36
  });
37
37
  this.cart = new CartSession({ bootstrap, view: options.view,
38
+ ...(options.recovery ? { recovery: options.recovery } : {}),
38
39
  transportSessionId: () => options.channel()?.sessionId ?? null,
39
40
  current: () => this.cartSnapshot(), selection: (productRef, variantRef) => this.currentCartSelection(productRef, variantRef),
40
41
  send: (type, payload) => {
@@ -110,6 +110,9 @@ export declare class ShopifyCartExecutor {
110
110
  peekPending(scope: LedgerScope): ShopifyCartRecovery | null;
111
111
  /** Call only after native accepted this exact report. Browser observation alone is not delivery. */
112
112
  acknowledgeReport(scope: LedgerScope, report: CommerceCartExecutionResult): boolean;
113
+ /** Called only after authenticated inspect/report of this exact original
114
+ * descriptor. Replays server-retained positive evidence without a new Add. */
115
+ acceptRecoveryReport(prepared: PreparedShopifyCartAddition, report: CommerceCartExecutionResult): Promise<ShopifyCartOutcome | null>;
113
116
  /** Restores only public intent and original evidence. Never consumes a grant or performs a POST. */
114
117
  reconcilePending(scope: ShopifyCartRecoveryScope): Promise<ShopifyCartRecovery>;
115
118
  execute(input: PreparedShopifyCartAddition, executionId: string): Promise<ShopifyCartOutcome>;