@oxvo/ai-live-assist 7.5.19 → 7.5.21

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 (99) hide show
  1. package/cjs/AiLiveAssist.d.ts +8 -1
  2. package/cjs/AiLiveAssist.js +113 -8
  3. package/cjs/client.d.ts +5 -3
  4. package/cjs/client.js +44 -5
  5. package/cjs/commerce/cartContracts.d.ts +158 -0
  6. package/cjs/commerce/cartContracts.js +228 -0
  7. package/cjs/commerce/cartSession.d.ts +86 -0
  8. package/cjs/commerce/cartSession.js +475 -0
  9. package/cjs/commerce/contracts.d.ts +152 -0
  10. package/cjs/commerce/contracts.js +322 -0
  11. package/cjs/commerce/pageContext.d.ts +50 -0
  12. package/cjs/commerce/pageContext.js +173 -0
  13. package/cjs/commerce/productPanel.d.ts +65 -0
  14. package/cjs/commerce/productPanel.js +662 -0
  15. package/cjs/commerce/realtimeCommerce.d.ts +73 -0
  16. package/cjs/commerce/realtimeCommerce.js +342 -0
  17. package/cjs/commerce/shopifyCart.d.ts +130 -0
  18. package/cjs/commerce/shopifyCart.js +1135 -0
  19. package/cjs/commerce/shopifyCartPresentation.d.ts +12 -0
  20. package/cjs/commerce/shopifyCartPresentation.js +379 -0
  21. package/cjs/commerce/shoppingNotes.d.ts +61 -0
  22. package/cjs/commerce/shoppingNotes.js +313 -0
  23. package/cjs/commerce/shoppingNotesView.d.ts +46 -0
  24. package/cjs/commerce/shoppingNotesView.js +269 -0
  25. package/cjs/control.d.ts +9 -1
  26. package/cjs/control.js +51 -1
  27. package/cjs/guideAdmission.d.ts +5 -2
  28. package/cjs/guideAdmission.js +21 -2
  29. package/cjs/guideInstaller.js +1 -1
  30. package/cjs/guideMeasurement.d.ts +5 -0
  31. package/cjs/guideMeasurement.js +29 -0
  32. package/cjs/guideSubjectStore.js +2 -0
  33. package/cjs/guideTypes.d.ts +18 -0
  34. package/cjs/liveControlChannel.d.ts +43 -1
  35. package/cjs/liveControlChannel.js +166 -14
  36. package/cjs/liveGuideAdmission.d.ts +3 -2
  37. package/cjs/liveGuideAdmission.js +10 -2
  38. package/cjs/liveGuideWidget.d.ts +18 -0
  39. package/cjs/liveGuideWidget.js +228 -23
  40. package/cjs/locales/resources.js +2240 -0
  41. package/cjs/messages.js +56 -0
  42. package/cjs/tabLock.d.ts +2 -0
  43. package/cjs/tabLock.js +11 -1
  44. package/cjs/types.d.ts +6 -2
  45. package/cjs/types.js +56 -0
  46. package/cjs/ui.d.ts +37 -0
  47. package/cjs/ui.js +261 -9
  48. package/cjs/version.d.ts +1 -1
  49. package/cjs/version.js +1 -1
  50. package/lib/AiLiveAssist.d.ts +8 -1
  51. package/lib/AiLiveAssist.js +113 -8
  52. package/lib/client.d.ts +5 -3
  53. package/lib/client.js +44 -5
  54. package/lib/commerce/cartContracts.d.ts +158 -0
  55. package/lib/commerce/cartContracts.js +221 -0
  56. package/lib/commerce/cartSession.d.ts +86 -0
  57. package/lib/commerce/cartSession.js +471 -0
  58. package/lib/commerce/contracts.d.ts +152 -0
  59. package/lib/commerce/contracts.js +300 -0
  60. package/lib/commerce/pageContext.d.ts +50 -0
  61. package/lib/commerce/pageContext.js +168 -0
  62. package/lib/commerce/productPanel.d.ts +65 -0
  63. package/lib/commerce/productPanel.js +657 -0
  64. package/lib/commerce/realtimeCommerce.d.ts +73 -0
  65. package/lib/commerce/realtimeCommerce.js +337 -0
  66. package/lib/commerce/shopifyCart.d.ts +130 -0
  67. package/lib/commerce/shopifyCart.js +1130 -0
  68. package/lib/commerce/shopifyCartPresentation.d.ts +12 -0
  69. package/lib/commerce/shopifyCartPresentation.js +376 -0
  70. package/lib/commerce/shoppingNotes.d.ts +61 -0
  71. package/lib/commerce/shoppingNotes.js +307 -0
  72. package/lib/commerce/shoppingNotesView.d.ts +46 -0
  73. package/lib/commerce/shoppingNotesView.js +265 -0
  74. package/lib/control.d.ts +9 -1
  75. package/lib/control.js +51 -1
  76. package/lib/guideAdmission.d.ts +5 -2
  77. package/lib/guideAdmission.js +21 -2
  78. package/lib/guideInstaller.js +1 -1
  79. package/lib/guideMeasurement.d.ts +5 -0
  80. package/lib/guideMeasurement.js +24 -0
  81. package/lib/guideSubjectStore.js +2 -0
  82. package/lib/guideTypes.d.ts +18 -0
  83. package/lib/liveControlChannel.d.ts +43 -1
  84. package/lib/liveControlChannel.js +166 -14
  85. package/lib/liveGuideAdmission.d.ts +3 -2
  86. package/lib/liveGuideAdmission.js +10 -2
  87. package/lib/liveGuideWidget.d.ts +18 -0
  88. package/lib/liveGuideWidget.js +228 -23
  89. package/lib/locales/resources.js +2240 -0
  90. package/lib/messages.js +56 -0
  91. package/lib/tabLock.d.ts +2 -0
  92. package/lib/tabLock.js +11 -1
  93. package/lib/types.d.ts +6 -2
  94. package/lib/types.js +56 -0
  95. package/lib/ui.d.ts +37 -0
  96. package/lib/ui.js +261 -9
  97. package/lib/version.d.ts +1 -1
  98. package/lib/version.js +1 -1
  99. package/package.json +1 -1
