@athoscommerce/snap-store-mobx 1.5.1-beta.116 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/cjs/Autocomplete/Stores/AutocompleteFacetStore.js +1 -2
  2. package/dist/cjs/Search/Stores/SearchFacetStore.d.ts.map +1 -1
  3. package/dist/cjs/Search/Stores/SearchFacetStore.js +10 -13
  4. package/dist/cjs/Search/Stores/SearchResultStore.d.ts.map +1 -1
  5. package/dist/cjs/Search/Stores/SearchResultStore.js +7 -6
  6. package/dist/cjs/Search/Stores/index.d.ts +1 -1
  7. package/dist/cjs/Search/Stores/index.d.ts.map +1 -1
  8. package/dist/cjs/Search/Stores/index.js +1 -2
  9. package/dist/cjs/index.d.ts +0 -4
  10. package/dist/cjs/index.d.ts.map +1 -1
  11. package/dist/cjs/index.js +1 -5
  12. package/dist/cjs/types.d.ts +2 -24
  13. package/dist/cjs/types.d.ts.map +1 -1
  14. package/dist/esm/Autocomplete/Stores/AutocompleteFacetStore.js +1 -1
  15. package/dist/esm/Search/Stores/SearchFacetStore.d.ts.map +1 -1
  16. package/dist/esm/Search/Stores/SearchFacetStore.js +10 -13
  17. package/dist/esm/Search/Stores/SearchResultStore.d.ts.map +1 -1
  18. package/dist/esm/Search/Stores/SearchResultStore.js +7 -6
  19. package/dist/esm/Search/Stores/index.d.ts +1 -1
  20. package/dist/esm/Search/Stores/index.d.ts.map +1 -1
  21. package/dist/esm/Search/Stores/index.js +1 -1
  22. package/dist/esm/index.d.ts +0 -4
  23. package/dist/esm/index.d.ts.map +1 -1
  24. package/dist/esm/index.js +0 -2
  25. package/dist/esm/types.d.ts +2 -24
  26. package/dist/esm/types.d.ts.map +1 -1
  27. package/package.json +5 -5
  28. package/dist/cjs/Chat/ChatStore.d.ts +0 -104
  29. package/dist/cjs/Chat/ChatStore.d.ts.map +0 -1
  30. package/dist/cjs/Chat/ChatStore.js +0 -676
  31. package/dist/cjs/Chat/Stores/ChatAttachmentStore.d.ts +0 -98
  32. package/dist/cjs/Chat/Stores/ChatAttachmentStore.d.ts.map +0 -1
  33. package/dist/cjs/Chat/Stores/ChatAttachmentStore.js +0 -314
  34. package/dist/cjs/Chat/Stores/ChatCompareStore.d.ts +0 -16
  35. package/dist/cjs/Chat/Stores/ChatCompareStore.d.ts.map +0 -1
  36. package/dist/cjs/Chat/Stores/ChatCompareStore.js +0 -64
  37. package/dist/cjs/Chat/Stores/ChatSessionStore.d.ts +0 -107
  38. package/dist/cjs/Chat/Stores/ChatSessionStore.d.ts.map +0 -1
  39. package/dist/cjs/Chat/Stores/ChatSessionStore.js +0 -644
  40. package/dist/esm/Chat/ChatStore.d.ts +0 -104
  41. package/dist/esm/Chat/ChatStore.d.ts.map +0 -1
  42. package/dist/esm/Chat/ChatStore.js +0 -601
  43. package/dist/esm/Chat/Stores/ChatAttachmentStore.d.ts +0 -98
  44. package/dist/esm/Chat/Stores/ChatAttachmentStore.d.ts.map +0 -1
  45. package/dist/esm/Chat/Stores/ChatAttachmentStore.js +0 -222
  46. package/dist/esm/Chat/Stores/ChatCompareStore.d.ts +0 -16
  47. package/dist/esm/Chat/Stores/ChatCompareStore.d.ts.map +0 -1
  48. package/dist/esm/Chat/Stores/ChatCompareStore.js +0 -50
  49. package/dist/esm/Chat/Stores/ChatSessionStore.d.ts +0 -107
  50. package/dist/esm/Chat/Stores/ChatSessionStore.d.ts.map +0 -1
  51. package/dist/esm/Chat/Stores/ChatSessionStore.js +0 -609
