@oxvo/ai-live-assist 7.5.20 → 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 +259 -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 +259 -9
  97. package/lib/version.d.ts +1 -1
  98. package/lib/version.js +1 -1
  99. package/package.json +1 -1
@@ -0,0 +1,73 @@
1
+ import type { ControlChannel } from '../control.js';
2
+ import type { ControlServerEnvelope, WidgetMessageKey } from '../types.js';
3
+ import { type CommerceBootstrap, type CommerceCatalog, type CommerceCartSelection, type CommerceProduct, type RealtimeCommerceDisplayed } from './contracts.js';
4
+ import type { CommerceProductPanelCallbacks } from './productPanel.js';
5
+ import { type CommerceCartView } from './cartSession.js';
6
+ type CommerceView = CommerceCartView & {
7
+ message(key: WidgetMessageKey): string;
8
+ setCommerceCatalog(catalog: CommerceCatalog, callbacks: CommerceProductPanelCallbacks): void;
9
+ clearCommerceCatalog(): void;
10
+ setCommerceBusy(busy: boolean): void;
11
+ setCommerceError(): void;
12
+ };
13
+ export declare function realtimeCommerceRequiredDigest(payload: unknown): string | null;
14
+ export type DisplayedRealtimeCommerceSelection = {
15
+ selection: CommerceCartSelection;
16
+ displayReceipt: RealtimeCommerceDisplayed;
17
+ product: CommerceProduct;
18
+ expiresAt: string;
19
+ };
20
+ /** Ephemeral presentation state only. The runtime owns provider generations,
21
+ * catalog issuance and all action authority; no catalog grants cart access. */
22
+ export declare class RealtimeCommerce {
23
+ readonly sessionId: string;
24
+ private readonly bootstrap;
25
+ private readonly options;
26
+ private readonly context;
27
+ private readonly cart;
28
+ private consentEpoch;
29
+ private cartConsentBlocked;
30
+ private active;
31
+ private started;
32
+ private resumeAfterPause;
33
+ private paused;
34
+ private destroyed;
35
+ private generation;
36
+ private revokedUntilInput;
37
+ private needsPublish;
38
+ private currentCatalog;
39
+ private displayed;
40
+ private pendingIntent;
41
+ private providerGenerationDigest;
42
+ private pendingProviderRefresh;
43
+ private readonly ingress;
44
+ constructor(sessionId: string, bootstrap: CommerceBootstrap, options: {
45
+ channel: () => ControlChannel | null;
46
+ view: () => CommerceView | null;
47
+ isCurrent: () => boolean;
48
+ sharePage: () => boolean;
49
+ cartConsent?: () => boolean;
50
+ submit: (text: string) => boolean;
51
+ });
52
+ /** Called only after media.connect and the real provider's fence proof. */
53
+ activate(providerGenerationDigest?: string, preserveProvider?: boolean): void;
54
+ suspend(): void;
55
+ pause(): void;
56
+ cut(): void;
57
+ permissionChanged(shared: boolean): void;
58
+ consentChanged(allowed: boolean): void;
59
+ beforeInput(): boolean;
60
+ observeIngress(message: ControlServerEnvelope, fenced: boolean): void;
61
+ receive(message: ControlServerEnvelope): void;
62
+ /** Evidence for a future explicit cart request, never execution authority.
63
+ * A caller still needs a fresh quote, visitor confirmation and one-use grant. */
64
+ currentCartSelection(productRef: string, variantRef: string): DisplayedRealtimeCommerceSelection | null;
65
+ destroy(): void;
66
+ private ready;
67
+ private publishContext;
68
+ private send;
69
+ private invalidateCatalog;
70
+ private cartSnapshot;
71
+ private sameProducts;
72
+ }
73
+ export {};
@@ -0,0 +1,337 @@
1
+ import { commerceCartSelection, commerceObject, displayedCommerceProducts, isCommerceOptions, isDisplayedCommerceProducts, parseRealtimeCommerceCatalog, realtimeCommerceDisplayedReceipt, } from './contracts.js';
2
+ import { CommercePageContext } from './pageContext.js';
3
+ import { CartSession } from './cartSession.js';
4
+ export function realtimeCommerceRequiredDigest(payload) {
5
+ return commerceObject(payload, ['schemaVersion', 'providerGenerationDigest']) && payload.schemaVersion === 1 &&
6
+ typeof payload.providerGenerationDigest === 'string' && /^[a-f0-9]{64}$/u.test(payload.providerGenerationDigest)
7
+ ? payload.providerGenerationDigest : null;
8
+ }
9
+ /** Ephemeral presentation state only. The runtime owns provider generations,
10
+ * catalog issuance and all action authority; no catalog grants cart access. */
11
+ export class RealtimeCommerce {
12
+ constructor(sessionId, bootstrap, options) {
13
+ this.sessionId = sessionId;
14
+ this.bootstrap = bootstrap;
15
+ this.options = options;
16
+ this.consentEpoch = 0;
17
+ this.cartConsentBlocked = false;
18
+ this.active = false;
19
+ this.started = false;
20
+ this.resumeAfterPause = false;
21
+ this.paused = false;
22
+ this.destroyed = false;
23
+ this.generation = 0;
24
+ this.revokedUntilInput = false;
25
+ this.needsPublish = true;
26
+ this.currentCatalog = null;
27
+ this.displayed = null;
28
+ this.pendingIntent = false;
29
+ this.providerGenerationDigest = null;
30
+ this.pendingProviderRefresh = null;
31
+ this.ingress = new WeakMap();
32
+ this.context = new CommercePageContext(options.sharePage, () => {
33
+ this.invalidateCatalog();
34
+ this.needsPublish = true;
35
+ this.publishContext();
36
+ });
37
+ this.cart = new CartSession({ bootstrap, view: options.view,
38
+ transportSessionId: () => options.channel()?.sessionId ?? null,
39
+ current: () => this.cartSnapshot(), selection: (productRef, variantRef) => this.currentCartSelection(productRef, variantRef),
40
+ send: (type, payload) => {
41
+ const channel = options.channel();
42
+ if (!channel?.hasFencedAuthority || !channel.commerceCartNegotiated)
43
+ throw new Error('Cart transport is unavailable.');
44
+ const operation = channel.reserveOperationIdentity(type);
45
+ const accepted = channel.waitForOutcome(operation.messageId, 10000, operation.sequence)
46
+ .then(outcome => outcome.status === 'ack');
47
+ channel.sendReserved(operation, payload);
48
+ return { messageId: operation.messageId, accepted };
49
+ },
50
+ });
51
+ }
52
+ /** Called only after media.connect and the real provider's fence proof. */
53
+ activate(providerGenerationDigest, preserveProvider = false) {
54
+ if (this.destroyed)
55
+ return;
56
+ this.providerGenerationDigest = providerGenerationDigest ?? (preserveProvider ? this.providerGenerationDigest : null);
57
+ this.pendingProviderRefresh = null;
58
+ this.active = true;
59
+ this.resumeAfterPause = false;
60
+ if (this.started)
61
+ this.context.refresh({ force: true });
62
+ else {
63
+ this.started = true;
64
+ this.context.start();
65
+ }
66
+ this.publishContext();
67
+ }
68
+ suspend() {
69
+ this.active = false;
70
+ this.needsPublish = true;
71
+ this.invalidateCatalog();
72
+ }
73
+ pause() {
74
+ this.paused = true;
75
+ this.suspend();
76
+ }
77
+ cut() {
78
+ if (!this.destroyed)
79
+ this.context.refresh({ force: true });
80
+ }
81
+ permissionChanged(shared) {
82
+ if (this.destroyed)
83
+ return;
84
+ // Withdrawal first retires all issued page-bound results. A subsequent
85
+ // explicit question can use a new, redacted market-only context.
86
+ this.revokedUntilInput = !shared;
87
+ this.context.refresh({ force: true });
88
+ }
89
+ consentChanged(allowed) {
90
+ this.consentEpoch += 1;
91
+ this.cartConsentBlocked = !allowed;
92
+ this.cart.cut();
93
+ this.cart.refreshControls();
94
+ }
95
+ beforeInput() {
96
+ this.cart.cut();
97
+ if (this.destroyed || !this.active)
98
+ return true;
99
+ const wasRevoked = this.revokedUntilInput;
100
+ this.revokedUntilInput = false;
101
+ this.context.refresh(wasRevoked ? { force: true } : undefined);
102
+ return this.publishContext();
103
+ }
104
+ observeIngress(message, fenced) {
105
+ if (message.sessionId !== this.sessionId)
106
+ return;
107
+ if (message.type === 'commerce.cart.execution.ready') {
108
+ if (fenced && this.options.channel()?.commerceCartNegotiated === true)
109
+ this.cart.onEvent(message.type, message.payload);
110
+ return;
111
+ }
112
+ if (fenced && message.type === 'consent.updated' && Array.isArray(message.payload.scopes) &&
113
+ (!message.payload.scopes.includes('ai_disclosure') || !message.payload.scopes.includes('commerce_cart'))) {
114
+ this.consentChanged(false);
115
+ }
116
+ if (message.type === 'commerce.context.required') {
117
+ const digest = realtimeCommerceRequiredDigest(message.payload);
118
+ if (digest && digest !== this.providerGenerationDigest && this.started && fenced && !this.destroyed &&
119
+ this.options.isCurrent() && this.options.channel()?.hasFencedAuthority === true &&
120
+ this.options.channel()?.negotiatedCommerceVersion === 1) {
121
+ if (this.paused)
122
+ this.pendingProviderRefresh = digest;
123
+ else
124
+ this.activate(digest);
125
+ }
126
+ return;
127
+ }
128
+ if (fenced && this.pendingIntent && this.ready()) {
129
+ if (message.type === 'error') {
130
+ this.pendingIntent = false;
131
+ this.options.view()?.setCommerceError();
132
+ }
133
+ else if ((message.type === 'assistant.state' && ['ready', 'listening'].includes(String(message.payload.state))) ||
134
+ (message.type === 'caption.segment' && message.payload.speaker === 'assistant' && message.payload.final === true)) {
135
+ this.pendingIntent = false;
136
+ this.options.view()?.setCommerceBusy(false);
137
+ }
138
+ }
139
+ if (message.type === 'provider.reconnecting')
140
+ this.resumeAfterPause = false;
141
+ if (message.type === 'session.state' && message.payload.state === 'paused') {
142
+ this.paused = true;
143
+ this.resumeAfterPause = true;
144
+ }
145
+ if (fenced && this.paused && message.type === 'session.state' &&
146
+ ['active_text', 'active_voice'].includes(String(message.payload.state))) {
147
+ this.paused = false;
148
+ if (this.resumeAfterPause || this.pendingProviderRefresh) {
149
+ this.activate(this.pendingProviderRefresh ?? this.providerGenerationDigest ?? undefined);
150
+ }
151
+ }
152
+ if (message.type === 'provider.reconnecting' ||
153
+ (message.type === 'session.state' && ['paused', 'ending', 'ended', 'failed', 'revoked'].includes(String(message.payload.state))) ||
154
+ (message.type === 'handoff.state' && ['prepared', 'handoff_pending', 'human_controlled'].includes(String(message.payload.state)))) {
155
+ this.suspend();
156
+ }
157
+ else if (message.type === 'assistant.interrupted') {
158
+ this.context.refresh({ force: true });
159
+ }
160
+ else if (message.type === 'consent.updated' &&
161
+ Array.isArray(message.payload.scopes) && !message.payload.scopes.includes('page_context') &&
162
+ this.options.sharePage()) {
163
+ this.permissionChanged(false);
164
+ }
165
+ if (fenced && this.ready())
166
+ this.ingress.set(message, this.generation);
167
+ }
168
+ receive(message) {
169
+ if (message.type.startsWith('commerce.cart.')) {
170
+ if (message.type !== 'commerce.cart.execution.ready' && message.sessionId === this.sessionId && this.ready() &&
171
+ this.options.channel()?.commerceCartNegotiated === true && this.ingress.get(message) === this.generation) {
172
+ this.cart.onEvent(message.type, message.payload);
173
+ }
174
+ return;
175
+ }
176
+ if (message.type !== 'commerce.catalog' || message.sessionId !== this.sessionId ||
177
+ !this.ready() || this.revokedUntilInput || this.ingress.get(message) !== this.generation)
178
+ return;
179
+ this.context.refresh();
180
+ if (this.ingress.get(message) !== this.generation)
181
+ return;
182
+ const event = parseRealtimeCommerceCatalog(message.payload, this.bootstrap, this.context.current, undefined, Date.now(), { cartNegotiated: this.options.channel()?.commerceCartNegotiated === true });
183
+ if (!event || (this.providerGenerationDigest !== null && event.providerGenerationDigest !== this.providerGenerationDigest))
184
+ return;
185
+ if (this.currentCatalog?.catalog.resultSetId === event.catalog.resultSetId &&
186
+ this.currentCatalog.executionId === event.executionId && this.currentCatalog.functionCallId === event.functionCallId &&
187
+ this.currentCatalog.providerGenerationDigest === event.providerGenerationDigest)
188
+ return;
189
+ this.cart.cut();
190
+ this.currentCatalog = event;
191
+ this.displayed = null;
192
+ this.pendingIntent = false;
193
+ const isCurrent = () => this.ready() && !this.revokedUntilInput && this.currentCatalog === event &&
194
+ this.context.current?.contextRevision === event.contextRevision && this.context.current.pageId === event.pageId &&
195
+ Date.parse(event.catalog.expiresAt) > Date.now();
196
+ const submit = (text) => {
197
+ this.context.refresh();
198
+ if (!isCurrent())
199
+ return;
200
+ this.pendingIntent = true;
201
+ this.options.view()?.setCommerceBusy(true);
202
+ if (!this.beforeInput() || !this.options.submit(text)) {
203
+ this.pendingIntent = false;
204
+ this.options.view()?.setCommerceError();
205
+ }
206
+ };
207
+ this.options.view()?.setCommerceCatalog(event.catalog, {
208
+ displayMode: this.bootstrap.cartEnabled && this.options.channel()?.commerceCartNegotiated === true ? 'visible' : 'all',
209
+ onSelection: (productRef, selectedOptions) => {
210
+ const product = event.catalog.products.find(item => item.productRef === productRef);
211
+ if (!product || !isCommerceOptions(selectedOptions) || selectedOptions.length !== product.options.length ||
212
+ !selectedOptions.every(choice => product.options.some(option => option.name === choice.name && option.values.includes(choice.value))))
213
+ return;
214
+ submit(`${this.options.view()?.message('commerceOptions')}: ${JSON.stringify({ productRef, selectedOptions })}`);
215
+ },
216
+ onCompare: productRefs => {
217
+ if (productRefs.length < 2 || productRefs.length > 3 || new Set(productRefs).size !== productRefs.length ||
218
+ !productRefs.every(ref => event.catalog.products.some(product => product.productRef === ref)))
219
+ return;
220
+ submit(`${this.options.view()?.message('commerceCompare')}: ${JSON.stringify({ productRefs })}`);
221
+ },
222
+ onRefresh: () => {
223
+ // Expired cards may still request a fresh read, but never display a
224
+ // receipt or carry a stale product selection into a new page.
225
+ if (!this.ready() || this.currentCatalog !== event)
226
+ return;
227
+ this.context.refresh();
228
+ if (this.currentCatalog !== event)
229
+ return;
230
+ this.pendingIntent = true;
231
+ this.options.view()?.setCommerceBusy(true);
232
+ if (!this.beforeInput() || !this.options.submit(`${this.options.view()?.message('commerceRefresh')}: ${JSON.stringify({ productRefs: event.catalog.products.map(product => product.productRef) })}`)) {
233
+ this.pendingIntent = false;
234
+ this.options.view()?.setCommerceError();
235
+ }
236
+ },
237
+ onDisplayed: (resultSetId, products) => {
238
+ this.context.refresh();
239
+ if (!isCurrent() || resultSetId !== event.catalog.resultSetId ||
240
+ !isDisplayedCommerceProducts(event.catalog, products))
241
+ return;
242
+ const issued = displayedCommerceProducts(event.catalog);
243
+ if ((!this.bootstrap.cartEnabled || this.options.channel()?.commerceCartNegotiated !== true) &&
244
+ !this.sameProducts(products, issued))
245
+ return;
246
+ const visible = issued.filter(item => [...(this.displayed ?? []), ...products].some(seen => seen.productRef === item.productRef && seen.variantRef === item.variantRef));
247
+ if (this.displayed && this.sameProducts(this.displayed, visible))
248
+ return;
249
+ // The panel invokes this only after visible DOM rendering. Preserve
250
+ // the runtime-issued provider digest and only the actually seen pairs.
251
+ if (this.send('commerce.catalog.displayed', { ...realtimeCommerceDisplayedReceipt(event), products: visible }) && isCurrent()) {
252
+ this.displayed = visible;
253
+ this.cart.refreshControls();
254
+ }
255
+ },
256
+ onClose: () => { if (this.currentCatalog === event)
257
+ this.invalidateCatalog(); },
258
+ });
259
+ this.cart.refreshControls();
260
+ }
261
+ /** Evidence for a future explicit cart request, never execution authority.
262
+ * A caller still needs a fresh quote, visitor confirmation and one-use grant. */
263
+ currentCartSelection(productRef, variantRef) {
264
+ this.context.refresh();
265
+ const event = this.currentCatalog;
266
+ const context = this.context.current;
267
+ if (!this.ready() || !this.bootstrap.cartEnabled || this.options.channel()?.commerceCartNegotiated !== true ||
268
+ this.revokedUntilInput || this.pendingIntent || !this.displayed || !event || !context ||
269
+ !this.displayed.some(item => item.productRef === productRef && item.variantRef === variantRef) ||
270
+ event.contextRevision !== context.contextRevision || event.pageId !== context.pageId ||
271
+ Date.parse(event.catalog.expiresAt) <= Date.now() ||
272
+ (this.providerGenerationDigest !== null && event.providerGenerationDigest !== this.providerGenerationDigest))
273
+ return null;
274
+ const selection = commerceCartSelection(event, productRef, variantRef);
275
+ const product = event.catalog.products.find(item => item.productRef === productRef && item.variant?.variantRef === variantRef);
276
+ if (!selection || !product)
277
+ return null;
278
+ // Do not let a future callback mutate the validated catalog held here.
279
+ return JSON.parse(JSON.stringify({ selection, displayReceipt: { ...realtimeCommerceDisplayedReceipt(event), products: this.displayed },
280
+ product, expiresAt: event.catalog.expiresAt }));
281
+ }
282
+ destroy() {
283
+ this.suspend();
284
+ this.cart.destroy();
285
+ this.destroyed = true;
286
+ this.context.destroy();
287
+ }
288
+ ready() {
289
+ const channel = this.options.channel();
290
+ return !this.destroyed && !this.paused && this.active && this.options.isCurrent() &&
291
+ channel?.hasFencedAuthority === true && channel.negotiatedCommerceVersion === 1;
292
+ }
293
+ publishContext() {
294
+ if (!this.ready())
295
+ return true;
296
+ if (!this.needsPublish)
297
+ return true;
298
+ const context = this.revokedUntilInput ? null : this.context.current;
299
+ const sent = this.send(context ? 'commerce.context' : 'commerce.context.clear', context ?? this.context.identity);
300
+ if (sent)
301
+ this.needsPublish = false;
302
+ return sent;
303
+ }
304
+ send(type, payload) {
305
+ if (!this.ready())
306
+ return false;
307
+ try {
308
+ this.options.channel().send(type, payload);
309
+ return true;
310
+ }
311
+ catch {
312
+ this.invalidateCatalog();
313
+ return false;
314
+ }
315
+ }
316
+ invalidateCatalog() {
317
+ this.cart?.cut();
318
+ this.generation += 1;
319
+ this.currentCatalog = null;
320
+ this.displayed = null;
321
+ this.pendingIntent = false;
322
+ this.options.view()?.clearCommerceCatalog();
323
+ }
324
+ cartSnapshot() {
325
+ this.context.refresh();
326
+ const channel = this.options.channel();
327
+ const context = this.context.current;
328
+ if (!this.ready() || this.revokedUntilInput || this.cartConsentBlocked || this.options.cartConsent?.() !== true ||
329
+ document.visibilityState === 'hidden' || !channel?.commerceCartNegotiated || !context || !this.providerGenerationDigest)
330
+ return null;
331
+ return { sessionId: this.sessionId, context, provider: { kind: 'realtime', generationDigest: this.providerGenerationDigest },
332
+ fencingToken: channel.leaseToken, consentEpoch: this.consentEpoch };
333
+ }
334
+ sameProducts(left, right) {
335
+ return left.length === right.length && left.every((item, index) => item.productRef === right[index]?.productRef && item.variantRef === right[index]?.variantRef);
336
+ }
337
+ }
@@ -0,0 +1,130 @@
1
+ import { type CommerceMarket, type CommerceOption, type CommerceStore, type CommerceVariant } from "./contracts.js";
2
+ import type { CommerceCartScope, CommerceCartExecutionResult } from "./cartContracts.js";
3
+ export interface PreparedShopifyCartAddition {
4
+ operationId: string;
5
+ operationMarker: string;
6
+ guideId: string;
7
+ store: CommerceStore;
8
+ market: CommerceMarket;
9
+ productRef: string;
10
+ variantRef: string;
11
+ shopifyVariantId: string;
12
+ selectedOptions: CommerceOption[];
13
+ quantity: number;
14
+ unitPrice: CommerceVariant["price"];
15
+ quantityRule: CommerceVariant["quantityRule"];
16
+ productUrl: string;
17
+ expiresAt: string;
18
+ /** Both are supplied by the fresh server quote, never inferred from missing Ajax fields. */
19
+ requiresSellingPlan: false;
20
+ requiresComponents: false;
21
+ /** Reporting correlation only; this is never a grant or mutation authority. */
22
+ reportScope?: CommerceCartScope;
23
+ reportSessionId?: string;
24
+ }
25
+ export interface ShopifyCartAuthority {
26
+ assertCurrent: (prepared: PreparedShopifyCartAddition) => boolean | Promise<boolean>;
27
+ /** The server atomically consumes this exact operation's grant. A replay can only reconcile. */
28
+ beginExecution: (input: {
29
+ executionId: string;
30
+ cartDigest: string;
31
+ }) => Promise<ShopifyCartExecutionReady>;
32
+ }
33
+ export interface ShopifyCartExecutionReady {
34
+ state: "prepared" | "already_started";
35
+ executionId: string;
36
+ cartDigest: string;
37
+ expiresAt: string;
38
+ }
39
+ export type ShopifyCartRequestOutcome = {
40
+ outcome: "response";
41
+ httpStatus: number;
42
+ } | {
43
+ outcome: "timeout" | "network_error" | "aborted" | "unknown";
44
+ };
45
+ export interface ShopifyCartObservation {
46
+ source: "browser_cart";
47
+ observedAt: string;
48
+ currency: string;
49
+ shopifyVariantId: string;
50
+ operationMarker: string;
51
+ quantity: number;
52
+ lineKeyDigest: string | null;
53
+ }
54
+ export interface ShopifyCartExecutionEvidence {
55
+ executionId: string;
56
+ cartDigest: string;
57
+ request: ShopifyCartRequestOutcome;
58
+ observation: ShopifyCartObservation | null;
59
+ }
60
+ export type ShopifyCartStatus = "confirmed" | "partial" | "conflict" | "uncertain" | "unavailable";
61
+ export type ShopifyCartReason = "matched" | "partial_quantity" | "cart_changed" | "line_changed" | "not_observed" | "execution_unverified" | "context_changed" | "invalid_request" | "unsupported_currency" | "storage_unavailable" | "expired" | "product_changed" | "transport" | "grant_unavailable" | "previous_operation_unresolved" | "previous_operation_reconciled";
62
+ export interface ShopifyCartReceipt {
63
+ schemaVersion: 1;
64
+ operationId: string;
65
+ executionId: string;
66
+ guideId: string;
67
+ storeRef: string;
68
+ productRef: string;
69
+ variantRef: string;
70
+ cartDigest: string;
71
+ lineDigest: string | null;
72
+ observedQuantity: number;
73
+ currency: string;
74
+ unitPrice: string | null;
75
+ observedAt: string;
76
+ }
77
+ export interface ShopifyCartOutcome {
78
+ status: ShopifyCartStatus;
79
+ reason: ShopifyCartReason;
80
+ canUndo: false;
81
+ receipt: ShopifyCartReceipt | null;
82
+ execution: ShopifyCartExecutionEvidence | null;
83
+ /** This stays in the shopper UI; it is not a merchant/provider telemetry payload. */
84
+ local: {
85
+ itemCount: number | null;
86
+ };
87
+ }
88
+ export interface ShopifyCartRecoveryScope {
89
+ guideId: string;
90
+ /** Actual runtime session ID, not an authorization token. Omit only when unknown. */
91
+ sessionId?: string;
92
+ store: CommerceStore;
93
+ market: CommerceMarket;
94
+ }
95
+ export interface ShopifyCartRecovery {
96
+ state: "none" | "resolved" | "unresolved";
97
+ prepared: PreparedShopifyCartAddition | null;
98
+ outcome: ShopifyCartOutcome | null;
99
+ }
100
+ /** A same-origin navigation link, never a mutation URL or a caller-selected path. */
101
+ export declare function getShopifyCartUrl(prepared: PreparedShopifyCartAddition): string | null;
102
+ type LedgerScope = Pick<ShopifyCartRecoveryScope, "guideId" | "store" | "sessionId">;
103
+ /** Isolated effect executor. No calls occur until execute/reconcile is explicitly invoked. */
104
+ export declare class ShopifyCartExecutor {
105
+ private readonly authority;
106
+ constructor(authority: ShopifyCartAuthority);
107
+ /** Synchronous gate used before even requesting another quote/grant. Fail closed on lost storage. */
108
+ hasPending(scope: LedgerScope): boolean;
109
+ /** Retained browser facts for immediate UI restoration; never network or mutation authority. */
110
+ peekPending(scope: LedgerScope): ShopifyCartRecovery | null;
111
+ /** Call only after native accepted this exact report. Browser observation alone is not delivery. */
112
+ acknowledgeReport(scope: LedgerScope, report: CommerceCartExecutionResult): boolean;
113
+ /** Restores only public intent and original evidence. Never consumes a grant or performs a POST. */
114
+ reconcilePending(scope: ShopifyCartRecoveryScope): Promise<ShopifyCartRecovery>;
115
+ execute(input: PreparedShopifyCartAddition, executionId: string): Promise<ShopifyCartOutcome>;
116
+ /** Read-only even after expiry/cut. recoveredReady must come from the trusted native ACK/ready path. */
117
+ reconcile(input: PreparedShopifyCartAddition, executionId: string, recoveredReady?: ShopifyCartExecutionReady): Promise<ShopifyCartOutcome>;
118
+ /** Ajax change.js sets an absolute quantity and offers no conditional delta/CAS.
119
+ * A read then change can overwrite the shopper's concurrent edit even by line key.
120
+ * https://shopify.dev/docs/api/ajax/reference/cart#post-locale-cart-change-js
121
+ */
122
+ undo(): {
123
+ status: "unsupported_conflict";
124
+ canUndo: false;
125
+ reason: "ajax_has_no_conditional_delta";
126
+ };
127
+ private current;
128
+ private observe;
129
+ }
130
+ export {};