@@ -5,6 +5,9 @@ const ui_js_1 = require("./ui.js");
5
5
  const liveGuideAdmission_js_1 = require("./liveGuideAdmission.js");
6
6
  const liveControlChannel_js_1 = require("./liveControlChannel.js");
7
7
  const liveBrowserDetector_js_1 = require("./liveBrowserDetector.js");
8
+ const pageContext_js_1 = require("./commerce/pageContext.js");
9
+ const cartSession_js_1 = require("./commerce/cartSession.js");
10
+ const contracts_js_1 = require("./commerce/contracts.js");
8
11
  const transcriptGroupLimit = 16000;
9
12
  /** Actual widget protocol branch. Reuses WidgetView, visitor possession storage,
10
13
  * local detector/media and authenticated runtime; never constructs a Realtime
@@ -18,6 +21,9 @@ class LiveGuideWidget {
18
21
  this.destroyed = false;
19
22
  this.active = false;
20
23
  this.starting = false;
24
+ this.ownsLock = false;
25
+ this.ownedLaunchId = null;
26
+ this.activeElsewhere = false;
21
27
  this.phase = 'ready';
22
28
  this.mode = 'text';
23
29
  this.captureEpoch = 0;
@@ -37,7 +43,20 @@ class LiveGuideWidget {
37
43
  this.pendingQuestions = [];
38
44
  this.requestIds = new Set();
39
45
  this.livePhase = 'voice_off';
46
+ this.commerceCatalog = null;
40
47
  this.pagehide = () => { void this.end().catch(() => undefined); };
48
+ this.refreshOwnership = () => {
49
+ if (this.destroyed || !this.activeElsewhere || this.active || this.starting || this.ending || !this.acquireLock())
50
+ return;
51
+ // A crashed owner's lock can expire without a storage event. An explicit
52
+ // open/focus may recover its saved intent, but never launches a new session.
53
+ if (this.admission.hasPendingLaunch()) {
54
+ this.ownedLaunchId = this.admission.pendingLaunchId();
55
+ void this.end().catch(() => undefined);
56
+ }
57
+ else
58
+ this.releaseLock();
59
+ };
41
60
  const config = options.bootstrap;
42
61
  if (config.providerProtocol !== 'live' || config.providerModel !== 'gpt-live-1' || !config.liveAssets ||
43
62
  JSON.stringify(config.liveCapabilities) !== JSON.stringify(liveControlChannel_js_1.LIVE_CONTROL_CLIENT_CAPABILITIES))
@@ -82,14 +101,40 @@ class LiveGuideWidget {
82
101
  this.view = new ui_js_1.WidgetView(config, options.messages ?? {}, callbacks, {
83
102
  ...options.viewOptions, preserveRawText: true, manualTurnsSupported: false,
84
103
  });
104
+ this.commerce = (0, contracts_js_1.parseCommerceBootstrap)(config.commerce, config.guideId, location.origin);
105
+ this.commerceContext = this.commerce ? new pageContext_js_1.CommercePageContext(() => this.scopes.includes('page_context') && config.capabilities?.pageContext === true, context => this.onCommerceContext(context)) : null;
106
+ this.commerceCart = this.commerce?.cartEnabled && config.capabilities?.commerceCart === true ? new cartSession_js_1.CartSession({
107
+ bootstrap: this.commerce, view: () => this.destroyed ? null : this.view,
108
+ current: () => this.currentCartSnapshot(),
109
+ transportSessionId: () => this.channel?.sessionId ?? null,
110
+ selection: (productRef, variantRef) => {
111
+ this.commerceContext?.refresh();
112
+ const selected = this.channel?.currentCartSelection(productRef, variantRef);
113
+ const visible = this.commerceCatalog;
114
+ return selected && visible && selected.displayReceipt.resultSetId === visible.catalog.resultSetId &&
115
+ selected.displayReceipt.taskId === visible.taskId && selected.displayReceipt.inputEpoch === visible.inputEpoch
116
+ ? selected : null;
117
+ },
118
+ send: (type, payload) => {
119
+ if (!this.channel)
120
+ throw new Error('The cart connection is unavailable.');
121
+ return this.channel.sendCommerceCart(type, payload);
122
+ },
123
+ }) : null;
124
+ this.commerceContext?.start();
85
125
  if (this.admission.hasPendingLaunch()) {
86
- this.phase = 'ending';
87
- this.view.showEndingDetached();
88
- void this.end().catch(() => undefined);
126
+ if (this.acquireLock()) {
127
+ this.ownedLaunchId = this.admission.pendingLaunchId();
128
+ void this.end().catch(() => undefined);
129
+ }
89
130
  }
90
- window.addEventListener('pagehide', this.pagehide);
131
+ // Capture runs before TabActivityLock releases cross-tab ownership.
132
+ window.addEventListener('pagehide', this.pagehide, true);
133
+ window.addEventListener('focus', this.refreshOwnership);
134
+ window.addEventListener('pageshow', this.refreshOwnership);
91
135
  }
92
136
  open(input = {}) {
137
+ this.refreshOwnership();
93
138
  if (input.requestId && this.requestIds.has(input.requestId))
94
139
  return this.getState();
95
140
  if (input.question && !this.active && this.pendingQuestions.length >= 8)
@@ -115,10 +160,14 @@ class LiveGuideWidget {
115
160
  companion: false, pendingQuestion: this.pendingQuestions.length > 0 };
116
161
  }
117
162
  start(mode, scopes, question) {
118
- if (this.destroyed || this.starting || this.active || this.ending || this.admission.hasPendingLaunch() || !this.options.acquire())
163
+ if (this.destroyed || this.starting || this.active || this.ending ||
164
+ (question && (!question.trim() || question.length > 4000)) || !this.acquireLock())
119
165
  return false;
120
- if (question && (!question.trim() || question.length > 4000)) {
121
- this.options.release();
166
+ // Recover abandoned intent only after acquiring the actual activity lock;
167
+ // tabId equality cannot distinguish a reload from a still-live document.
168
+ if (this.admission.hasPendingLaunch()) {
169
+ this.ownedLaunchId = this.admission.pendingLaunchId();
170
+ void this.end().catch(() => undefined);
122
171
  return false;
123
172
  }
124
173
  this.mode = mode;
@@ -136,13 +185,16 @@ class LiveGuideWidget {
136
185
  capabilitySummary: { ctaOffer: false, microphone: mode === 'voice' && scopes.includes('microphone'),
137
186
  webrtc: typeof RTCPeerConnection !== 'undefined', audioPlayback: typeof HTMLAudioElement !== 'undefined', webAudio: typeof AudioContext !== 'undefined',
138
187
  svgOverlay: false, visualViewport: typeof visualViewport !== 'undefined', reducedMotion: matchMedia('(prefers-reduced-motion: reduce)').matches, lowPower: false } };
188
+ this.ownedLaunchId = intent.launchRequestId;
139
189
  // Start after the view has committed its connecting presentation. This does
140
190
  // not manufacture activation: prepareVoice tests the current real gesture.
141
191
  queueMicrotask(() => {
142
192
  void (async () => {
143
193
  try {
194
+ if (operation.signal.aborted || this.destroyed || this.operation !== operation || !this.hasLock())
195
+ throw new Error('Cancelled.');
144
196
  const authorization = await this.admission.launch(intent, operation.signal);
145
- if (operation.signal.aborted || this.destroyed || this.operation !== operation)
197
+ if (operation.signal.aborted || this.destroyed || this.operation !== operation || !this.hasLock())
146
198
  throw new Error('Cancelled.');
147
199
  const audio = this.view.livePlaybackElement();
148
200
  const channel = new liveControlChannel_js_1.LiveControlChannel({ authorization, trustedRuntimeOrigin: new URL(this.options.runtime.baseUrl).origin,
@@ -159,22 +211,33 @@ class LiveGuideWidget {
159
211
  },
160
212
  onTextAnswer: value => {
161
213
  this.backendWorking = false;
214
+ this.view.setCommerceBusy(false);
162
215
  this.view.addCaption('assistant', value.text, true);
163
216
  this.view.setAssistantState('ready');
164
217
  },
165
218
  onTaskState: value => {
219
+ if (['cancelled', 'failed', 'blocked', 'fresh_task_required'].includes(value.status))
220
+ this.commerceCart?.cut();
166
221
  this.backendWorking = value.status === 'working';
222
+ if (value.status !== 'working')
223
+ this.view.setCommerceBusy(false);
167
224
  if (value.status === 'working')
168
225
  this.view.setAssistantState('thinking');
169
226
  else if (value.status === 'fresh_task_required') {
170
227
  this.view.setAssistantState('ready');
171
228
  this.view.setStatus(this.view.message('taskContextLimit'));
172
229
  }
173
- else if (value.status === 'failed' || value.status === 'blocked')
230
+ else if (value.status === 'failed' || value.status === 'blocked') {
231
+ this.view.setCommerceError();
174
232
  this.view.setStatus(this.view.message('error'));
233
+ }
175
234
  else
176
235
  this.view.setAssistantState('ready');
177
236
  },
237
+ ...(this.commerce ? { commerce: { bootstrap: this.commerce, currentContext: () => this.commerceContext?.current ?? null,
238
+ ...(this.commerceCart ? { cartVersion: 1 } : {}) },
239
+ onCommerceCatalog: (value) => this.showCommerceCatalog(value),
240
+ onCommerceCartEvent: (type, payload) => this.commerceCart?.onEvent(type, payload) } : {}),
178
241
  onTranscript: value => this.onTranscript(value),
179
242
  onRepeatAfterReady: () => this.view.setStatus(this.view.message('repeatWhenMicrophoneReady')),
180
243
  media: { audioElement: audio, workletUrl: config.liveAssets.audioWorkletUrl, dataChannelLabel: 'oai-events',
@@ -194,6 +257,7 @@ class LiveGuideWidget {
194
257
  this.active = true;
195
258
  this.phase = 'active';
196
259
  this.view.showActive(null);
260
+ this.commerceContext?.refresh({ force: true });
197
261
  this.view.configureVoiceControls(mode === 'voice', false, true);
198
262
  if (question)
199
263
  this.submitText(question, true);
@@ -204,7 +268,7 @@ class LiveGuideWidget {
204
268
  this.options.onState();
205
269
  }
206
270
  catch {
207
- if (!this.destroyed && !this.ending) {
271
+ if (!this.destroyed && !this.ending && this.operation === operation) {
208
272
  this.starting = false;
209
273
  this.phase = 'error';
210
274
  this.view.showError(this.view.message('error'), true);
@@ -341,6 +405,7 @@ class LiveGuideWidget {
341
405
  if (playing === null) {
342
406
  this.playbackUnknownSince ?? (this.playbackUnknownSince = now);
343
407
  if (now - this.playbackUnknownSince >= 2000) {
408
+ this.commerceCart?.cut();
344
409
  this.capturePrepared = false;
345
410
  this.channel.fence('audio_suspended');
346
411
  this.view.setMuted(true);
@@ -365,6 +430,8 @@ class LiveGuideWidget {
365
430
  }
366
431
  }
367
432
  onControlState(state) {
433
+ if (['suspended', 'ended', 'budget_blocked'].includes(state.phase))
434
+ this.commerceCart?.cut();
368
435
  if (this.livePhase !== state.phase && state.phase === 'local_listening')
369
436
  this.wakeRequested = false;
370
437
  this.livePhase = state.phase;
@@ -386,6 +453,8 @@ class LiveGuideWidget {
386
453
  if (!this.channel || !this.active || !text.trim() || text.length > 4000)
387
454
  return false;
388
455
  try {
456
+ this.commerceCart?.cut();
457
+ this.commerceContext?.refresh();
389
458
  this.channel.submitText({ inputId: crypto.randomUUID(), inputEpoch: ++this.inputEpoch, text });
390
459
  if (echo)
391
460
  this.view.addCaption('user', text, true);
@@ -397,12 +466,21 @@ class LiveGuideWidget {
397
466
  return false;
398
467
  }
399
468
  }
400
- stop() { this.inputEpoch++; this.channel?.stop(); this.wakeRequested = false; this.view.interruptPlayback(); }
469
+ stop() {
470
+ this.commerceCart?.cut();
471
+ this.inputEpoch++;
472
+ this.channel?.stop();
473
+ this.wakeRequested = false;
474
+ this.view.interruptPlayback();
475
+ this.commerceContext?.refresh({ force: true });
476
+ }
401
477
  privacy(reason) {
478
+ this.commerceCart?.cut();
402
479
  this.inputEpoch++;
403
480
  this.capturePrepared = false;
404
481
  this.wakeRequested = false;
405
482
  this.channel?.fence(reason);
483
+ this.commerceContext?.refresh({ force: true });
406
484
  }
407
485
  toText() {
408
486
  this.privacy('mode_change');
@@ -411,24 +489,97 @@ class LiveGuideWidget {
411
489
  this.view.setModeTransitionPending(null);
412
490
  this.options.onState();
413
491
  }
492
+ onCommerceContext(context) {
493
+ this.commerceCart?.cut();
494
+ this.commerceCatalog = null;
495
+ this.view.clearCommerceCatalog();
496
+ if (!this.active || !this.channel?.commerceNegotiated || !this.commerceContext)
497
+ return;
498
+ try {
499
+ this.channel.setCommerceContext(context ?? this.commerceContext.identity);
500
+ }
501
+ catch {
502
+ this.view.setCommerceError();
503
+ }
504
+ }
505
+ currentCartSnapshot() {
506
+ if (!this.active || this.destroyed || document.visibilityState === 'hidden' ||
507
+ !this.scopes.includes('ai_disclosure') || !this.scopes.includes('commerce_cart'))
508
+ return null;
509
+ this.commerceContext?.refresh();
510
+ const authority = this.channel?.currentCartAuthority();
511
+ const context = this.commerceContext?.current;
512
+ if (!authority || !context)
513
+ return null;
514
+ return { sessionId: authority.sessionId, context, provider: { kind: 'live', taskId: authority.taskId, inputEpoch: authority.inputEpoch },
515
+ fencingToken: authority.fencingToken, consentEpoch: 0 };
516
+ }
517
+ showCommerceCatalog(event) {
518
+ if (!this.commerce || !this.active || !this.channel?.commerceNegotiated ||
519
+ !(0, contracts_js_1.parseLiveCommerceCatalog)(event, this.commerce, this.commerceContext?.current ?? null, undefined, Date.now(), { cartNegotiated: this.channel.commerceCartNegotiated }))
520
+ return;
521
+ this.commerceCart?.cut();
522
+ this.commerceCatalog = event;
523
+ const current = () => this.commerceCatalog === event && this.active && !!this.commerce &&
524
+ !!(0, contracts_js_1.parseLiveCommerceCatalog)(event, this.commerce, this.commerceContext?.current ?? null, undefined, Date.now(), { cartNegotiated: this.channel?.commerceCartNegotiated ?? false });
525
+ const request = (key, detail) => {
526
+ const context = this.commerceContext?.current;
527
+ const sameContext = this.commerceCatalog === event && this.active && context?.pageId === event.pageId &&
528
+ context.contextRevision === event.contextRevision;
529
+ if (!sameContext || (key !== 'commerceRefresh' && !current()))
530
+ return;
531
+ this.view.setCommerceBusy(true);
532
+ if (!this.submitText(`${this.view.message(key)}: ${JSON.stringify(detail)}`, true))
533
+ this.view.setCommerceError();
534
+ };
535
+ this.view.setCommerceCatalog(event.catalog, {
536
+ displayMode: this.channel.commerceCartNegotiated ? 'visible' : 'all',
537
+ onSelection: (productRef, selectedOptions) => {
538
+ const product = event.catalog.products.find(item => item.productRef === productRef);
539
+ if (!product || !(0, contracts_js_1.isCommerceOptions)(selectedOptions) || selectedOptions.length !== product.options.length ||
540
+ !selectedOptions.every(choice => product.options.some(option => option.name === choice.name && option.values.includes(choice.value))))
541
+ return;
542
+ request('commerceOptions', { productRef, selectedOptions });
543
+ },
544
+ onCompare: productRefs => {
545
+ if (productRefs.length < 2 || productRefs.length > 3 || new Set(productRefs).size !== productRefs.length ||
546
+ !productRefs.every(ref => event.catalog.products.some(product => product.productRef === ref)))
547
+ return;
548
+ request('commerceCompare', { productRefs });
549
+ },
550
+ onRefresh: () => request('commerceRefresh', { productRefs: event.catalog.products.map(product => product.productRef) }),
551
+ onClose: () => { this.commerceCart?.cut(); this.commerceCatalog = null; this.view.clearCommerceCatalog(); },
552
+ onDisplayed: (resultSetId, products) => {
553
+ if (!current())
554
+ return;
555
+ try {
556
+ if (this.channel?.acknowledgeCommerceCatalog({ schemaVersion: 1, taskId: event.taskId, inputEpoch: event.inputEpoch,
557
+ contextRevision: event.contextRevision, pageId: event.pageId, resultSetId, products }))
558
+ this.commerceCart?.refreshControls();
559
+ }
560
+ catch { /* A newer context or command cut invalidates this presentation receipt. */ }
561
+ },
562
+ });
563
+ this.commerceCart?.refreshControls();
564
+ }
414
565
  end() {
415
566
  if (this.ending)
416
567
  return this.ending;
417
- this.active = false;
418
- this.starting = false;
419
- this.capturePrepared = false;
420
- this.pendingQuestions = [];
568
+ if (!this.hasLock()) {
569
+ this.ownsLock = false;
570
+ this.ownedLaunchId = null;
571
+ this.detachSession();
572
+ return Promise.resolve();
573
+ }
574
+ const launchRequestId = this.ownedLaunchId;
575
+ this.detachSession();
421
576
  this.phase = 'ending';
422
- const channel = this.channel;
423
- this.channel = null;
424
- channel?.end();
425
- this.operation?.abort();
426
- this.operation = null;
427
577
  if (!this.destroyed)
428
578
  this.view.showEndingDetached();
429
- const pending = this.admission.end().then(() => {
579
+ const pending = (launchRequestId ? this.admission.end(undefined, launchRequestId) : Promise.resolve()).then(() => {
580
+ this.ownedLaunchId = null;
430
581
  this.phase = 'ended';
431
- this.options.release();
582
+ this.releaseLock();
432
583
  if (!this.destroyed)
433
584
  this.view.showResumeStopped();
434
585
  this.options.onState();
@@ -439,11 +590,65 @@ class LiveGuideWidget {
439
590
  this.ending = pending;
440
591
  return pending;
441
592
  }
593
+ onTabActivityChange(active) {
594
+ if (this.destroyed)
595
+ return;
596
+ if (this.ownsLock && !this.hasLock() && !this.ending) {
597
+ this.ownsLock = false;
598
+ this.ownedLaunchId = null;
599
+ this.detachSession();
600
+ this.phase = 'ready';
601
+ }
602
+ this.showActiveElsewhere(active && !this.hasLock());
603
+ }
604
+ hasLock() { return this.ownsLock && (this.options.ownsActivity?.() ?? true); }
605
+ acquireLock() {
606
+ if (!this.options.acquire()) {
607
+ this.showActiveElsewhere(true);
608
+ return false;
609
+ }
610
+ this.ownsLock = true;
611
+ this.showActiveElsewhere(false);
612
+ return true;
613
+ }
614
+ releaseLock() {
615
+ const owned = this.hasLock();
616
+ this.ownsLock = false;
617
+ if (owned)
618
+ this.options.release();
619
+ }
620
+ showActiveElsewhere(active) {
621
+ if (this.activeElsewhere === active)
622
+ return;
623
+ this.activeElsewhere = active;
624
+ this.view.showActiveElsewhere(active);
625
+ if (!this.ending)
626
+ this.phase = active ? 'active_elsewhere' : 'ready';
627
+ this.options.onState();
628
+ }
629
+ detachSession() {
630
+ this.commerceCart?.cut();
631
+ this.active = false;
632
+ this.starting = false;
633
+ this.capturePrepared = false;
634
+ this.pendingQuestions = [];
635
+ this.commerceCatalog = null;
636
+ this.view.clearCommerceCatalog();
637
+ const channel = this.channel;
638
+ this.channel = null;
639
+ channel?.end();
640
+ this.operation?.abort();
641
+ this.operation = null;
642
+ }
442
643
  destroy() {
443
644
  if (this.destroyed)
444
645
  return;
445
646
  this.destroyed = true;
446
- window.removeEventListener('pagehide', this.pagehide);
647
+ window.removeEventListener('pagehide', this.pagehide, true);
648
+ window.removeEventListener('focus', this.refreshOwnership);
649
+ window.removeEventListener('pageshow', this.refreshOwnership);
650
+ this.commerceCart?.destroy();
651
+ this.commerceContext?.destroy();
447
652
  void this.end().catch(() => undefined);
448
653
  this.view.destroy();
449
654
  }