@@ -1,676 +0,0 @@
1
- "use strict";
2
- var __extends = (this && this.__extends) || (function () {
3
- var extendStatics = function (d, b) {
4
- extendStatics = Object.setPrototypeOf ||
5
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
- return extendStatics(d, b);
8
- };
9
- return function (d, b) {
10
- if (typeof b !== "function" && b !== null)
11
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
- extendStatics(d, b);
13
- function __() { this.constructor = d; }
14
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
- };
16
- })();
17
- var __assign = (this && this.__assign) || function () {
18
- __assign = Object.assign || function(t) {
19
- for (var s, i = 1, n = arguments.length; i < n; i++) {
20
- s = arguments[i];
21
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
22
- t[p] = s[p];
23
- }
24
- return t;
25
- };
26
- return __assign.apply(this, arguments);
27
- };
28
- Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.ChatStore = void 0;
30
- var mobx_1 = require("mobx");
31
- var MetaStore_1 = require("../Meta/MetaStore");
32
- var AbstractStore_1 = require("../Abstract/AbstractStore");
33
- var snap_toolbox_1 = require("@athoscommerce/snap-toolbox");
34
- var ChatSessionStore_1 = require("./Stores/ChatSessionStore");
35
- var SearchResultStore_1 = require("../Search/Stores/SearchResultStore");
36
- var SearchFacetStore_1 = require("../Search/Stores/SearchFacetStore");
37
- var CHAT_STATUS_EXPIRATION_TIME = 1000 * 60 * 60 * 12; // 12 hours
38
- var ChatStore = /** @class */ (function (_super) {
39
- __extends(ChatStore, _super);
40
- function ChatStore(config, services) {
41
- var _this = _super.call(this, config) || this;
42
- _this.meta = undefined;
43
- _this.inputValue = '';
44
- _this.open = false;
45
- _this.chats = [];
46
- _this.chatEnabled = null;
47
- _this.initChatLoading = false;
48
- _this.suggestedQuestions = [];
49
- _this.welcomeMessage = '';
50
- _this.features = { imageSearch: { enabled: false }, similarProducts: { enabled: false } };
51
- _this.productQuickview = null;
52
- _this.productQuickviewError = null;
53
- /** Raw meta kept for lazy hydration of inactive chat sessions. */
54
- _this.storedMetaData = null;
55
- /** Tracks which message currently owns the displayed facets — guards against redundant rebuilds. */
56
- _this.activeFacetsMessageId = null;
57
- /** Bumps on every detached-urlManager change so observers re-evaluate isFacetSelected. */
58
- _this.urlVersion = 0;
59
- /** Snapshot of the applied filter state captured the last time the active message was seeded.
60
- * Compared against the live urlManager state to decide whether there are pending changes.
61
- * `null` means no facets have been seeded yet — there are no pending changes in that case. */
62
- _this.appliedFilterSnapshot = null;
63
- _this.services = services;
64
- _this.urlManager = services.urlManager.detach(true);
65
- _this.urlManager.subscribe(function () {
66
- _this.urlVersion++;
67
- });
68
- var legacyKey = "ss-".concat(_this.config.id);
69
- var storageKey = _this.config.siteId ? "ss-".concat(_this.config.siteId, "-").concat(_this.config.id) : legacyKey;
70
- _this.storage = new snap_toolbox_1.StorageStore({
71
- type: 'local',
72
- key: storageKey,
73
- });
74
- _this.facets = _this.buildFacetStore();
75
- var storedChatStatusResponse = _this.storage.get('chatStatusResponse');
76
- if (storedChatStatusResponse) {
77
- try {
78
- var storedChatStatus = JSON.parse(storedChatStatusResponse);
79
- if (storedChatStatus.checkTime && Date.now() - storedChatStatus.checkTime > CHAT_STATUS_EXPIRATION_TIME) {
80
- // chat status is expired, remove from storage to trigger a new check
81
- _this.storage.set('chatStatusResponse', null);
82
- }
83
- else {
84
- // Apply the stored response without persisting, so the 12-hour
85
- // checkTime keeps counting from the last real API call rather
86
- // than resetting on every page load.
87
- _this.applyChatStatusResponse(storedChatStatus.response);
88
- }
89
- }
90
- catch (_a) {
91
- _this.storage.set('chatStatusResponse', null);
92
- }
93
- }
94
- // check for entries in storage
95
- var latestChatId = '';
96
- var storedChats = _this.storage.get('chats');
97
- storedChats &&
98
- Object.keys(storedChats || {}).forEach(function (chatId) {
99
- var chatData = storedChats[chatId];
100
- if (chatData) {
101
- var restoredChat = new ChatSessionStore_1.ChatSessionStore({
102
- data: __assign(__assign({}, chatData), { id: chatId }),
103
- stores: {
104
- storage: _this.storage,
105
- },
106
- });
107
- // Mark as unhydrated — results are still raw JSON from storage.
108
- // Only the active session will be hydrated below.
109
- restoredChat.hydrated = false;
110
- _this.chats.push(restoredChat);
111
- latestChatId = chatId;
112
- }
113
- });
114
- // Prefer the persisted active chat ID so switching chats survives page reloads.
115
- // Fall back to the most recently created chat if the stored ID is missing or stale.
116
- var storedCurrentChatId = _this.storage.get('currentChatId');
117
- var activeChatId = storedCurrentChatId && _this.chats.some(function (chat) { return chat.id === storedCurrentChatId; }) ? storedCurrentChatId : latestChatId;
118
- var storedMeta = _this.storage.get('meta');
119
- if (storedMeta) {
120
- try {
121
- var metaData = JSON.parse(storedMeta);
122
- _this.meta = new MetaStore_1.MetaStore({
123
- data: {
124
- meta: metaData,
125
- },
126
- });
127
- // Keep raw meta for lazy hydration of inactive sessions
128
- _this.storedMetaData = metaData;
129
- // Only hydrate the active chat session — inactive sessions will be
130
- // hydrated lazily when switched to via switchChat()
131
- var activeChat = _this.chats.find(function (chat) { return chat.id === activeChatId; });
132
- if (activeChat) {
133
- activeChat.hydrateResults(metaData);
134
- activeChat.hydrated = true;
135
- }
136
- }
137
- catch (_b) {
138
- _this.storage.set('meta', null);
139
- }
140
- }
141
- _this.currentChatId = activeChatId;
142
- (0, mobx_1.makeObservable)(_this, {
143
- meta: mobx_1.observable,
144
- inputValue: mobx_1.observable,
145
- open: mobx_1.observable,
146
- chats: mobx_1.observable,
147
- currentChatId: mobx_1.observable,
148
- chatEnabled: mobx_1.observable,
149
- initChatLoading: mobx_1.observable,
150
- blocked: mobx_1.computed,
151
- currentChat: mobx_1.computed,
152
- chatsIds: mobx_1.computed,
153
- features: mobx_1.observable,
154
- suggestedQuestions: mobx_1.observable,
155
- welcomeMessage: mobx_1.observable,
156
- productQuickview: mobx_1.observable,
157
- productQuickviewError: mobx_1.observable,
158
- facets: mobx_1.observable,
159
- urlVersion: mobx_1.observable,
160
- hasPendingFacetChanges: mobx_1.computed,
161
- pendingFacetCount: mobx_1.computed,
162
- searchFilters: mobx_1.computed,
163
- });
164
- // Sync the root facets display with the active message. Only productSearchResult
165
- // messages carry facets — for any other active message, clear the display so a
166
- // stale facet bar from a previous response doesn't linger.
167
- // Exception: when the user clicks "discuss product" on a carousel result, the
168
- // active message becomes the productQuery side-chat, but the carousel is still
169
- // the last real message — keep its facets visible alongside the product context.
170
- (0, mobx_1.reaction)(function () {
171
- var chat = _this.currentChat;
172
- var active = chat === null || chat === void 0 ? void 0 : chat.activeMessage;
173
- if ((active === null || active === void 0 ? void 0 : active.messageType) === 'productSearchResult')
174
- return active;
175
- if ((active === null || active === void 0 ? void 0 : active.messageType) === 'productQuery' && chat) {
176
- var messages = chat.chat;
177
- var activeIdx = messages.findIndex(function (m) { return m.id === active.id; });
178
- if (activeIdx > 0 && messages[activeIdx - 1].messageType === 'productSearchResult') {
179
- return messages[activeIdx - 1];
180
- }
181
- }
182
- return null;
183
- }, function (active) {
184
- if (active && active.id !== _this.activeFacetsMessageId) {
185
- var facets = active.facets;
186
- _this.setActiveFacets(facets || [], active.id);
187
- }
188
- else if (!active && _this.activeFacetsMessageId !== null) {
189
- _this.setActiveFacets([], null);
190
- }
191
- }, { fireImmediately: true });
192
- // Mirror the urlManager's pending range filters into each RangeFacet's `active`.
193
- // Slider facets are remounted whenever their dropdown closes/reopens and the
194
- // FacetSlider seeds its state from facet.active — without this sync the slider
195
- // would snap back to the server-provided active on every reopen, losing the
196
- // user's pending selection until Apply is clicked.
197
- // Note: range filters round-trip through the detached urlManager's URL form,
198
- // so they come back as `[{low, high}]` arrays even though they were set as objects.
199
- var readRangeFilter = function (raw) {
200
- var entry = Array.isArray(raw) ? raw[raw.length - 1] : raw;
201
- if (!entry || typeof entry !== 'object')
202
- return null;
203
- if (typeof entry.low === 'undefined' && typeof entry.high === 'undefined')
204
- return null;
205
- return {
206
- low: entry.low === null || typeof entry.low === 'undefined' ? undefined : Number(entry.low),
207
- high: entry.high === null || typeof entry.high === 'undefined' ? undefined : Number(entry.high),
208
- };
209
- };
210
- (0, mobx_1.reaction)(function () {
211
- var _a;
212
- void _this.urlVersion;
213
- var filterState = ((_a = _this.urlManager.state) === null || _a === void 0 ? void 0 : _a.filter) || {};
214
- return _this.facets
215
- .filter(function (f) { return f.type === 'range'; })
216
- .map(function (f) {
217
- var _a, _b;
218
- var pending = readRangeFilter(filterState[f.field]);
219
- return "".concat(f.field, ":").concat((_a = pending === null || pending === void 0 ? void 0 : pending.low) !== null && _a !== void 0 ? _a : '*', ":").concat((_b = pending === null || pending === void 0 ? void 0 : pending.high) !== null && _b !== void 0 ? _b : '*');
220
- })
221
- .join('|');
222
- }, function () {
223
- var _a, _b, _c, _d, _e;
224
- var filterState = ((_a = _this.urlManager.state) === null || _a === void 0 ? void 0 : _a.filter) || {};
225
- for (var _i = 0, _f = _this.facets; _i < _f.length; _i++) {
226
- var facet = _f[_i];
227
- if (facet.type !== 'range')
228
- continue;
229
- var rangeFacet = facet;
230
- var pending_1 = readRangeFilter(filterState[rangeFacet.field]);
231
- var desired = pending_1
232
- ? {
233
- low: typeof pending_1.low !== 'undefined' ? pending_1.low : (_b = rangeFacet.range) === null || _b === void 0 ? void 0 : _b.low,
234
- high: typeof pending_1.high !== 'undefined' ? pending_1.high : (_c = rangeFacet.range) === null || _c === void 0 ? void 0 : _c.high,
235
- }
236
- : rangeFacet.range
237
- ? { low: rangeFacet.range.low, high: rangeFacet.range.high }
238
- : null;
239
- if (!desired)
240
- continue;
241
- if (((_d = rangeFacet.active) === null || _d === void 0 ? void 0 : _d.low) !== desired.low || ((_e = rangeFacet.active) === null || _e === void 0 ? void 0 : _e.high) !== desired.high) {
242
- rangeFacet.active = desired;
243
- }
244
- }
245
- }, { fireImmediately: true });
246
- return _this;
247
- }
248
- /** Build a SearchFacetStore from raw facet data using the current detached urlManager.
249
- * Synthesizes meta entries for each facet so SearchFacetStore's display/meta filter
250
- * doesn't drop chat facets (the chat backend already decided what to send). */
251
- ChatStore.prototype.buildFacetStore = function (facets) {
252
- var _a;
253
- if (facets === void 0) { facets = []; }
254
- var baseMeta = ((_a = this.meta) === null || _a === void 0 ? void 0 : _a.data) || {};
255
- var baseFacetMeta = baseMeta.facets || {};
256
- var facetMeta = __assign({}, baseFacetMeta);
257
- facets.forEach(function (facet) {
258
- if (!facet.field)
259
- return;
260
- var expectedDisplay = facet.type === 'range' ? 'slider' : 'list';
261
- var existing = facetMeta[facet.field];
262
- if (!existing || existing.display !== expectedDisplay) {
263
- facetMeta[facet.field] = __assign(__assign({}, (existing || {})), { field: facet.field, label: facet.label, display: expectedDisplay });
264
- }
265
- });
266
- return new SearchFacetStore_1.SearchFacetStore({
267
- config: {},
268
- services: __assign(__assign({}, this.services), { urlManager: this.urlManager }),
269
- stores: { storage: this.storage },
270
- data: {
271
- search: { facets: facets },
272
- meta: __assign(__assign({}, baseMeta), { facets: facetMeta }),
273
- },
274
- });
275
- };
276
- /** Reset the detached urlManager and seed it with this message's filtered facet values,
277
- * then rebuild the root SearchFacetStore so the UI shows the matching display. */
278
- ChatStore.prototype.setActiveFacets = function (facets, messageId) {
279
- var _this = this;
280
- var _a;
281
- // reset url state, then seed with the API-reported filtered values
282
- this.urlManager.reset().go();
283
- facets.forEach(function (facet) {
284
- // Slider/range facets carry the active selection on the facet itself rather
285
- // than on individual bucket values.
286
- if (facet.type === 'range') {
287
- var active = facet.active;
288
- var range = facet.range;
289
- if (active && range && (active.low !== range.low || active.high !== range.high)) {
290
- _this.urlManager.set("filter.".concat(facet.field), { low: active.low, high: active.high }).go();
291
- }
292
- return;
293
- }
294
- var filteredValues = (facet.values || []).filter(function (v) { return v === null || v === void 0 ? void 0 : v.filtered; });
295
- filteredValues.forEach(function (v) {
296
- if (typeof v.low !== 'undefined' || typeof v.high !== 'undefined') {
297
- _this.urlManager.merge("filter.".concat(facet.field), [{ low: v.low, high: v.high }]).go();
298
- }
299
- else if (typeof v.value !== 'undefined') {
300
- _this.urlManager.merge("filter.".concat(facet.field), v.value).go();
301
- }
302
- });
303
- });
304
- this.facets = this.buildFacetStore(facets);
305
- this.activeFacetsMessageId = messageId;
306
- this.appliedFilterSnapshot = stableStringify((_a = this.urlManager.state) === null || _a === void 0 ? void 0 : _a.filter);
307
- };
308
- Object.defineProperty(ChatStore.prototype, "pendingFacetCount", {
309
- /** Total number of selected facet values in the in-progress urlManager state, summed
310
- * across all filter fields. Each value in a value facet, each range in a range-bucket
311
- * facet, and the single range on a slider facet each count as one. */
312
- get: function () {
313
- var _a;
314
- void this.urlVersion;
315
- var filterState = (_a = this.urlManager.state) === null || _a === void 0 ? void 0 : _a.filter;
316
- if (!filterState)
317
- return 0;
318
- var count = 0;
319
- for (var _i = 0, _b = Object.keys(filterState); _i < _b.length; _i++) {
320
- var key = _b[_i];
321
- var value = filterState[key];
322
- if (Array.isArray(value)) {
323
- count += value.length;
324
- }
325
- else if (typeof value !== 'undefined') {
326
- count += 1;
327
- }
328
- }
329
- return count;
330
- },
331
- enumerable: false,
332
- configurable: true
333
- });
334
- Object.defineProperty(ChatStore.prototype, "searchFilters", {
335
- /** Current in-progress facet selection translated into the API's `searchFilters` shape.
336
- * Returned unconditionally (not gated on `hasPendingFacetChanges`) so callers that need
337
- * to explicitly force a `productSearch` request — e.g. the non-multiselect facet
338
- * click handlers — can attach the current filters without re-implementing the mapping. */
339
- get: function () {
340
- var _a;
341
- void this.urlVersion;
342
- var filterState = (_a = this.urlManager.state) === null || _a === void 0 ? void 0 : _a.filter;
343
- var result = [];
344
- if (!filterState)
345
- return result;
346
- Object.keys(filterState).forEach(function (field) {
347
- var raw = filterState[field];
348
- var values = Array.isArray(raw) ? raw : [raw];
349
- var options = [];
350
- values.forEach(function (v) {
351
- if (typeof v === 'object' && v !== null) {
352
- var low = v.low;
353
- var high = v.high;
354
- if (low == null && high == null)
355
- return;
356
- options.push({ low: low == null ? '*' : String(low), high: high == null ? '*' : String(high) });
357
- }
358
- else {
359
- options.push({ key: String(v) });
360
- }
361
- });
362
- if (options.length > 0) {
363
- result.push({ key: field, options: options });
364
- }
365
- });
366
- return result;
367
- },
368
- enumerable: false,
369
- configurable: true
370
- });
371
- Object.defineProperty(ChatStore.prototype, "hasPendingFacetChanges", {
372
- /** True when the in-progress facet selection differs from the filters that were applied
373
- * by the active productSearchResult — i.e. the user has selected/removed something that
374
- * hasn't been sent yet. Used to decide whether to show the Apply button. */
375
- get: function () {
376
- var _a;
377
- // touch the version so mobx re-runs this when urlManager state changes
378
- void this.urlVersion;
379
- var filterState = (_a = this.urlManager.state) === null || _a === void 0 ? void 0 : _a.filter;
380
- if (this.appliedFilterSnapshot === null) {
381
- // No facets have been seeded — pending changes exist only if
382
- // the user has manually added filters via addFacet.
383
- return filterState !== undefined && Object.keys(filterState).length > 0;
384
- }
385
- return stableStringify(filterState) !== this.appliedFilterSnapshot;
386
- },
387
- enumerable: false,
388
- configurable: true
389
- });
390
- Object.defineProperty(ChatStore.prototype, "currentChat", {
391
- get: function () {
392
- var _this = this;
393
- return this.chats.find(function (chat) { return chat.id === _this.currentChatId; });
394
- },
395
- enumerable: false,
396
- configurable: true
397
- });
398
- Object.defineProperty(ChatStore.prototype, "chatsIds", {
399
- get: function () {
400
- return this.chats.map(function (chat) { return chat.id; });
401
- },
402
- enumerable: false,
403
- configurable: true
404
- });
405
- Object.defineProperty(ChatStore.prototype, "blocked", {
406
- get: function () {
407
- var _a;
408
- var isBlocked = false;
409
- var blockedAttachments = (_a = this.currentChat) === null || _a === void 0 ? void 0 : _a.attachments.items.some(function (item) { return item.type === 'image' && item.state === 'loading'; });
410
- if (this.loading || blockedAttachments) {
411
- isBlocked = true;
412
- }
413
- return isBlocked;
414
- },
415
- enumerable: false,
416
- configurable: true
417
- });
418
- ChatStore.prototype.applyChatStatusResponse = function (response) {
419
- var chatbot = response.chatbot, features = response.features;
420
- var status = chatbot.status, suggestedQuestions = chatbot.suggestedQuestions, welcomeMessage = chatbot.welcomeMessage;
421
- this.chatEnabled = status.enabled === true;
422
- this.features = features;
423
- this.suggestedQuestions = suggestedQuestions || [];
424
- this.welcomeMessage = welcomeMessage || '';
425
- return this.chatEnabled;
426
- };
427
- ChatStore.prototype.handleChatStatusResponse = function (response) {
428
- var enabled = this.applyChatStatusResponse(response);
429
- // Always persist on a real API response — restarts the 12-hour expiration
430
- // so each new chat session refreshes the cache.
431
- this.storage.set('chatStatusResponse', JSON.stringify({ response: response, checkTime: Date.now() }));
432
- return enabled;
433
- };
434
- ChatStore.prototype.reset = function () {
435
- this.chats = [];
436
- this.clearProductQuickview();
437
- this.storage.clear();
438
- this.createChat();
439
- };
440
- ChatStore.prototype.setProductQuickview = function (product) {
441
- var _a;
442
- // Clone the product so variant selections (and the parent-mappings merge done
443
- // in updateProductQuickview) only affect the quickview — the carousel and any
444
- // other surfaces still hold the original instance.
445
- this.productQuickview = cloneProductForQuickview(product, (_a = this.meta) === null || _a === void 0 ? void 0 : _a.data);
446
- this.productQuickviewError = null;
447
- };
448
- ChatStore.prototype.updateProductQuickview = function (response) {
449
- var _a;
450
- if (!this.productQuickview) {
451
- return;
452
- }
453
- // merge parent-level mappings from the API response into the Product
454
- this.productQuickview.mappings = __assign(__assign({}, this.productQuickview.mappings), { core: __assign(__assign({}, this.productQuickview.mappings.core), response.mappings.core) });
455
- var meta = ((_a = this.meta) === null || _a === void 0 ? void 0 : _a.data) || {};
456
- if (this.productQuickview.variants) {
457
- // update existing Variants with new data from the Products API
458
- this.productQuickview.variants.optionConfig = response.variants.optionConfig;
459
- this.productQuickview.variants.update(response.variants.data);
460
- }
461
- else {
462
- // create Variants for the first time using the Products API data
463
- this.productQuickview.variants = new SearchResultStore_1.Variants({
464
- data: {
465
- mask: this.productQuickview.mask,
466
- variants: response.variants.data,
467
- optionConfig: response.variants.optionConfig,
468
- meta: meta,
469
- },
470
- });
471
- }
472
- };
473
- ChatStore.prototype.setProductQuickviewError = function (message) {
474
- this.productQuickviewError = message;
475
- };
476
- ChatStore.prototype.clearProductQuickview = function () {
477
- this.productQuickview = null;
478
- this.productQuickviewError = null;
479
- };
480
- ChatStore.prototype.clearHistory = function () {
481
- // drop previous chats while keeping the conversation the user is currently in;
482
- // if there is no current chat, fall back to a full reset
483
- var currentChat = this.currentChat;
484
- if (!currentChat) {
485
- this.reset();
486
- return;
487
- }
488
- var storedChats = this.storage.get('chats') || {};
489
- var filtered = {};
490
- if (storedChats[currentChat.id]) {
491
- filtered[currentChat.id] = storedChats[currentChat.id];
492
- }
493
- this.storage.set('chats', filtered);
494
- this.chats = [currentChat];
495
- };
496
- ChatStore.prototype.createChat = function (data) {
497
- // abandon any in-flight request state from the previous chat — its
498
- // response will be discarded by the controller, so the UI shouldn't
499
- // keep showing its loading spinner or stale error
500
- this.loading = false;
501
- this.error = undefined;
502
- // Prune old sessions before creating a new one to keep storage bounded
503
- ChatSessionStore_1.ChatSessionStore.pruneStoredSessions(this.storage);
504
- var newChat = new ChatSessionStore_1.ChatSessionStore({
505
- data: {
506
- sessionId: data === null || data === void 0 ? void 0 : data.sessionId,
507
- sessionEndTime: data === null || data === void 0 ? void 0 : data.sessionEndTime,
508
- },
509
- stores: {
510
- storage: this.storage,
511
- },
512
- });
513
- this.currentChatId = newChat.id;
514
- this.storage.set('currentChatId', newChat.id);
515
- this.chats.push(newChat);
516
- return newChat;
517
- };
518
- ChatStore.prototype.switchChat = function (id) {
519
- var chatExists = this.chats.find(function (chat) { return chat.id === id; });
520
- if (chatExists) {
521
- // Lazily hydrate results when switching to a session for the first time
522
- if (!chatExists.hydrated && this.storedMetaData) {
523
- chatExists.hydrateResults(this.storedMetaData);
524
- chatExists.hydrated = true;
525
- }
526
- this.currentChatId = id;
527
- this.storage.set('currentChatId', id);
528
- }
529
- };
530
- ChatStore.prototype.sendProductQuery = function (result, options) {
531
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
532
- var display = (result === null || result === void 0 ? void 0 : result.display) || result;
533
- (_a = this.currentChat) === null || _a === void 0 ? void 0 : _a.attachments.add({
534
- type: 'product',
535
- requestType: options.requestType,
536
- productId: result.id,
537
- name: (_c = (_b = display.mappings) === null || _b === void 0 ? void 0 : _b.core) === null || _c === void 0 ? void 0 : _c.name,
538
- thumbnailUrl: ((_e = (_d = display.mappings) === null || _d === void 0 ? void 0 : _d.core) === null || _e === void 0 ? void 0 : _e.thumbnailImageUrl) || ((_g = (_f = display.mappings) === null || _f === void 0 ? void 0 : _f.core) === null || _g === void 0 ? void 0 : _g.imageUrl) || ((_j = (_h = display.mappings) === null || _h === void 0 ? void 0 : _h.core) === null || _j === void 0 ? void 0 : _j.parentImageUrl),
539
- });
540
- // for the productQuery flow we want the secondary chat to immediately
541
- // show the product details panel — push a productQuery message so it
542
- // becomes the active side-chat message until a productAnswer arrives
543
- if (options.requestType === 'productQuery' && this.currentChat) {
544
- this.currentChat.pushProductQueryMessage(result);
545
- }
546
- };
547
- ChatStore.prototype.compareProduct = function (result) {
548
- var _a;
549
- (_a = this.currentChat) === null || _a === void 0 ? void 0 : _a.comparisons.add({
550
- result: result,
551
- });
552
- };
553
- ChatStore.prototype.addFacet = function (facet) {
554
- var value = parseFacetValue(facet.value);
555
- this.urlManager.merge("filter.".concat(facet.key), Array.isArray(value) ? value : value).go();
556
- };
557
- ChatStore.prototype.removeFacet = function (key, value) {
558
- var parsed = parseFacetValue(value);
559
- this.urlManager.remove("filter.".concat(key), parsed).go();
560
- };
561
- ChatStore.prototype.clearPendingFacets = function () {
562
- this.urlManager.remove('filter').go();
563
- };
564
- ChatStore.prototype.isFacetSelected = function (key, value) {
565
- var _a;
566
- // touch the version so mobx re-runs this when urlManager state changes (the
567
- // underlying UrlManager isn't a mobx observable, so we mirror its updates here)
568
- void this.urlVersion;
569
- var filterState = (_a = this.urlManager.state) === null || _a === void 0 ? void 0 : _a.filter;
570
- if (!filterState || !filterState[key])
571
- return false;
572
- var stored = Array.isArray(filterState[key]) ? filterState[key] : [filterState[key]];
573
- var parsed = parseFacetValue(value);
574
- return stored.some(function (entry) { return facetValueEquals(entry, parsed); });
575
- };
576
- ChatStore.prototype.request = function (request) {
577
- var _this = this;
578
- var _a, _b;
579
- // snapshot facet labels (field + per-value) from the active facets display so the
580
- // outgoing user message can render "Filter by Color Red" rather than raw keys
581
- var filterLabels = {};
582
- var _loop_1 = function (facet) {
583
- var valueFacet = facet;
584
- var values = {};
585
- (valueFacet.values || []).forEach(function (v) {
586
- var _a, _b;
587
- if (typeof v.low !== 'undefined' || typeof v.high !== 'undefined') {
588
- values["".concat((_a = v.low) !== null && _a !== void 0 ? _a : '*', ":").concat((_b = v.high) !== null && _b !== void 0 ? _b : '*')] = v.label;
589
- }
590
- else if (typeof v.value !== 'undefined') {
591
- values[v.value] = v.label;
592
- }
593
- });
594
- filterLabels[valueFacet.field] = { facetLabel: valueFacet.label || valueFacet.field, values: values };
595
- };
596
- for (var _i = 0, _c = this.facets; _i < _c.length; _i++) {
597
- var facet = _c[_i];
598
- _loop_1(facet);
599
- }
600
- (_a = this.currentChat) === null || _a === void 0 ? void 0 : _a.request(request, filterLabels);
601
- // remove any productSimilar attachments after request
602
- var productSimilarAttachments = ((_b = this.currentChat) === null || _b === void 0 ? void 0 : _b.attachments.attached.filter(function (item) { return item.type === 'product' && item.requestType === 'productSimilar'; })) || [];
603
- productSimilarAttachments.forEach(function (item) {
604
- var _a;
605
- (_a = _this.currentChat) === null || _a === void 0 ? void 0 : _a.attachments.remove(item.id);
606
- });
607
- };
608
- ChatStore.prototype.update = function (data) {
609
- // TODO: handle error
610
- // if(err?.responseBody?.errorMessage || err?.responseBody?.errorCode) {
611
- // const errorMessage = err?.responseBody?.errorMessage || 'An unknown error has occurred.';
612
- // }
613
- var _a;
614
- (_a = this.currentChat) === null || _a === void 0 ? void 0 : _a.update(data);
615
- if (!this.meta) {
616
- this.storage.set('meta', JSON.stringify(data.meta));
617
- }
618
- this.meta = new MetaStore_1.MetaStore({
619
- data: {
620
- meta: data.meta,
621
- },
622
- });
623
- // Keep raw meta in sync for lazy hydration of inactive sessions
624
- this.storedMetaData = data.meta;
625
- };
626
- return ChatStore;
627
- }(AbstractStore_1.AbstractStore));
628
- exports.ChatStore = ChatStore;
629
- /** Deterministic JSON.stringify — sorts object keys recursively so equality comparisons
630
- * aren't sensitive to insertion order. */
631
- function stableStringify(value) {
632
- if (value === null || value === undefined)
633
- return 'null';
634
- if (typeof value !== 'object')
635
- return JSON.stringify(value);
636
- if (Array.isArray(value)) {
637
- return "[".concat(value.map(function (v) { return stableStringify(v); }).join(','), "]");
638
- }
639
- var keys = Object.keys(value).sort();
640
- return "{".concat(keys.map(function (k) { return "".concat(JSON.stringify(k), ":").concat(stableStringify(value[k])); }).join(','), "}");
641
- }
642
- /** Convert a chat-facet UI value into the URL-state shape — range buckets arrive as "low:high". */
643
- function parseFacetValue(value) {
644
- if (typeof value === 'string' && value.includes(':')) {
645
- var _a = value.split(':'), low = _a[0], high = _a[1];
646
- return {
647
- low: low === '*' ? undefined : Number(low),
648
- high: high === '*' ? undefined : Number(high),
649
- };
650
- }
651
- return value;
652
- }
653
- function facetValueEquals(a, b) {
654
- if (typeof a === 'object' && a !== null && typeof b === 'object' && b !== null) {
655
- return a.low === b.low && a.high === b.high;
656
- }
657
- return a === b;
658
- }
659
- /** Build a fresh observable Product from an existing one. Variants are intentionally
660
- * omitted — `updateProductQuickview` populates them from the products API response. */
661
- function cloneProductForQuickview(product, meta) {
662
- var _a, _b, _c;
663
- var result = {
664
- id: product.id,
665
- responseId: product.responseId,
666
- mappings: JSON.parse(JSON.stringify(product.mappings || {})),
667
- attributes: JSON.parse(JSON.stringify(product.attributes || {})),
668
- badges: ((_b = (_a = product.badges) === null || _a === void 0 ? void 0 : _a.all) === null || _b === void 0 ? void 0 : _b.map(function (b) { return ({ tag: b.tag }); })) || [],
669
- };
670
- return new SearchResultStore_1.Product({
671
- config: {},
672
- data: { result: result, meta: meta || {} },
673
- position: (_c = product.position) !== null && _c !== void 0 ? _c : 0,
674
- responseId: product.responseId,
675
- });
676
- }