@wix/himalaya-cli 0.1768.0 → 0.1769.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.
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/dev-server/src/app-config.d.ts +4 -0
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/dev-server/src/app-module.d.ts +7 -0
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/sdui.mjs +1 -0
- package/dist/cli.mjs +25 -6
- package/guides/himi-json-output.md +3 -3
- package/guides/qa-builds.md +73 -84
- package/package.json +2 -2
- package/templates/beauty-salon/tier5-src/_shared/business-chat-transport.ts +20 -4
- package/templates/beauty-salon/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/beauty-salon-owner/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/branded-lite/config.ts +2 -1
- package/templates/branded-lite/dev/index.ts +2 -1
- package/templates/branded-lite/l10n/ar.json +120 -0
- package/templates/branded-lite/l10n/cs.json +120 -0
- package/templates/branded-lite/l10n/da.json +120 -0
- package/templates/branded-lite/l10n/de.json +120 -0
- package/templates/branded-lite/l10n/el.json +120 -0
- package/templates/branded-lite/l10n/es.json +120 -0
- package/templates/branded-lite/l10n/fi.json +120 -0
- package/templates/branded-lite/l10n/fr.json +120 -0
- package/templates/branded-lite/l10n/he.json +96 -0
- package/templates/branded-lite/l10n/hu.json +120 -0
- package/templates/branded-lite/l10n/id.json +120 -0
- package/templates/branded-lite/l10n/it.json +120 -0
- package/templates/branded-lite/l10n/ja.json +120 -0
- package/templates/branded-lite/l10n/ko.json +120 -0
- package/templates/branded-lite/l10n/lt.json +120 -0
- package/templates/branded-lite/l10n/nl.json +120 -0
- package/templates/branded-lite/l10n/no.json +120 -0
- package/templates/branded-lite/l10n/pl.json +120 -0
- package/templates/branded-lite/l10n/pt.json +120 -0
- package/templates/branded-lite/l10n/ru.json +120 -0
- package/templates/branded-lite/l10n/sv.json +120 -0
- package/templates/branded-lite/l10n/th.json +120 -0
- package/templates/branded-lite/l10n/tr.json +120 -0
- package/templates/branded-lite/l10n/uk.json +120 -0
- package/templates/branded-lite/l10n/vi.json +120 -0
- package/templates/branded-lite/l10n/zh.json +120 -0
- package/templates/branded-lite/tier5-src/_shared/business-chat-transport.ts +20 -4
- package/templates/branded-lite/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/branded-lite/tier5-src/_shared/inbox-rooms.ts +101 -11
- package/templates/branded-lite/tier5-src/_shared/inbox-search.ts +119 -0
- package/templates/branded-lite/tier5-src/_shared/member-inbox-transport.ts +64 -0
- package/templates/branded-lite/tier5-src/_shared/member-thread-rows.ts +233 -0
- package/templates/branded-lite/tier5-src/business-chat/index.ts +73 -22
- package/templates/branded-lite/tier5-src/himi-branded-lite-inbox/index.ts +777 -54
- package/templates/branded-lite/tier5-src/wix-spaces-chat-thread/index.ts +426 -143
- package/templates/branded-lite/tier5-src/wix-spaces-new-message/index.ts +4 -2
- package/templates/brandy/tier5-src/_shared/business-chat-message-model.ts +177 -0
- package/templates/brandy/tier5-src/_shared/business-chat-transport.ts +164 -0
- package/templates/brandy/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/brandy/tier5-src/_shared/inbox-rooms.ts +101 -11
- package/templates/brandy/tier5-src/_shared/inbox-search.ts +119 -0
- package/templates/brandy/tier5-src/_shared/member-inbox-transport.ts +64 -0
- package/templates/brandy/tier5-src/_shared/member-thread-rows.ts +233 -0
- package/templates/brandy/tier5-src/himi-branded-lite-inbox/index.ts +777 -54
- package/templates/brandy/tier5-src/wix-spaces-chat-thread/index.ts +426 -143
- package/templates/community-club/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/community-club-owner/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/conference/tier5-src/_shared/business-chat-transport.ts +20 -4
- package/templates/conference/tier5-src/_shared/chat-live.ts +242 -0
- package/templates/conference/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/conference/tier5-src/_shared/inbox-rooms.ts +101 -11
- package/templates/conference/tier5-src/business-chat/index.ts +73 -22
- package/templates/events-meetups/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/events-meetups-owner/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/fitness-gym/tier5-src/_shared/business-chat-transport.ts +20 -4
- package/templates/fitness-gym/tier5-src/_shared/chat-live.ts +242 -0
- package/templates/fitness-gym/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/fitness-gym/tier5-src/_shared/inbox-rooms.ts +101 -11
- package/templates/fitness-gym/tier5-src/business-chat/index.ts +73 -22
- package/templates/gym-fitness/tier5-src/_shared/business-chat-transport.ts +20 -4
- package/templates/gym-fitness/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/gym-fitness-owner/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/medical-services/tier5-src/_shared/business-chat-transport.ts +20 -4
- package/templates/medical-services/tier5-src/_shared/chat-live.ts +242 -0
- package/templates/medical-services/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/medical-services/tier5-src/_shared/inbox-rooms.ts +101 -11
- package/templates/medical-services/tier5-src/business-chat/index.ts +73 -22
- package/templates/nonprofit-cause/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/nonprofit-cause-owner/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/owner-lite/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/personal-fitness-trainer/dev/index.ts +2 -1
- package/templates/personal-fitness-trainer/tier5-src/_shared/business-chat-transport.ts +20 -4
- package/templates/personal-fitness-trainer/tier5-src/_shared/chat-live.ts +242 -0
- package/templates/personal-fitness-trainer/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/personal-fitness-trainer/tier5-src/_shared/inbox-rooms.ts +101 -11
- package/templates/personal-fitness-trainer/tier5-src/business-chat/index.ts +73 -22
- package/templates/podcast-creator/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/podcast-creator-owner/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/portfolio-creative/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/portfolio-creative-owner/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/restaurant/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/restaurant-owner/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/retail-store/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/retail-store-owner/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/salon-spa/tier5-src/_shared/business-chat-transport.ts +20 -4
- package/templates/salon-spa/tier5-src/_shared/chat-live.ts +242 -0
- package/templates/salon-spa/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/salon-spa/tier5-src/_shared/inbox-rooms.ts +101 -11
- package/templates/salon-spa/tier5-src/business-chat/index.ts +73 -22
- package/templates/wholesale-store/tier5-src/_shared/business-chat-transport.ts +20 -4
- package/templates/wholesale-store/tier5-src/_shared/chat-live.ts +242 -0
- package/templates/wholesale-store/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/wholesale-store/tier5-src/_shared/inbox-rooms.ts +101 -11
- package/templates/wholesale-store/tier5-src/business-chat/index.ts +73 -22
- package/templates/yoga-studio/tier5-src/_shared/business-chat-transport.ts +20 -4
- package/templates/yoga-studio/tier5-src/_shared/engine-intl.ts +6 -0
- package/templates/yoga-studio-owner/tier5-src/_shared/engine-intl.ts +6 -0
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
// The rows of the member chat thread (wix-spaces-chat-thread): one row per chat-web message, oldest first, with a day
|
|
2
|
+
// label on the first message of each day.
|
|
3
|
+
//
|
|
4
|
+
// A row always carries the original fields the Spaces thread screen binds (text, when, mine, badge, avatar, one image,
|
|
5
|
+
// day label). Everything else is ADDITIVE, and the parts that read the message body more deeply (images, files, a card,
|
|
6
|
+
// the unsupported fallback, the outgoing queue) are filled only when the screen opted in with `richThread`; otherwise
|
|
7
|
+
// they hold neutral values (`hasX` false, `hideX` true), so a screen that does not ask for them sees the same rows as before.
|
|
8
|
+
//
|
|
9
|
+
// Every visual part has BOTH polarities: `hasX` is true when the part is there, `hideX` is the opposite, for a screen
|
|
10
|
+
// that hides on TRUE (`hiddenWhen`).
|
|
11
|
+
import type { ChatMessage } from "@himalaya/wix-chat-web";
|
|
12
|
+
import { formatClock, formatMonthDay, formatMonthDayTime } from "./engine-intl.js";
|
|
13
|
+
import { initials } from "./himi-text.js";
|
|
14
|
+
import { copyParam } from "./himi-copy.js";
|
|
15
|
+
import { normalizeMessages, type PartRow } from "./business-chat-message-model.js";
|
|
16
|
+
|
|
17
|
+
/** Where an outgoing message of this visit stands. "" is a message the server already holds. */
|
|
18
|
+
export type SendState = "" | "sending" | "sent" | "failed";
|
|
19
|
+
|
|
20
|
+
/** A message the member sent from this screen that the server has not listed yet (or could not take). `id` is the
|
|
21
|
+
* idempotency id the send carries, so a retry of the same entry is the same message to chat-web. */
|
|
22
|
+
export interface OutboxEntry { id: string; roomId: string; text: string; at: number; state: Exclude<SendState, ""> }
|
|
23
|
+
|
|
24
|
+
export interface ImageItem { id: string; url: string; description: string }
|
|
25
|
+
export interface AttachmentItem { id: string; kind: "file" | "audio" | "video"; url: string; label: string }
|
|
26
|
+
|
|
27
|
+
export interface Row {
|
|
28
|
+
id: string; text: string; when: string; leadFill: string; mine: boolean; notMine: boolean;
|
|
29
|
+
senderBadge: string; avatarUrl: string; avatarInitials: string;
|
|
30
|
+
/** An incoming member message with no sender photo: the screen draws the initials. Never for my own messages or the
|
|
31
|
+
* business (business, staff), which keep their own avatar. */
|
|
32
|
+
noPhoto: boolean;
|
|
33
|
+
imageUrl: string; imageDescription: string; imageHidden: boolean; dayLabel: string; dayHidden: boolean;
|
|
34
|
+
/** Avatar only on the last bubble of a run from the same sender (never on my own). */
|
|
35
|
+
showAvatar: boolean; hideAvatar: boolean;
|
|
36
|
+
/** Locale clock time ("" when the message has no time). */
|
|
37
|
+
time: string;
|
|
38
|
+
/** Outgoing rows only: "10:42 · Sent", "Sending…" or "Couldn't send". "" for incoming rows. */
|
|
39
|
+
statusText: string; hideStatus: boolean;
|
|
40
|
+
sendState: SendState; failed: boolean; notFailed: boolean;
|
|
41
|
+
hasText: boolean; hideText: boolean;
|
|
42
|
+
images: ImageItem[]; hasImages: boolean; hideImages: boolean;
|
|
43
|
+
/** Files, recordings and videos, as link rows; `attachmentUrl`/`Label`/`Kind` are the first one. */
|
|
44
|
+
attachments: AttachmentItem[]; attachmentUrl: string; attachmentLabel: string; attachmentKind: string;
|
|
45
|
+
hasAttachment: boolean; hideAttachment: boolean;
|
|
46
|
+
cardTitle: string; cardCaption: string; cardImageUrl: string; cardCtaLabel: string; cardCtaUrl: string;
|
|
47
|
+
hasCard: boolean; hideCard: boolean; hideCardTitle: boolean; hideCardCaption: boolean; hideCardImage: boolean; hideCardCta: boolean;
|
|
48
|
+
/** A message with nothing the thread can show: the fallback line instead of a blank bubble. */
|
|
49
|
+
unsupportedText: string; hasUnsupported: boolean; hideUnsupported: boolean;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface RowOptions {
|
|
53
|
+
/** The screen opted in to the richer rows (`richThread`). */
|
|
54
|
+
rich?: boolean;
|
|
55
|
+
/** Sends of this visit that the server may not list yet. */
|
|
56
|
+
outbox?: readonly OutboxEntry[];
|
|
57
|
+
/** Authorized download URLs of private attachments, by media id (see `privateMediaOf`). */
|
|
58
|
+
mediaUrls?: ReadonlyMap<string, string>;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const NO_VISUALS = {
|
|
62
|
+
hasText: true, hideText: false,
|
|
63
|
+
images: [] as ImageItem[], hasImages: false, hideImages: true,
|
|
64
|
+
attachments: [] as AttachmentItem[], attachmentUrl: "", attachmentLabel: "", attachmentKind: "", hasAttachment: false, hideAttachment: true,
|
|
65
|
+
cardTitle: "", cardCaption: "", cardImageUrl: "", cardCtaLabel: "", cardCtaUrl: "",
|
|
66
|
+
hasCard: false, hideCard: true, hideCardTitle: true, hideCardCaption: true, hideCardImage: true, hideCardCta: true,
|
|
67
|
+
unsupportedText: "", hasUnsupported: false, hideUnsupported: true,
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
export const PRIVATE_MEDIA = "WixMediaPrivate";
|
|
71
|
+
|
|
72
|
+
/** The private attachments of these messages: each needs an authorized download URL (never its raw link). */
|
|
73
|
+
export function privateMediaOf(messages: readonly unknown[]): PartRow[] {
|
|
74
|
+
const found: PartRow[] = [];
|
|
75
|
+
for (const row of normalizeMessages([...messages])) {
|
|
76
|
+
for (const part of row.parts) {
|
|
77
|
+
if ((part.kind === "image" || part.kind === "file" || part.kind === "audio" || part.kind === "video") && part.mediaProvider === PRIVATE_MEDIA && part.mediaId) found.push(part);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return found;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** chat-web marks the business side as "business", "businessUser" or "user" (the same predicate
|
|
84
|
+
* as wix-owner-inbox-thread); a visitor or member is anything else. */
|
|
85
|
+
function isBusinessSender(m: ChatMessage): boolean {
|
|
86
|
+
const type = String(m.sender?.type ?? "").toLowerCase();
|
|
87
|
+
return type === "business" || type === "businessuser" || type === "user";
|
|
88
|
+
}
|
|
89
|
+
export const dayKeyOf = (d: Date): string => `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;
|
|
90
|
+
|
|
91
|
+
/** What a message shows beyond its text, from the shared message model (the business chat reads the same parts). */
|
|
92
|
+
function visualsOf(m: ChatMessage, myUserId: string, mediaUrls: ReadonlyMap<string, string>, legacyText: string): typeof NO_VISUALS & { richText: string } {
|
|
93
|
+
const parts = normalizeMessages([m], myUserId)[0]?.parts ?? [];
|
|
94
|
+
// A private attachment is shown only through its authorized URL; a public one through its own https link.
|
|
95
|
+
const urlOf = (part: PartRow): string => (part.mediaProvider === PRIVATE_MEDIA ? (part.mediaId ? mediaUrls.get(part.mediaId) ?? "" : "") : part.url);
|
|
96
|
+
// A caption equal to the unavailable reason is the model's English diagnostic, not the sender's words.
|
|
97
|
+
const captionOf = (part: PartRow): string => (part.caption && part.caption !== part.unavailableReason ? part.caption : "");
|
|
98
|
+
const images: ImageItem[] = [];
|
|
99
|
+
const attachments: AttachmentItem[] = [];
|
|
100
|
+
for (const part of parts) {
|
|
101
|
+
if (part.kind === "image") {
|
|
102
|
+
const url = urlOf(part);
|
|
103
|
+
if (url) images.push({ id: part.id, url, description: captionOf(part) || copyParam("chatThread.imageDescription", "Photo in this conversation") });
|
|
104
|
+
} else if (part.kind === "file" || part.kind === "audio" || part.kind === "video") {
|
|
105
|
+
const url = urlOf(part);
|
|
106
|
+
if (url) attachments.push({ id: part.id, kind: part.kind, url, label: (part.fileName || captionOf(part) || copyParam("chatThread.openAttachment", "Open attachment")).slice(0, 40) });
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
const card = parts.find((part) => part.kind === "card");
|
|
110
|
+
const lines = (card?.text ?? "").split("\n");
|
|
111
|
+
const cardTitle = card ? (lines[0] ?? "").trim() : "";
|
|
112
|
+
const cardCaption = card ? lines.slice(1).join("\n").trim() : "";
|
|
113
|
+
const cardImageUrl = card?.url ?? "";
|
|
114
|
+
const cta = card?.buttons?.find((button) => button.url);
|
|
115
|
+
const hasCard = !!card && !!(cardTitle || cardCaption || cardImageUrl || cta);
|
|
116
|
+
const visual = images.length > 0 || attachments.length > 0 || hasCard;
|
|
117
|
+
const bodyText = parts.filter((part) => part.kind === "text" || part.kind === "system").map((part) => part.text).filter(Boolean).join("\n");
|
|
118
|
+
// The server's own preview line stands in only when nothing else says what the message is.
|
|
119
|
+
const richText = bodyText || (visual ? "" : legacyText);
|
|
120
|
+
const unsupported = !richText && !visual;
|
|
121
|
+
const first = attachments[0];
|
|
122
|
+
return {
|
|
123
|
+
richText,
|
|
124
|
+
hasText: richText !== "", hideText: richText === "",
|
|
125
|
+
images, hasImages: images.length > 0, hideImages: images.length === 0,
|
|
126
|
+
attachments, attachmentUrl: first?.url ?? "", attachmentLabel: first?.label ?? "", attachmentKind: first?.kind ?? "",
|
|
127
|
+
hasAttachment: !!first, hideAttachment: !first,
|
|
128
|
+
cardTitle: hasCard ? cardTitle : "", cardCaption: hasCard ? cardCaption : "", cardImageUrl: hasCard ? cardImageUrl : "",
|
|
129
|
+
cardCtaLabel: hasCard ? cta?.label ?? "" : "", cardCtaUrl: hasCard ? cta?.url ?? "" : "",
|
|
130
|
+
hasCard, hideCard: !hasCard, hideCardTitle: !(hasCard && cardTitle), hideCardCaption: !(hasCard && cardCaption),
|
|
131
|
+
hideCardImage: !(hasCard && cardImageUrl), hideCardCta: !(hasCard && cta),
|
|
132
|
+
unsupportedText: unsupported ? copyParam("chatThread.unsupportedText", "This message can't be shown here yet.") : "",
|
|
133
|
+
hasUnsupported: unsupported, hideUnsupported: !unsupported,
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** "10:42 · Sent", "Sending…" or "Couldn't send" for one of my messages. */
|
|
138
|
+
export function statusOf(state: SendState, time: string): string {
|
|
139
|
+
if (state === "sending") return copyParam("chatThread.statusSending", "Sending message…");
|
|
140
|
+
if (state === "failed") return copyParam("chatThread.statusFailed", "Couldn't send");
|
|
141
|
+
const sent = copyParam("chatThread.statusSent", "Sent");
|
|
142
|
+
return time ? `${time} · ${sent}` : sent;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
type Entry = Row & { timestamp: number; dayKey: string; senderKey: string };
|
|
146
|
+
|
|
147
|
+
function norm(m: ChatMessage, i: number, myUserId: string, options: RowOptions): Entry {
|
|
148
|
+
const mm = m as unknown as {
|
|
149
|
+
id?: string; summary?: string; data?: Array<{ mimeType?: string; data?: { text?: string; uri?: string; thumbnailUrl?: string } }>;
|
|
150
|
+
payload?: { text?: string }; content?: string; createdAt?: number; createdDate?: string;
|
|
151
|
+
senderDisplayData?: { name?: string; image?: { url?: string } };
|
|
152
|
+
};
|
|
153
|
+
const legacyText = mm.data?.find((part) => part.data?.text)?.data?.text || mm.summary || mm.payload?.text || mm.content || "";
|
|
154
|
+
const ms = mm.createdAt || (mm.createdDate ? Date.parse(mm.createdDate) : 0);
|
|
155
|
+
const date = ms ? new Date(ms) : null;
|
|
156
|
+
const senderName = mm.senderDisplayData?.name || "";
|
|
157
|
+
const avatarUrl = mm.senderDisplayData?.image?.url || "";
|
|
158
|
+
const image = mm.data?.find((part) => part.mimeType?.startsWith("image/") || part.data?.thumbnailUrl);
|
|
159
|
+
const rawImageUrl = image?.data?.thumbnailUrl || image?.data?.uri || "";
|
|
160
|
+
// Mine when the message sender matches my user id (resolved once per load).
|
|
161
|
+
const mine = !!(myUserId && m.sender?.userId && m.sender.userId === myUserId);
|
|
162
|
+
const rich = options.rich ? visualsOf(m, myUserId, options.mediaUrls ?? new Map(), legacyText) : undefined;
|
|
163
|
+
const { richText: _richText, ...visuals } = rich ?? { ...NO_VISUALS, richText: "" };
|
|
164
|
+
// The screen's one-image binding follows the authorized list when the screen opted in; a raw link of a private file never reaches it.
|
|
165
|
+
const imageUrl = rich ? rich.images[0]?.url ?? "" : rawImageUrl;
|
|
166
|
+
const time = date ? formatClock(date) : "";
|
|
167
|
+
return {
|
|
168
|
+
id: mm.id || `m${i}`, text: rich ? rich.richText : legacyText || "Message", when: date ? formatMonthDayTime(date) : "", leadFill: mine ? " " : "", mine, notMine: !mine,
|
|
169
|
+
senderBadge: isBusinessSender(m) ? copyParam("chatThread.businessBadge", "Business") : "",
|
|
170
|
+
avatarUrl, avatarInitials: initials(senderName), noPhoto: !mine && !isBusinessSender(m) && !avatarUrl,
|
|
171
|
+
imageUrl, imageDescription: imageUrl ? (rich ? rich.images[0]!.description : `${senderName || "Message"} attachment`) : "", imageHidden: !imageUrl, dayLabel: "", dayHidden: true,
|
|
172
|
+
showAvatar: false, hideAvatar: true, time,
|
|
173
|
+
statusText: mine ? statusOf("", time) : "", hideStatus: !mine,
|
|
174
|
+
sendState: "", failed: false, notFailed: true,
|
|
175
|
+
...visuals,
|
|
176
|
+
timestamp: ms, dayKey: date ? dayKeyOf(date) : "",
|
|
177
|
+
senderKey: mine ? "me" : m.sender?.userId || senderName || "other",
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** One of my own messages the server does not list (yet): sending, sent or failed. */
|
|
182
|
+
function queued(entry: OutboxEntry, newestStored: number): Entry {
|
|
183
|
+
const date = new Date(entry.at);
|
|
184
|
+
const time = formatClock(date);
|
|
185
|
+
const failed = entry.state === "failed";
|
|
186
|
+
return {
|
|
187
|
+
id: entry.id, text: entry.text, when: formatMonthDayTime(date), leadFill: " ", mine: true, notMine: false,
|
|
188
|
+
senderBadge: "", avatarUrl: "", avatarInitials: "", noPhoto: false, imageUrl: "", imageDescription: "", imageHidden: true, dayLabel: "", dayHidden: true,
|
|
189
|
+
showAvatar: false, hideAvatar: true, time: failed ? "" : time,
|
|
190
|
+
statusText: statusOf(entry.state, time), hideStatus: false,
|
|
191
|
+
sendState: entry.state, failed, notFailed: !failed,
|
|
192
|
+
...NO_VISUALS,
|
|
193
|
+
// After every message the server holds: the phone's clock and the server's differ, and a send is the newest by construction.
|
|
194
|
+
timestamp: Math.max(entry.at, newestStored), dayKey: dayKeyOf(date), senderKey: "me",
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** My own message shown after its send was accepted but its re-read failed: a row with no time (the original fallback). */
|
|
199
|
+
export function localSentRow(id: string, text: string): Row {
|
|
200
|
+
const { timestamp: _t, dayKey: _d, senderKey: _s, ...row } = { ...queued({ id, roomId: "", text, at: 0, state: "sent" }, 0) };
|
|
201
|
+
return { ...row, when: "", time: "", statusText: statusOf("", ""), dayLabel: "", dayHidden: true };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Oldest first, one row per message id, and a day label on the first message of each day. The outbox entries the
|
|
205
|
+
* server already lists are dropped (its row wins); the rest follow the messages they were sent after. */
|
|
206
|
+
export function rowsOf(messages: ChatMessage[], myUserId: string, options: RowOptions = {}): Row[] {
|
|
207
|
+
const stored = messages.map((m, i) => norm(m, i, myUserId, options));
|
|
208
|
+
const known = new Set(stored.map((row) => row.id));
|
|
209
|
+
const newestStored = stored.reduce((newest, row) => Math.max(newest, row.timestamp), 0);
|
|
210
|
+
const waiting = (options.outbox ?? []).filter((entry) => !known.has(entry.id)).map((entry) => queued(entry, newestStored));
|
|
211
|
+
const sorted = [...stored, ...waiting].sort((a, b) => a.timestamp - b.timestamp);
|
|
212
|
+
const today = new Date();
|
|
213
|
+
const todayKey = dayKeyOf(today);
|
|
214
|
+
const yesterdayKey = dayKeyOf(new Date(today.getFullYear(), today.getMonth(), today.getDate() - 1));
|
|
215
|
+
const seen = new Set<string>();
|
|
216
|
+
const entries: Array<Entry & { startsDay: boolean }> = [];
|
|
217
|
+
let previousDay = "";
|
|
218
|
+
for (const entry of sorted) {
|
|
219
|
+
if (seen.has(entry.id)) continue;
|
|
220
|
+
seen.add(entry.id);
|
|
221
|
+
const startsDay = !!entry.dayKey && entry.dayKey !== previousDay;
|
|
222
|
+
if (entry.dayKey) previousDay = entry.dayKey;
|
|
223
|
+
const dayLabel = !startsDay ? "" : entry.dayKey === todayKey ? copyParam("chatThread.today", "Today") : entry.dayKey === yesterdayKey ? copyParam("chatThread.yesterday", "Yesterday") : formatMonthDay(new Date(entry.timestamp));
|
|
224
|
+
entries.push({ ...entry, dayLabel, dayHidden: !dayLabel, startsDay });
|
|
225
|
+
}
|
|
226
|
+
return entries.map(({ timestamp: _t, dayKey: _d, senderKey, startsDay: _s, ...row }, at) => {
|
|
227
|
+
const next = entries[at + 1];
|
|
228
|
+
// The last bubble of a run: nothing follows, another sender follows, or the next message opens a new day.
|
|
229
|
+
const lastOfRun = !next || next.senderKey !== senderKey || next.startsDay;
|
|
230
|
+
const showAvatar = !row.mine && lastOfRun;
|
|
231
|
+
return { ...row, showAvatar, hideAvatar: !showAvatar };
|
|
232
|
+
});
|
|
233
|
+
}
|
|
@@ -10,6 +10,8 @@ import { businessInAppRoute, type BusinessArticleAction, dispatchBusinessSuggest
|
|
|
10
10
|
import { listMessages, streamMessages } from '@himalaya/wix-ai-site-chat';
|
|
11
11
|
import { smartChatHistory } from '../_shared/business-chat-history.js';
|
|
12
12
|
import { hostSiteFromInput } from '../_shared/branded-lite-hosted.js';
|
|
13
|
+
import { CHAT_LIVE_POLL_ID, livePollDirective } from '../_shared/chat-live.js';
|
|
14
|
+
import type { PollDirective, PollStopDirective } from '@himalaya/state';
|
|
13
15
|
import { productImage, searchStoreProducts } from '../_shared/himi-store.js';
|
|
14
16
|
import { queryServices } from '@himalaya/wix-bookings';
|
|
15
17
|
import { logBi, logChatSendError } from '../_shared/wix-bi.js';
|
|
@@ -26,8 +28,19 @@ type BusinessMessageRow = Pick<MessageRow,'id'|'sender'|'when'|'createdDate'|'mi
|
|
|
26
28
|
/** Confirmed local delivery, retained until the authoritative history returns it. */
|
|
27
29
|
acceptedIntent?:PendingIntent;
|
|
28
30
|
};
|
|
31
|
+
/** Integration contract for a screen that binds this worker (the design is the screen's; these fields are the data).
|
|
32
|
+
* Visitor chat is opt-in: the screen's init passes `visitorChat:"1"`, else a signed-out user is a guest.
|
|
33
|
+
* - phase: 'loading'|'ready'|'error'|'guest'. isGuest/notGuest: the sign-in prompt state (signed out, no visitor chat, or a lost session).
|
|
34
|
+
* - visitor/notVisitor: a signed-out visitor chatting with Smart Chat (no room, no realtime, re-read every 4 s). A visitor
|
|
35
|
+
* still has phase 'ready', so the composer shows; hide it only on isGuest. Signing in closes into a member chat on `load`.
|
|
36
|
+
* - sendEnabled/sendDisabled: the Send button state for the member and the visitor alike.
|
|
37
|
+
* - messages: the rows. quickReplies: the visitor options (hasQuickReplies/noQuickReplies).
|
|
38
|
+
* - liveLabel: the realtime status text; blank for a visitor, who has no realtime. */
|
|
29
39
|
type State = {
|
|
30
40
|
phase:'loading'|'ready'|'error'|'guest'; error:string; notice:string; member:boolean;
|
|
41
|
+
/** Signed out, chatting with Smart Chat as a site visitor: no member room, no realtime, a 4 s re-read instead. */
|
|
42
|
+
visitor:boolean; notVisitor:boolean;
|
|
43
|
+
_poll?:PollDirective|PollStopDirective;
|
|
31
44
|
roomId:string; principal:string; scope:string; messages:BusinessMessageRow[]; draft:string; busy:boolean;
|
|
32
45
|
historySource:'members'|'smart-chat'; historyRevision:number; smartChatEmpty:boolean;
|
|
33
46
|
/** Actual row namespace, independent of the transport followed after acceptance. */
|
|
@@ -54,9 +67,19 @@ function initialsOf(name:string):string{
|
|
|
54
67
|
const words=name.trim().split(/\s+/).filter(Boolean);
|
|
55
68
|
return (words.length>1?`${first(words[0]!)}${first(words[words.length-1]!)}`:first(words[0]??'')).toUpperCase();
|
|
56
69
|
}
|
|
57
|
-
const initial:State={hostedName,businessName:hostedName,businessInitials:initialsOf(hostedName),hasHostedName:!!hostedName,noHostedName:!hostedName,phase:'loading',error:'',notice:'',member:false,roomId:'',principal:'',scope:'',messages:[],draft:'',busy:false,historySource:'members',historyRevision:0,smartChatEmpty:false,transcriptSource:'members',
|
|
70
|
+
const initial:State={hostedName,businessName:hostedName,businessInitials:initialsOf(hostedName),hasHostedName:!!hostedName,noHostedName:!hostedName,phase:'loading',error:'',notice:'',member:false,visitor:false,notVisitor:true,roomId:'',principal:'',scope:'',messages:[],draft:'',busy:false,historySource:'members',historyRevision:0,smartChatEmpty:false,transcriptSource:'members',
|
|
58
71
|
liveState:'unavailable',liveReason:'',realtimeEventCount:0,lastRealtimeEventType:'',liveLabel:'',hasActiveRoom:false,noActiveRoom:true,isGuest:false,notGuest:true,realtimeDiagnostic:'',pendingIntent:null,scrollAnchor:'',scrollSend:0,usedSuggestionIds:[],visitorOptions:null,quickReplies:[],hasQuickReplies:false,noQuickReplies:true,noError:true,noNotice:true,noMessages:true,hasMessages:false,noEmpty:true,notLoading:false,sendDisabled:true,sendEnabled:false,noLive:true,loadingHidden:false,errorText:'',loadFailure:''};
|
|
59
72
|
let currentIdentity:ChatIdentity|null=null;
|
|
73
|
+
/** A visitor has no member principal: this one stands in, so a refresh started for the visitor is dropped once someone signs in. */
|
|
74
|
+
const VISITOR='visitor';
|
|
75
|
+
let visitorMode=false;
|
|
76
|
+
/** Visitor chat is opt-in: only a screen that passes `visitorChat:"1"` to init lets a signed-out visitor chat. Any other
|
|
77
|
+
* screen keeps the member-only chat, where signed out means the sign-in prompt. A retry passes no param: it keeps. */
|
|
78
|
+
let visitorChatOn=false;
|
|
79
|
+
/** Who the in-flight work belongs to: the member, the visitor, or no one. */
|
|
80
|
+
function currentPrincipal():string{return currentIdentity?(currentIdentity.userId||currentIdentity.email):visitorMode?VISITOR:'';}
|
|
81
|
+
/** A Smart Chat read or send, fenced for whoever is chatting now. */
|
|
82
|
+
function smartChatGuard<T>(run:()=>Promise<T>):Promise<T>{return visitorMode?chat.visitorFence(run):chat.fence(me(),run);}
|
|
60
83
|
let subscriptionId='';
|
|
61
84
|
let initFlight=false;
|
|
62
85
|
let suggestionFlight=false;
|
|
@@ -87,7 +110,7 @@ async function loadSmartChatMessages():Promise<unknown[]>{
|
|
|
87
110
|
const incomplete=()=>Object.assign(new Error('smart_chat_history_incomplete'),{code:'smart_chat_history_incomplete'});
|
|
88
111
|
for(let page=0;page<20;page++){
|
|
89
112
|
let response:Awaited<ReturnType<typeof listMessages>>;
|
|
90
|
-
try{response=await
|
|
113
|
+
try{response=await smartChatGuard(()=>listMessages({cursorPaging:{limit:100,...(cursor?{cursor}:{})}}));}
|
|
91
114
|
catch(error){
|
|
92
115
|
if(/member_sign_in_required|MemberAccessChanged|\b401\b/i.test(String(error))||(page>0&&/\b403\b/.test(String(error))))throw Object.assign(new Error('member_sign_in_required'),{code:'smart_chat_history_incomplete'});
|
|
93
116
|
// Only an explicit unavailable feature permits the legacy fallback. A timeout or
|
|
@@ -110,7 +133,7 @@ async function loadSmartChatMessages():Promise<unknown[]>{
|
|
|
110
133
|
async function sendBusinessVisitorOption(options:BusinessVisitorOptions|null|undefined,label:string):Promise<boolean>{
|
|
111
134
|
const request=businessVisitorOptionRequest(options,label,newBusinessSelectionId());
|
|
112
135
|
if(!request)return false;
|
|
113
|
-
await
|
|
136
|
+
await smartChatGuard(()=>streamMessages(request));
|
|
114
137
|
return true;
|
|
115
138
|
}
|
|
116
139
|
function liveDescription(state:string,reason:string):string{return businessRealtimeStatusLabel(state,reason);}
|
|
@@ -141,11 +164,11 @@ function selectedOptionVisible(aiMessages:unknown[],messages:BusinessMessageRow[
|
|
|
141
164
|
messages.some(row=>row.id===`smart-chat:${message.id}`&&row.mine&&row.bodyText.trim()===intent.text.trim());
|
|
142
165
|
});
|
|
143
166
|
}
|
|
144
|
-
function shape(s:State):State{const used=new Set(s.usedSuggestionIds);const messages=s.messages.map(row=>({...row,noSuggestions:s.phase!=='ready'||!(row.suggestions||[]).length,suggestions:(row.suggestions||[]).map(button=>used.has(button.id)?{...button,enabled:false,disabled:true}:button)}));const quickReplies=(s.quickReplies||[]).map(button=>used.has(button.id)?{...button,enabled:false,disabled:true}:button);const quickEnabled=s.phase==='ready'&&quickReplies.some(button=>button.enabled);return {...s,messages,quickReplies,hasQuickReplies:quickEnabled,noQuickReplies:!quickEnabled,scrollAnchor:messages[messages.length-1]?.scrollAnchor||'',liveLabel:liveDescription(s.liveState,s.liveReason),hasActiveRoom:!!s.roomId,noActiveRoom:!s.roomId,hasHostedName:!!s.hostedName,noHostedName:!s.hostedName,isGuest:s.phase==='guest',notGuest:s.phase!=='guest',realtimeDiagnostic:`state=${s.liveState}; reason=${s.liveReason||'none'}; events=${s.realtimeEventCount}; lastType=${/^(message|messagesent)$/i.test(s.lastRealtimeEventType)?s.lastRealtimeEventType:'none'}`,errorText:s.error,loadingHidden:s.phase!=='loading'||!!s.error,noError:!s.error,noNotice:!s.notice,noMessages:!messages.length,hasMessages:!!messages.length,noEmpty:s.phase!=='ready'||!!messages.length,
|
|
167
|
+
function shape(s:State):State{const used=new Set(s.usedSuggestionIds);const messages=s.messages.map(row=>({...row,noSuggestions:s.phase!=='ready'||!(row.suggestions||[]).length,suggestions:(row.suggestions||[]).map(button=>used.has(button.id)?{...button,enabled:false,disabled:true}:button)}));const quickReplies=(s.quickReplies||[]).map(button=>used.has(button.id)?{...button,enabled:false,disabled:true}:button);const quickEnabled=s.phase==='ready'&&quickReplies.some(button=>button.enabled);return {...s,messages,quickReplies,hasQuickReplies:quickEnabled,noQuickReplies:!quickEnabled,scrollAnchor:messages[messages.length-1]?.scrollAnchor||'',liveLabel:s.visitor?'':liveDescription(s.liveState,s.liveReason),hasActiveRoom:!!s.roomId,noActiveRoom:!s.roomId,hasHostedName:!!s.hostedName,noHostedName:!s.hostedName,isGuest:s.phase==='guest',notVisitor:!s.visitor,notGuest:s.phase!=='guest',realtimeDiagnostic:`state=${s.liveState}; reason=${s.liveReason||'none'}; events=${s.realtimeEventCount}; lastType=${/^(message|messagesent)$/i.test(s.lastRealtimeEventType)?s.lastRealtimeEventType:'none'}`,errorText:s.error,loadingHidden:s.phase!=='loading'||!!s.error,noError:!s.error,noNotice:!s.notice,noMessages:!messages.length,hasMessages:!!messages.length,noEmpty:s.phase!=='ready'||!!messages.length,
|
|
145
168
|
notLoading:s.phase!=='loading',sendDisabled:!canSend(s,s.draft),sendEnabled:canSend(s,s.draft),noLive:!s.roomId||s.liveState==='connected'};}
|
|
146
169
|
/** Smart Chat resolves the conversation from the member identity, including the first message.
|
|
147
170
|
* History must finish loading before Send is offered so delivery has a reliable anchor. */
|
|
148
|
-
function canSend(s:State,draft:string):boolean{return !!s.member&&s.phase==='ready'&&!s.busy&&!!draft.trim()&&!s.pendingIntent;}
|
|
171
|
+
function canSend(s:State,draft:string):boolean{return (!!s.member||!!s.visitor)&&s.phase==='ready'&&!s.busy&&!!draft.trim()&&!s.pendingIntent;}
|
|
149
172
|
function safeLoadFailure(error:unknown):string{
|
|
150
173
|
const name=error instanceof Error?error.name:'UnknownError';
|
|
151
174
|
const code=(error as {code?:unknown}|null)?.code;
|
|
@@ -249,12 +272,14 @@ function slimRow(row:Record<string,unknown>):BusinessMessageRow{
|
|
|
249
272
|
return pick('id','sender','when','createdDate','mine','senderAvatar','senderName','senderInitials','senderBadge','imageUrl','imageDescription','noImage','bodyText','bodyMarkdown','suggestions','articleActions','couponCode','noCoupon','notMine','isCard','notCard','noSuggestions','noActions','cardTitle','cardDetail','noCardText','dayLabel','dayHidden','startsDay','scrollAnchor') as unknown as BusinessMessageRow;
|
|
250
273
|
}
|
|
251
274
|
async function presentMessages(existing:MessageRow[],raw:unknown[],memberId?:string,participantId=businessParticipantId||'smart-chat:visitor'):Promise<BusinessMessageRow[]>{
|
|
252
|
-
|
|
275
|
+
// A private attachment's download URL is member-only: a visitor's row keeps the part without one.
|
|
276
|
+
const identity=visitorMode?null:me();const presentationEpoch=epoch;
|
|
253
277
|
const rows=chronologicalMessages(existing,raw,memberId) as MessageRow[];
|
|
254
278
|
const prepared=await Promise.all(rows.map(async row=>{
|
|
255
279
|
const parts=await Promise.all(row.parts.map(async part=>{
|
|
256
280
|
if(part.kind!=='image'&&part.kind!=='file'&&part.kind!=='audio'&&part.kind!=='video')return part;
|
|
257
281
|
if(part.mediaProvider==='WixMediaPrivate'&&part.mediaId){
|
|
282
|
+
if(!identity)return {...part,url:''};
|
|
258
283
|
try{return {...part,url:await privateAttachmentUrl(part,identity,presentationEpoch)};}catch{return {...part,url:''};}
|
|
259
284
|
}
|
|
260
285
|
return part;
|
|
@@ -296,8 +321,9 @@ function safeError(error:unknown,operation:'load'|'send'|'init'):string{
|
|
|
296
321
|
}
|
|
297
322
|
async function endSubscription():Promise<void>{const id=subscriptionId;subscriptionId='';if(id)try{await unsubscribeRealtime({subscriptionId:id});}catch{}}
|
|
298
323
|
function clearPrivate(s:State,phase:'guest'|'error'='guest'):State{
|
|
324
|
+
const wasVisitor=visitorMode;visitorMode=false;
|
|
299
325
|
attachmentUrls.clear();seenSelections.clear();productImages.clear();productImageLookups.clear();serviceIds.clear();serviceIdLookups.clear();currentIdentity=null;businessParticipantId='';epoch++;void endSubscription();
|
|
300
|
-
return shape({...initial,phase,error:phase==='guest'?businessChatCopy('signInPrompt'):s.error});
|
|
326
|
+
return shape({...initial,phase,error:phase==='guest'?businessChatCopy('signInPrompt'):s.error,...(wasVisitor?{_poll:{id:CHAT_LIVE_POLL_ID,stop:true as const}}:{})});
|
|
301
327
|
}
|
|
302
328
|
let refreshTail:Promise<unknown>=Promise.resolve();
|
|
303
329
|
/** One refresh runs at a time. A caller that needs the data (init, a send) waits for the one in flight and
|
|
@@ -314,7 +340,7 @@ async function loadHistory(s:State,wait=false):Promise<State|undefined>{
|
|
|
314
340
|
async function refreshHistory(s:State):Promise<State|undefined>{
|
|
315
341
|
refreshFlight=true;const startEpoch=epoch;const roomId=s.roomId;const principal=s.principal;const participantId=businessParticipantId||'smart-chat:visitor';const startDraftRevision=draftRevision;
|
|
316
342
|
// A refresh that outlived its member or session says nothing: returning a state would overwrite the new one.
|
|
317
|
-
const stale=()=>startEpoch!==epoch||(
|
|
343
|
+
const stale=()=>startEpoch!==epoch||currentPrincipal()!==principal;
|
|
318
344
|
try{
|
|
319
345
|
loadStage='history_request';
|
|
320
346
|
// The Members room and Smart Chat may be different conversations. Read Smart Chat's
|
|
@@ -416,12 +442,12 @@ type SendResult={id:string;outcome:'sent'|'rejected'|'unconfirmed'|'signed_out';
|
|
|
416
442
|
/** Posts one message and reports how it ended; never throws. The caller already showed the message. The call lasts
|
|
417
443
|
* until the AI has answered: history usually shows the stored copy first, which replaces the placeholder, while Send
|
|
418
444
|
* stays held until this settles (the site's widget also waits for the answer). */
|
|
419
|
-
async function deliver(pending:BusinessChatIntent,draft:string):Promise<void>{
|
|
445
|
+
async function deliver(pending:BusinessChatIntent,draft:string,visitor=false):Promise<void>{
|
|
420
446
|
const sendEpoch=epoch;
|
|
421
447
|
let result:SendResult={id:pending.id,outcome:'sent',draft};
|
|
422
448
|
try{
|
|
423
449
|
await Promise.resolve();// the action that started this has returned its state by now
|
|
424
|
-
result.storedId=await chat.sendMessage(me(),pending.text);
|
|
450
|
+
result.storedId=await (visitor?chat.sendVisitorMessage(pending.text):chat.sendMessage(me(),pending.text));
|
|
425
451
|
}catch(error){
|
|
426
452
|
const lost=/member_sign_in_required|MemberAccessChanged|\b401\b|\b403\b/i.test(String(error));
|
|
427
453
|
result={id:pending.id,draft,error,outcome:lost?'signed_out':businessChatSendRejected(error)?'rejected':'unconfirmed'};
|
|
@@ -465,7 +491,8 @@ const svc=defineService<State,Record<string,(s:State,a?:unknown)=>State|undefine
|
|
|
465
491
|
// A host runs `load` when the screen shows again, also when a sign-in modal over it closes.
|
|
466
492
|
// Only a guest loads again: a member's chat is already live. No args: init keeps the site
|
|
467
493
|
// and name the screen gave first.
|
|
468
|
-
|
|
494
|
+
// A visitor loads again too: the sign-in modal over the chat closing is how a visitor becomes a member.
|
|
495
|
+
load:async (s):Promise<State|undefined>=>s.phase==='guest'||s.visitor?svc.init():undefined,
|
|
469
496
|
init:async(s,a)=>{
|
|
470
497
|
// Keep $t: keys as values: renderers translate bound worker copy in the active locale.
|
|
471
498
|
const copy=Object.fromEntries(Object.keys(BUSINESS_CHAT_COPY).map(key=>[`businessChat.${key}`,param(a,`businessChat.${key}`)]).filter(([,text])=>!!text));
|
|
@@ -473,6 +500,7 @@ const svc=defineService<State,Record<string,(s:State,a?:unknown)=>State|undefine
|
|
|
473
500
|
if(initFlight)return s;initFlight=true;eventDuringInit=false;statusDuringInit=null;
|
|
474
501
|
// A retry passes no site: the one the screen gave first stays. A site the screen passes, even an empty one (a
|
|
475
502
|
// business with no site), replaces it, so an earlier business's links are not routed to this one's screens.
|
|
503
|
+
if(hasParam(a,'visitorChat'))visitorChatOn=param(a,'visitorChat')==='1';
|
|
476
504
|
if(hasParam(a,'siteUrl')){ownSiteUrl=param(a,'siteUrl');ownScreens.product=param(a,'productScreen');ownScreens.service=param(a,'serviceScreen');}
|
|
477
505
|
// A retry passes no name: the one the screen gave first stays. Under `displayName`, a copy key, so a template
|
|
478
506
|
// sweep that renames the business renames it here too and the initials follow.
|
|
@@ -518,10 +546,21 @@ const svc=defineService<State,Record<string,(s:State,a?:unknown)=>State|undefine
|
|
|
518
546
|
loadStage='room_selection';
|
|
519
547
|
const identity=await getCurrentMember();
|
|
520
548
|
if(myEpoch!==epoch)return undefined;
|
|
521
|
-
if(!identity.authenticated)
|
|
549
|
+
if(!identity.authenticated){
|
|
550
|
+
if(!visitorChatOn)throw new Error('member_sign_in_required');
|
|
551
|
+
// Signed out: chat with Smart Chat as a site visitor, as on the website. No member room and no realtime
|
|
552
|
+
// (both are member-only), so the transcript is re-read every 4 s while the screen is open.
|
|
553
|
+
if(oldPrincipal&&oldPrincipal!==VISITOR){s=signed(clearPrivate(s,'guest'));myEpoch=epoch;reset=true;}
|
|
554
|
+
currentIdentity=null;visitorMode=true;businessParticipantId='';
|
|
555
|
+
s=shape({...s,phase:'loading',member:false,visitor:true,principal:VISITOR,scope:'',roomId:'',error:'',notice:''});
|
|
556
|
+
const loaded=await loadLatest(s,true);
|
|
557
|
+
if(!loaded||myEpoch!==epoch)return undefined;
|
|
558
|
+
return shape({...keepTyped(loaded),_poll:livePollDirective('businessChat.refresh')});
|
|
559
|
+
}
|
|
522
560
|
if(oldPrincipal&&(oldPrincipal!==(identity.userId||identity.email)||s.scope!==identity.scope)){s=signed(clearPrivate(s,'guest'));myEpoch=epoch;reset=true;}
|
|
523
561
|
currentIdentity=identity;
|
|
524
|
-
|
|
562
|
+
visitorMode=false;
|
|
563
|
+
s=shape({...s,phase:'loading',member:true,visitor:false,principal:identity.userId||identity.email,scope:identity.scope,error:'',notice:''});
|
|
525
564
|
const existingRoom=await resolveExistingBusinessRoom(myEpoch,signedBy);
|
|
526
565
|
if(myEpoch!==epoch)return undefined;
|
|
527
566
|
const live=readServiceState();
|
|
@@ -563,8 +602,9 @@ const svc=defineService<State,Record<string,(s:State,a?:unknown)=>State|undefine
|
|
|
563
602
|
// business (biLogger.service.ts:226-258, origin 'native' from biLogger.utils.ts). RN has no contact id here either.
|
|
564
603
|
// It is logged on the Send tap, before the network call, on purpose: RN calls engageSendMessageClick synchronously
|
|
565
604
|
// before sendMessageService.sendMessage, so a send the server then refuses has logged 510 and also logs 1604 (deliver).
|
|
566
|
-
|
|
567
|
-
|
|
605
|
+
// A signed-out visitor is not a member: the member-to-business event is not theirs to log.
|
|
606
|
+
if(!s.visitor)logBi({evid:510,src:5,endpoint:'',params:{origin:'native',is_member:true,chatRoomType:'member to business',activity_type:'',appName:'',expand_mode:false,textLength:text.length,is_demo:false}});
|
|
607
|
+
void deliver(pending,s.draft,!!s.visitor);
|
|
568
608
|
return shape({...s,draft:'',pendingIntent:pending,messages:[...s.messages,pendingRow(pending)],error:'',notice:'',scrollSend:s.scrollSend+1});
|
|
569
609
|
},
|
|
570
610
|
settleSend:async(s,a)=>{
|
|
@@ -625,8 +665,9 @@ const svc=defineService<State,Record<string,(s:State,a?:unknown)=>State|undefine
|
|
|
625
665
|
if(!loaded)return undefined;
|
|
626
666
|
resolved=loaded;
|
|
627
667
|
resolved=latestResolved();
|
|
628
|
-
// Creating a conversation is a consequence of the accepted send, never of opening chat.
|
|
629
|
-
|
|
668
|
+
// Creating a conversation is a consequence of the accepted send, never of opening chat. A visitor has no
|
|
669
|
+
// Members room to find: Smart Chat is their whole conversation.
|
|
670
|
+
if(!resolved.roomId&&!resolved.visitor){
|
|
630
671
|
const room=await resolveExistingBusinessRoom(sendEpoch,s.businessName);
|
|
631
672
|
if(sendEpoch!==epoch)return undefined;
|
|
632
673
|
const latest=latestResolved();
|
|
@@ -658,16 +699,16 @@ const svc=defineService<State,Record<string,(s:State,a?:unknown)=>State|undefine
|
|
|
658
699
|
}catch{return shape({...withLiveDraft(accepted),notice:businessChatCopy('suggestionSent')});}
|
|
659
700
|
},
|
|
660
701
|
sendSuggestion:(s,a)=>{
|
|
661
|
-
if(suggestionFlight
|
|
702
|
+
if(suggestionFlight||(!s.member&&!s.visitor)||s.phase!=='ready'||!!s.pendingIntent)return s;
|
|
662
703
|
const id=param(a,'id');
|
|
663
704
|
if(!id||s.usedSuggestionIds.includes(id))return s;
|
|
664
705
|
const rows=[{suggestions:s.quickReplies} as {suggestions?:BusinessSuggestion[]},...s.messages];
|
|
665
706
|
const suggestion=findBusinessSuggestion(rows,id);
|
|
666
707
|
// A first conversation has no room yet: only an AI option can start it.
|
|
667
708
|
if(!suggestion||!s.roomId&&suggestion.kind!=='visitor_option')return s;
|
|
668
|
-
const currentPrincipal
|
|
669
|
-
if(!s.principal||s.principal!==
|
|
670
|
-
const session:SuggestionSession={member:s.member,roomId:s.roomId,principal:s.principal,currentPrincipal,scope:s.scope,currentScope:currentIdentity?.scope||''};
|
|
709
|
+
const principalNow=currentPrincipal();
|
|
710
|
+
if(!s.principal||s.principal!==principalNow||s.scope!==(currentIdentity?.scope??''))return s;
|
|
711
|
+
const session:SuggestionSession={member:s.member||s.visitor,roomId:s.roomId,principal:s.principal,currentPrincipal:principalNow,scope:s.scope,currentScope:currentIdentity?.scope||''};
|
|
671
712
|
suggestionFlight=true;
|
|
672
713
|
if(suggestion.kind!=='visitor_option'){
|
|
673
714
|
void deliverButtonSuggestion(id,rows,session).finally(()=>{suggestionFlight=false;});
|
|
@@ -712,7 +753,17 @@ const svc=defineService<State,Record<string,(s:State,a?:unknown)=>State|undefine
|
|
|
712
753
|
}
|
|
713
754
|
catch(error){if(startEpoch!==epoch)return undefined;const lost=/member_sign_in_required|MemberAccessChanged|\b401\b|\b403\b/i.test(String(error));return lost?clearPrivate(next,'guest'):shape({...withLiveDraft(next),error:safeError(error,'load'),loadFailure:typeof (error as {businessLoadFailure?:unknown})?.businessLoadFailure==='string'?(error as {businessLoadFailure:string}).businessLoadFailure:safeLoadFailure(error)});}
|
|
714
755
|
},
|
|
715
|
-
|
|
756
|
+
// The visitor's 4 s re-read. A member is live through realtime and never polls; a tick that finds someone
|
|
757
|
+
// signed in meanwhile hands over to init, which moves the chat to the member.
|
|
758
|
+
refresh:async (s):Promise<State|undefined>=>{
|
|
759
|
+
if(!s.visitor||s.phase!=='ready')return undefined;
|
|
760
|
+
const startEpoch=epoch;
|
|
761
|
+
try{return await loadLatest(s);}catch(error){
|
|
762
|
+
if(startEpoch!==epoch)return undefined;
|
|
763
|
+
return /member_sign_in_required|MemberAccessChanged/i.test(String(error))?svc.init():undefined;
|
|
764
|
+
}
|
|
765
|
+
},
|
|
766
|
+
dispose:async s=>{epoch++;visitorMode=false;attachmentUrls.clear();seenSelections.clear();productImages.clear();productImageLookups.clear();serviceIds.clear();serviceIdLookups.clear();currentIdentity=null;businessParticipantId='';await endSubscription();return shape({...initial,phase:'guest'});},
|
|
716
767
|
}
|
|
717
768
|
});
|
|
718
769
|
readServiceState=()=>svc.getState();
|