@athoscommerce/snap-store-mobx 1.5.0 → 1.5.1-beta.112

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 +87 -0
  3. package/dist/cjs/Chat/ChatStore.d.ts.map +1 -0
  4. package/dist/cjs/Chat/ChatStore.js +545 -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 +314 -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 +65 -0
  11. package/dist/cjs/Chat/Stores/ChatSessionStore.d.ts +107 -0
  12. package/dist/cjs/Chat/Stores/ChatSessionStore.d.ts.map +1 -0
  13. package/dist/cjs/Chat/Stores/ChatSessionStore.js +635 -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 +21 -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 +87 -0
  26. package/dist/esm/Chat/ChatStore.d.ts.map +1 -0
  27. package/dist/esm/Chat/ChatStore.js +484 -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 +222 -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 +51 -0
  34. package/dist/esm/Chat/Stores/ChatSessionStore.d.ts +107 -0
  35. package/dist/esm/Chat/Stores/ChatSessionStore.d.ts.map +1 -0
  36. package/dist/esm/Chat/Stores/ChatSessionStore.js +601 -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 +21 -2
  46. package/dist/esm/types.d.ts.map +1 -1
  47. package/package.json +5 -5
@@ -0,0 +1,484 @@
1
+ import { makeObservable, observable, computed, reaction } from 'mobx';
2
+ import { MetaStore } from '../Meta/MetaStore';
3
+ import { AbstractStore } from '../Abstract/AbstractStore';
4
+ import { StorageStore } from '@athoscommerce/snap-toolbox';
5
+ import { ChatSessionStore } from './Stores/ChatSessionStore';
6
+ import { Product, Variants } from '../Search/Stores/SearchResultStore';
7
+ import { SearchFacetStore } from '../Search/Stores/SearchFacetStore';
8
+ const CHAT_STATUS_EXPIRATION_TIME = 1000 * 60 * 60 * 12; // 12 hours
9
+ export class ChatStore extends AbstractStore {
10
+ constructor(config, services) {
11
+ super(config);
12
+ this.meta = undefined;
13
+ this.inputValue = '';
14
+ this.open = false;
15
+ this.chats = [];
16
+ this.chatEnabled = null;
17
+ this.initChatLoading = false;
18
+ this.suggestedQuestions = [];
19
+ this.welcomeMessage = '';
20
+ this.features = { imageSearch: { enabled: false }, similarProducts: { enabled: false } };
21
+ this.productQuickview = null;
22
+ this.productQuickviewError = null;
23
+ /** Raw meta kept for lazy hydration of inactive chat sessions. */
24
+ this.storedMetaData = null;
25
+ /** Tracks which message currently owns the displayed facets — guards against redundant rebuilds. */
26
+ this.activeFacetsMessageId = null;
27
+ /** Bumps on every detached-urlManager change so observers re-evaluate isFacetSelected. */
28
+ this.urlVersion = 0;
29
+ /** Snapshot of the applied filter state captured the last time the active message was seeded.
30
+ * Compared against the live urlManager state to decide whether there are pending changes.
31
+ * `null` means no facets have been seeded yet — there are no pending changes in that case. */
32
+ this.appliedFilterSnapshot = null;
33
+ this.services = services;
34
+ this.urlManager = services.urlManager.detach(true);
35
+ this.urlManager.subscribe(() => {
36
+ this.urlVersion++;
37
+ });
38
+ const legacyKey = `ss-${this.config.id}`;
39
+ const storageKey = this.config.siteId ? `ss-${this.config.siteId}-${this.config.id}` : legacyKey;
40
+ this.storage = new StorageStore({
41
+ type: 'local',
42
+ key: storageKey,
43
+ });
44
+ this.facets = this.buildFacetStore();
45
+ const storedChatStatusResponse = this.storage.get('chatStatusResponse');
46
+ if (storedChatStatusResponse) {
47
+ try {
48
+ const storedChatStatus = JSON.parse(storedChatStatusResponse);
49
+ if (storedChatStatus.checkTime && Date.now() - storedChatStatus.checkTime > CHAT_STATUS_EXPIRATION_TIME) {
50
+ // chat status is expired, remove from storage to trigger a new check
51
+ this.storage.set('chatStatusResponse', null);
52
+ }
53
+ else {
54
+ // Apply the stored response without persisting, so the 12-hour
55
+ // checkTime keeps counting from the last real API call rather
56
+ // than resetting on every page load.
57
+ this.applyChatStatusResponse(storedChatStatus.response);
58
+ }
59
+ }
60
+ catch {
61
+ this.storage.set('chatStatusResponse', null);
62
+ }
63
+ }
64
+ // check for entries in storage
65
+ let latestChatId = '';
66
+ const storedChats = this.storage.get('chats');
67
+ storedChats &&
68
+ Object.keys(storedChats || {}).forEach((chatId) => {
69
+ const chatData = storedChats[chatId];
70
+ if (chatData) {
71
+ const restoredChat = new ChatSessionStore({
72
+ data: {
73
+ ...chatData,
74
+ id: chatId,
75
+ },
76
+ stores: {
77
+ storage: this.storage,
78
+ },
79
+ });
80
+ // Mark as unhydrated — results are still raw JSON from storage.
81
+ // Only the active session will be hydrated below.
82
+ restoredChat.hydrated = false;
83
+ this.chats.push(restoredChat);
84
+ latestChatId = chatId;
85
+ }
86
+ });
87
+ // Prefer the persisted active chat ID so switching chats survives page reloads.
88
+ // Fall back to the most recently created chat if the stored ID is missing or stale.
89
+ const storedCurrentChatId = this.storage.get('currentChatId');
90
+ const activeChatId = storedCurrentChatId && this.chats.some((chat) => chat.id === storedCurrentChatId) ? storedCurrentChatId : latestChatId;
91
+ const storedMeta = this.storage.get('meta');
92
+ if (storedMeta) {
93
+ try {
94
+ const metaData = JSON.parse(storedMeta);
95
+ this.meta = new MetaStore({
96
+ data: {
97
+ meta: metaData,
98
+ },
99
+ });
100
+ // Keep raw meta for lazy hydration of inactive sessions
101
+ this.storedMetaData = metaData;
102
+ // Only hydrate the active chat session — inactive sessions will be
103
+ // hydrated lazily when switched to via switchChat()
104
+ const activeChat = this.chats.find((chat) => chat.id === activeChatId);
105
+ if (activeChat) {
106
+ activeChat.hydrateResults(metaData);
107
+ activeChat.hydrated = true;
108
+ }
109
+ }
110
+ catch {
111
+ this.storage.set('meta', null);
112
+ }
113
+ }
114
+ this.currentChatId = activeChatId;
115
+ makeObservable(this, {
116
+ meta: observable,
117
+ inputValue: observable,
118
+ open: observable,
119
+ chats: observable,
120
+ currentChatId: observable,
121
+ chatEnabled: observable,
122
+ initChatLoading: observable,
123
+ blocked: computed,
124
+ currentChat: computed,
125
+ chatsIds: computed,
126
+ features: observable,
127
+ suggestedQuestions: observable,
128
+ welcomeMessage: observable,
129
+ productQuickview: observable,
130
+ productQuickviewError: observable,
131
+ facets: observable,
132
+ urlVersion: observable,
133
+ hasPendingFacetChanges: computed,
134
+ });
135
+ // Sync the root facets display with the active message. Only productSearchResult
136
+ // messages carry facets — for any other active message, clear the display so a
137
+ // stale facet bar from a previous response doesn't linger.
138
+ reaction(() => {
139
+ const active = this.currentChat?.activeMessage;
140
+ return active && active.messageType === 'productSearchResult' ? active : null;
141
+ }, (active) => {
142
+ if (active && active.id !== this.activeFacetsMessageId) {
143
+ const facets = active.facets;
144
+ this.setActiveFacets(facets || [], active.id);
145
+ }
146
+ else if (!active && this.activeFacetsMessageId !== null) {
147
+ this.setActiveFacets([], null);
148
+ }
149
+ }, { fireImmediately: true });
150
+ }
151
+ /** Build a SearchFacetStore from raw facet data using the current detached urlManager.
152
+ * Synthesizes meta entries for each facet so SearchFacetStore's display/meta filter
153
+ * doesn't drop chat facets (the chat backend already decided what to send). */
154
+ buildFacetStore(facets = []) {
155
+ const baseMeta = this.meta?.data || {};
156
+ const baseFacetMeta = baseMeta.facets || {};
157
+ const facetMeta = { ...baseFacetMeta };
158
+ facets.forEach((facet) => {
159
+ if (!facet.field)
160
+ return;
161
+ const expectedDisplay = facet.type === 'range' ? 'slider' : 'list';
162
+ const existing = facetMeta[facet.field];
163
+ if (!existing || existing.display !== expectedDisplay) {
164
+ facetMeta[facet.field] = {
165
+ ...(existing || {}),
166
+ field: facet.field,
167
+ label: facet.label,
168
+ display: expectedDisplay,
169
+ };
170
+ }
171
+ });
172
+ return new SearchFacetStore({
173
+ config: {},
174
+ services: { ...this.services, urlManager: this.urlManager },
175
+ stores: { storage: this.storage },
176
+ data: {
177
+ search: { facets },
178
+ meta: { ...baseMeta, facets: facetMeta },
179
+ },
180
+ });
181
+ }
182
+ /** Reset the detached urlManager and seed it with this message's filtered facet values,
183
+ * then rebuild the root SearchFacetStore so the UI shows the matching display. */
184
+ setActiveFacets(facets, messageId) {
185
+ // reset url state, then seed with the API-reported filtered values
186
+ this.urlManager.reset().go();
187
+ facets.forEach((facet) => {
188
+ // Slider/range facets carry the active selection on the facet itself rather
189
+ // than on individual bucket values.
190
+ if (facet.type === 'range') {
191
+ const active = facet.active;
192
+ const range = facet.range;
193
+ if (active && range && (active.low !== range.low || active.high !== range.high)) {
194
+ this.urlManager.set(`filter.${facet.field}`, { low: active.low, high: active.high }).go();
195
+ }
196
+ return;
197
+ }
198
+ const filteredValues = (facet.values || []).filter((v) => v?.filtered);
199
+ filteredValues.forEach((v) => {
200
+ if (typeof v.low !== 'undefined' || typeof v.high !== 'undefined') {
201
+ this.urlManager.merge(`filter.${facet.field}`, [{ low: v.low, high: v.high }]).go();
202
+ }
203
+ else if (typeof v.value !== 'undefined') {
204
+ this.urlManager.merge(`filter.${facet.field}`, v.value).go();
205
+ }
206
+ });
207
+ });
208
+ this.facets = this.buildFacetStore(facets);
209
+ this.activeFacetsMessageId = messageId;
210
+ this.appliedFilterSnapshot = stableStringify(this.urlManager.state?.filter);
211
+ }
212
+ /** True when the in-progress facet selection differs from the filters that were applied
213
+ * by the active productSearchResult — i.e. the user has selected/removed something that
214
+ * hasn't been sent yet. Used to decide whether to show the Apply button. */
215
+ get hasPendingFacetChanges() {
216
+ // touch the version so mobx re-runs this when urlManager state changes
217
+ void this.urlVersion;
218
+ const filterState = this.urlManager.state?.filter;
219
+ if (this.appliedFilterSnapshot === null) {
220
+ // No facets have been seeded — pending changes exist only if
221
+ // the user has manually added filters via addFacet.
222
+ return filterState !== undefined && Object.keys(filterState).length > 0;
223
+ }
224
+ return stableStringify(filterState) !== this.appliedFilterSnapshot;
225
+ }
226
+ get currentChat() {
227
+ return this.chats.find((chat) => chat.id === this.currentChatId);
228
+ }
229
+ get chatsIds() {
230
+ return this.chats.map((chat) => chat.id);
231
+ }
232
+ get blocked() {
233
+ let isBlocked = false;
234
+ const blockedAttachments = this.currentChat?.attachments.items.some((item) => item.type === 'image' && item.state === 'loading');
235
+ if (this.loading || blockedAttachments) {
236
+ isBlocked = true;
237
+ }
238
+ return isBlocked;
239
+ }
240
+ applyChatStatusResponse(response) {
241
+ const { chatbot, features } = response;
242
+ const { status, suggestedQuestions, welcomeMessage } = chatbot;
243
+ this.chatEnabled = status.enabled === true;
244
+ this.features = features;
245
+ this.suggestedQuestions = suggestedQuestions || [];
246
+ this.welcomeMessage = welcomeMessage || '';
247
+ return this.chatEnabled;
248
+ }
249
+ handleChatStatusResponse(response) {
250
+ const enabled = this.applyChatStatusResponse(response);
251
+ // Always persist on a real API response — restarts the 12-hour expiration
252
+ // so each new chat session refreshes the cache.
253
+ this.storage.set('chatStatusResponse', JSON.stringify({ response, checkTime: Date.now() }));
254
+ return enabled;
255
+ }
256
+ reset() {
257
+ this.chats = [];
258
+ this.clearProductQuickview();
259
+ this.storage.clear();
260
+ this.createChat();
261
+ }
262
+ setProductQuickview(product) {
263
+ // Clone the product so variant selections (and the parent-mappings merge done
264
+ // in updateProductQuickview) only affect the quickview — the carousel and any
265
+ // other surfaces still hold the original instance.
266
+ this.productQuickview = cloneProductForQuickview(product, this.meta?.data);
267
+ this.productQuickviewError = null;
268
+ }
269
+ updateProductQuickview(response) {
270
+ if (!this.productQuickview) {
271
+ return;
272
+ }
273
+ // merge parent-level mappings from the API response into the Product
274
+ this.productQuickview.mappings = {
275
+ ...this.productQuickview.mappings,
276
+ core: { ...this.productQuickview.mappings.core, ...response.mappings.core },
277
+ };
278
+ const meta = this.meta?.data || {};
279
+ if (this.productQuickview.variants) {
280
+ // update existing Variants with new data from the Products API
281
+ this.productQuickview.variants.optionConfig = response.variants.optionConfig;
282
+ this.productQuickview.variants.update(response.variants.data);
283
+ }
284
+ else {
285
+ // create Variants for the first time using the Products API data
286
+ this.productQuickview.variants = new Variants({
287
+ data: {
288
+ mask: this.productQuickview.mask,
289
+ variants: response.variants.data,
290
+ optionConfig: response.variants.optionConfig,
291
+ meta,
292
+ },
293
+ });
294
+ }
295
+ }
296
+ setProductQuickviewError(message) {
297
+ this.productQuickviewError = message;
298
+ }
299
+ clearProductQuickview() {
300
+ this.productQuickview = null;
301
+ this.productQuickviewError = null;
302
+ }
303
+ clearHistory() {
304
+ // drop previous chats while keeping the conversation the user is currently in;
305
+ // if there is no current chat, fall back to a full reset
306
+ const currentChat = this.currentChat;
307
+ if (!currentChat) {
308
+ this.reset();
309
+ return;
310
+ }
311
+ const storedChats = this.storage.get('chats') || {};
312
+ const filtered = {};
313
+ if (storedChats[currentChat.id]) {
314
+ filtered[currentChat.id] = storedChats[currentChat.id];
315
+ }
316
+ this.storage.set('chats', filtered);
317
+ this.chats = [currentChat];
318
+ }
319
+ createChat(data) {
320
+ // abandon any in-flight request state from the previous chat — its
321
+ // response will be discarded by the controller, so the UI shouldn't
322
+ // keep showing its loading spinner or stale error
323
+ this.loading = false;
324
+ this.error = undefined;
325
+ // Prune old sessions before creating a new one to keep storage bounded
326
+ ChatSessionStore.pruneStoredSessions(this.storage);
327
+ const newChat = new ChatSessionStore({
328
+ data: {
329
+ sessionId: data?.sessionId,
330
+ sessionEndTime: data?.sessionEndTime,
331
+ },
332
+ stores: {
333
+ storage: this.storage,
334
+ },
335
+ });
336
+ this.currentChatId = newChat.id;
337
+ this.storage.set('currentChatId', newChat.id);
338
+ this.chats.push(newChat);
339
+ return newChat;
340
+ }
341
+ switchChat(id) {
342
+ const chatExists = this.chats.find((chat) => chat.id === id);
343
+ if (chatExists) {
344
+ // Lazily hydrate results when switching to a session for the first time
345
+ if (!chatExists.hydrated && this.storedMetaData) {
346
+ chatExists.hydrateResults(this.storedMetaData);
347
+ chatExists.hydrated = true;
348
+ }
349
+ this.currentChatId = id;
350
+ this.storage.set('currentChatId', id);
351
+ }
352
+ }
353
+ sendProductQuery(result, options) {
354
+ const display = result?.display || result;
355
+ this.currentChat?.attachments.add({
356
+ type: 'product',
357
+ requestType: options.requestType,
358
+ productId: result.id,
359
+ name: display.mappings?.core?.name,
360
+ thumbnailUrl: display.mappings?.core?.thumbnailImageUrl || display.mappings?.core?.imageUrl || display.mappings?.core?.parentImageUrl,
361
+ });
362
+ // for the productQuery flow we want the secondary chat to immediately
363
+ // show the product details panel — push a productQuery message so it
364
+ // becomes the active side-chat message until a productAnswer arrives
365
+ if (options.requestType === 'productQuery' && this.currentChat) {
366
+ this.currentChat.pushProductQueryMessage(result);
367
+ }
368
+ }
369
+ compareProduct(result) {
370
+ this.currentChat?.comparisons.add({
371
+ result,
372
+ });
373
+ }
374
+ addFacet(facet) {
375
+ const value = parseFacetValue(facet.value);
376
+ this.urlManager.merge(`filter.${facet.key}`, Array.isArray(value) ? value : value).go();
377
+ }
378
+ removeFacet(key, value) {
379
+ const parsed = parseFacetValue(value);
380
+ this.urlManager.remove(`filter.${key}`, parsed).go();
381
+ }
382
+ clearPendingFacets() {
383
+ this.urlManager.remove('filter').go();
384
+ }
385
+ isFacetSelected(key, value) {
386
+ // touch the version so mobx re-runs this when urlManager state changes (the
387
+ // underlying UrlManager isn't a mobx observable, so we mirror its updates here)
388
+ void this.urlVersion;
389
+ const filterState = this.urlManager.state?.filter;
390
+ if (!filterState || !filterState[key])
391
+ return false;
392
+ const stored = Array.isArray(filterState[key]) ? filterState[key] : [filterState[key]];
393
+ const parsed = parseFacetValue(value);
394
+ return stored.some((entry) => facetValueEquals(entry, parsed));
395
+ }
396
+ request(request) {
397
+ // snapshot facet labels (field + per-value) from the active facets display so the
398
+ // outgoing user message can render "Filter by Color Red" rather than raw keys
399
+ const filterLabels = {};
400
+ for (const facet of this.facets) {
401
+ const valueFacet = facet;
402
+ const values = {};
403
+ (valueFacet.values || []).forEach((v) => {
404
+ if (typeof v.low !== 'undefined' || typeof v.high !== 'undefined') {
405
+ values[`${v.low ?? '*'}:${v.high ?? '*'}`] = v.label;
406
+ }
407
+ else if (typeof v.value !== 'undefined') {
408
+ values[v.value] = v.label;
409
+ }
410
+ });
411
+ filterLabels[valueFacet.field] = { facetLabel: valueFacet.label || valueFacet.field, values };
412
+ }
413
+ this.currentChat?.request(request, filterLabels);
414
+ // remove any productSimilar attachments after request
415
+ const productSimilarAttachments = this.currentChat?.attachments.attached.filter((item) => item.type === 'product' && item.requestType === 'productSimilar') || [];
416
+ productSimilarAttachments.forEach((item) => {
417
+ this.currentChat?.attachments.remove(item.id);
418
+ });
419
+ }
420
+ update(data) {
421
+ // TODO: handle error
422
+ // if(err?.responseBody?.errorMessage || err?.responseBody?.errorCode) {
423
+ // const errorMessage = err?.responseBody?.errorMessage || 'An unknown error has occurred.';
424
+ // }
425
+ this.currentChat?.update(data);
426
+ if (!this.meta) {
427
+ this.storage.set('meta', JSON.stringify(data.meta));
428
+ }
429
+ this.meta = new MetaStore({
430
+ data: {
431
+ meta: data.meta,
432
+ },
433
+ });
434
+ // Keep raw meta in sync for lazy hydration of inactive sessions
435
+ this.storedMetaData = data.meta;
436
+ }
437
+ }
438
+ /** Deterministic JSON.stringify — sorts object keys recursively so equality comparisons
439
+ * aren't sensitive to insertion order. */
440
+ function stableStringify(value) {
441
+ if (value === null || value === undefined)
442
+ return 'null';
443
+ if (typeof value !== 'object')
444
+ return JSON.stringify(value);
445
+ if (Array.isArray(value)) {
446
+ return `[${value.map((v) => stableStringify(v)).join(',')}]`;
447
+ }
448
+ const keys = Object.keys(value).sort();
449
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(',')}}`;
450
+ }
451
+ /** Convert a chat-facet UI value into the URL-state shape — range buckets arrive as "low:high". */
452
+ function parseFacetValue(value) {
453
+ if (typeof value === 'string' && value.includes(':')) {
454
+ const [low, high] = value.split(':');
455
+ return {
456
+ low: low === '*' ? undefined : Number(low),
457
+ high: high === '*' ? undefined : Number(high),
458
+ };
459
+ }
460
+ return value;
461
+ }
462
+ function facetValueEquals(a, b) {
463
+ if (typeof a === 'object' && a !== null && typeof b === 'object' && b !== null) {
464
+ return a.low === b.low && a.high === b.high;
465
+ }
466
+ return a === b;
467
+ }
468
+ /** Build a fresh observable Product from an existing one. Variants are intentionally
469
+ * omitted — `updateProductQuickview` populates them from the products API response. */
470
+ function cloneProductForQuickview(product, meta) {
471
+ const result = {
472
+ id: product.id,
473
+ responseId: product.responseId,
474
+ mappings: JSON.parse(JSON.stringify(product.mappings || {})),
475
+ attributes: JSON.parse(JSON.stringify(product.attributes || {})),
476
+ badges: product.badges?.all?.map((b) => ({ tag: b.tag })) || [],
477
+ };
478
+ return new Product({
479
+ config: {},
480
+ data: { result, meta: meta || {} },
481
+ position: product.position ?? 0,
482
+ responseId: product.responseId,
483
+ });
484
+ }
@@ -0,0 +1,98 @@
1
+ type AttachmentState = 'loading' | 'error' | 'attached' | 'active' | 'saved';
2
+ type AttachmentError = {
3
+ message: string;
4
+ };
5
+ export type ChatAttachmentAddAttachment = ChatAttachmentImageConfig | ChatAttachmentProductConfig | ChatAttachmentFacetConfig;
6
+ export declare class ChatAttachmentStore {
7
+ items: ChatAttachments[];
8
+ constructor();
9
+ get attached(): ChatAttachments[];
10
+ get compared(): ChatAttachmentProduct[];
11
+ add<T extends ChatAttachments>(attachment: ChatAttachmentAddAttachment): T;
12
+ remove(id: string): void;
13
+ get(id: string): ChatAttachments | undefined;
14
+ reset(): void;
15
+ hydrate(attachments: ChatAttachmentAddAttachment[]): void;
16
+ }
17
+ type ChatAttachments = ChatAttachmentImage | ChatAttachmentProduct | ChatAttachmentFacet;
18
+ declare abstract class ChatAttachment {
19
+ abstract type: string;
20
+ id: string;
21
+ state: AttachmentState;
22
+ error?: AttachmentError;
23
+ constructor(params?: {
24
+ data?: {
25
+ id?: string;
26
+ state?: AttachmentState;
27
+ error?: AttachmentError;
28
+ };
29
+ });
30
+ save(): void;
31
+ activate(): void;
32
+ }
33
+ type ChatAttachmentImageConfig = {
34
+ type: 'image';
35
+ id?: string;
36
+ base64?: string;
37
+ fileName?: string;
38
+ imageId?: string;
39
+ imageUrl?: string;
40
+ thumbnailUrl?: string;
41
+ state?: AttachmentState;
42
+ error?: AttachmentError;
43
+ };
44
+ type ChatAttachmentProductConfig = {
45
+ type: 'product';
46
+ id?: string;
47
+ productId: string;
48
+ thumbnailUrl: string;
49
+ name: string;
50
+ requestType: 'productQuery' | 'productSimilar' | 'productComparison';
51
+ state?: AttachmentState;
52
+ error?: AttachmentError;
53
+ };
54
+ type ChatAttachmentFacetConfig = {
55
+ type: 'facet';
56
+ id?: string;
57
+ key: string;
58
+ facetLabel: string;
59
+ value: string;
60
+ label: string;
61
+ count: number;
62
+ state?: AttachmentState;
63
+ error?: AttachmentError;
64
+ };
65
+ export declare class ChatAttachmentProduct extends ChatAttachment {
66
+ type: 'product' | never;
67
+ productId: string;
68
+ thumbnailUrl: string;
69
+ name: string;
70
+ requestType: 'productQuery' | 'productSimilar' | 'productComparison';
71
+ constructor({ id, productId, thumbnailUrl, name, requestType, state, error }: ChatAttachmentProductConfig);
72
+ }
73
+ export declare class ChatAttachmentFacet extends ChatAttachment {
74
+ type: 'facet' | never;
75
+ key: string;
76
+ facetLabel: string;
77
+ value: string;
78
+ label: string;
79
+ count: number;
80
+ constructor({ id, key, facetLabel, value, label, count, state, error }: ChatAttachmentFacetConfig);
81
+ }
82
+ export declare class ChatAttachmentImage extends ChatAttachment {
83
+ type: 'image' | never;
84
+ fileName?: string;
85
+ imageId?: string;
86
+ imageUrl?: string;
87
+ thumbnailUrl?: string;
88
+ base64?: string;
89
+ constructor({ id, base64, fileName, imageId, imageUrl, thumbnailUrl, state, error }: ChatAttachmentImageConfig);
90
+ update: ({ imageId, imageUrl, thumbnailUrl, error, }: {
91
+ imageId?: string;
92
+ imageUrl?: string;
93
+ thumbnailUrl?: string;
94
+ error?: AttachmentError;
95
+ }) => Promise<void>;
96
+ }
97
+ export {};
98
+ //# sourceMappingURL=ChatAttachmentStore.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ChatAttachmentStore.d.ts","sourceRoot":"","sources":["../../../../src/Chat/Stores/ChatAttachmentStore.ts"],"names":[],"mappings":"AAMA,KAAK,eAAe,GAAG,SAAS,GAAG,OAAO,GAAG,UAAU,GAAG,QAAQ,GAAG,OAAO,CAAC;AAC7E,KAAK,eAAe,GAAG;IACtB,OAAO,EAAE,MAAM,CAAC;CAChB,CAAC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