@athoscommerce/snap-store-mobx 1.7.0 → 1.7.1-beta.129

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