@wix/himalaya-cli 0.1768.0 → 0.1770.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/dev-server/src/app-config.d.ts +4 -0
  2. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/dev-server/src/app-module.d.ts +7 -0
  3. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/sdui.mjs +1 -0
  4. package/dist/cli.mjs +311 -56
  5. package/guides/himi-json-output.md +3 -3
  6. package/guides/qa-builds.md +73 -84
  7. package/package.json +2 -2
  8. package/templates/beauty-salon/tier5-src/_shared/business-chat-transport.ts +20 -4
  9. package/templates/beauty-salon/tier5-src/_shared/engine-intl.ts +6 -0
  10. package/templates/beauty-salon-owner/tier5-src/_shared/engine-intl.ts +6 -0
  11. package/templates/branded-lite/config.ts +2 -1
  12. package/templates/branded-lite/dev/index.ts +2 -1
  13. package/templates/branded-lite/l10n/ar.json +120 -0
  14. package/templates/branded-lite/l10n/cs.json +120 -0
  15. package/templates/branded-lite/l10n/da.json +120 -0
  16. package/templates/branded-lite/l10n/de.json +120 -0
  17. package/templates/branded-lite/l10n/el.json +120 -0
  18. package/templates/branded-lite/l10n/es.json +120 -0
  19. package/templates/branded-lite/l10n/fi.json +120 -0
  20. package/templates/branded-lite/l10n/fr.json +120 -0
  21. package/templates/branded-lite/l10n/he.json +96 -0
  22. package/templates/branded-lite/l10n/hu.json +120 -0
  23. package/templates/branded-lite/l10n/id.json +120 -0
  24. package/templates/branded-lite/l10n/it.json +120 -0
  25. package/templates/branded-lite/l10n/ja.json +120 -0
  26. package/templates/branded-lite/l10n/ko.json +120 -0
  27. package/templates/branded-lite/l10n/lt.json +120 -0
  28. package/templates/branded-lite/l10n/nl.json +120 -0
  29. package/templates/branded-lite/l10n/no.json +120 -0
  30. package/templates/branded-lite/l10n/pl.json +120 -0
  31. package/templates/branded-lite/l10n/pt.json +120 -0
  32. package/templates/branded-lite/l10n/ru.json +120 -0
  33. package/templates/branded-lite/l10n/sv.json +120 -0
  34. package/templates/branded-lite/l10n/th.json +120 -0
  35. package/templates/branded-lite/l10n/tr.json +120 -0
  36. package/templates/branded-lite/l10n/uk.json +120 -0
  37. package/templates/branded-lite/l10n/vi.json +120 -0
  38. package/templates/branded-lite/l10n/zh.json +120 -0
  39. package/templates/branded-lite/tier5-src/_shared/business-chat-transport.ts +20 -4
  40. package/templates/branded-lite/tier5-src/_shared/engine-intl.ts +6 -0
  41. package/templates/branded-lite/tier5-src/_shared/inbox-rooms.ts +101 -11
  42. package/templates/branded-lite/tier5-src/_shared/inbox-search.ts +119 -0
  43. package/templates/branded-lite/tier5-src/_shared/member-inbox-transport.ts +64 -0
  44. package/templates/branded-lite/tier5-src/_shared/member-thread-rows.ts +233 -0
  45. package/templates/branded-lite/tier5-src/business-chat/index.ts +73 -22
  46. package/templates/branded-lite/tier5-src/himi-branded-lite-inbox/index.ts +777 -54
  47. package/templates/branded-lite/tier5-src/wix-spaces-chat-thread/index.ts +426 -143
  48. package/templates/branded-lite/tier5-src/wix-spaces-new-message/index.ts +4 -2
  49. package/templates/brandy/tier5-src/_shared/business-chat-message-model.ts +177 -0
  50. package/templates/brandy/tier5-src/_shared/business-chat-transport.ts +164 -0
  51. package/templates/brandy/tier5-src/_shared/engine-intl.ts +6 -0
  52. package/templates/brandy/tier5-src/_shared/inbox-rooms.ts +101 -11
  53. package/templates/brandy/tier5-src/_shared/inbox-search.ts +119 -0
  54. package/templates/brandy/tier5-src/_shared/member-inbox-transport.ts +64 -0
  55. package/templates/brandy/tier5-src/_shared/member-thread-rows.ts +233 -0
  56. package/templates/brandy/tier5-src/himi-branded-lite-inbox/index.ts +777 -54
  57. package/templates/brandy/tier5-src/wix-spaces-chat-thread/index.ts +426 -143
  58. package/templates/community-club/tier5-src/_shared/engine-intl.ts +6 -0
  59. package/templates/community-club-owner/tier5-src/_shared/engine-intl.ts +6 -0
  60. package/templates/conference/tier5-src/_shared/business-chat-transport.ts +20 -4
  61. package/templates/conference/tier5-src/_shared/chat-live.ts +242 -0
  62. package/templates/conference/tier5-src/_shared/engine-intl.ts +6 -0
  63. package/templates/conference/tier5-src/_shared/inbox-rooms.ts +101 -11
  64. package/templates/conference/tier5-src/business-chat/index.ts +73 -22
  65. package/templates/events-meetups/tier5-src/_shared/engine-intl.ts +6 -0
  66. package/templates/events-meetups-owner/tier5-src/_shared/engine-intl.ts +6 -0
  67. package/templates/fitness-gym/tier5-src/_shared/business-chat-transport.ts +20 -4
  68. package/templates/fitness-gym/tier5-src/_shared/chat-live.ts +242 -0
  69. package/templates/fitness-gym/tier5-src/_shared/engine-intl.ts +6 -0
  70. package/templates/fitness-gym/tier5-src/_shared/inbox-rooms.ts +101 -11
  71. package/templates/fitness-gym/tier5-src/business-chat/index.ts +73 -22
  72. package/templates/gym-fitness/tier5-src/_shared/business-chat-transport.ts +20 -4
  73. package/templates/gym-fitness/tier5-src/_shared/engine-intl.ts +6 -0
  74. package/templates/gym-fitness-owner/tier5-src/_shared/engine-intl.ts +6 -0
  75. package/templates/medical-services/tier5-src/_shared/business-chat-transport.ts +20 -4
  76. package/templates/medical-services/tier5-src/_shared/chat-live.ts +242 -0
  77. package/templates/medical-services/tier5-src/_shared/engine-intl.ts +6 -0
  78. package/templates/medical-services/tier5-src/_shared/inbox-rooms.ts +101 -11
  79. package/templates/medical-services/tier5-src/business-chat/index.ts +73 -22
  80. package/templates/nonprofit-cause/tier5-src/_shared/engine-intl.ts +6 -0
  81. package/templates/nonprofit-cause-owner/tier5-src/_shared/engine-intl.ts +6 -0
  82. package/templates/owner-lite/tier5-src/_shared/engine-intl.ts +6 -0
  83. package/templates/personal-fitness-trainer/dev/index.ts +2 -1
  84. package/templates/personal-fitness-trainer/tier5-src/_shared/business-chat-transport.ts +20 -4
  85. package/templates/personal-fitness-trainer/tier5-src/_shared/chat-live.ts +242 -0
  86. package/templates/personal-fitness-trainer/tier5-src/_shared/engine-intl.ts +6 -0
  87. package/templates/personal-fitness-trainer/tier5-src/_shared/inbox-rooms.ts +101 -11
  88. package/templates/personal-fitness-trainer/tier5-src/business-chat/index.ts +73 -22
  89. package/templates/podcast-creator/tier5-src/_shared/engine-intl.ts +6 -0
  90. package/templates/podcast-creator-owner/tier5-src/_shared/engine-intl.ts +6 -0
  91. package/templates/portfolio-creative/tier5-src/_shared/engine-intl.ts +6 -0
  92. package/templates/portfolio-creative-owner/tier5-src/_shared/engine-intl.ts +6 -0
  93. package/templates/restaurant/tier5-src/_shared/engine-intl.ts +6 -0
  94. package/templates/restaurant-owner/tier5-src/_shared/engine-intl.ts +6 -0
  95. package/templates/retail-store/tier5-src/_shared/engine-intl.ts +6 -0
  96. package/templates/retail-store-owner/tier5-src/_shared/engine-intl.ts +6 -0
  97. package/templates/salon-spa/tier5-src/_shared/business-chat-transport.ts +20 -4
  98. package/templates/salon-spa/tier5-src/_shared/chat-live.ts +242 -0
  99. package/templates/salon-spa/tier5-src/_shared/engine-intl.ts +6 -0
  100. package/templates/salon-spa/tier5-src/_shared/inbox-rooms.ts +101 -11
  101. package/templates/salon-spa/tier5-src/business-chat/index.ts +73 -22
  102. package/templates/wholesale-store/tier5-src/_shared/business-chat-transport.ts +20 -4
  103. package/templates/wholesale-store/tier5-src/_shared/chat-live.ts +242 -0
  104. package/templates/wholesale-store/tier5-src/_shared/engine-intl.ts +6 -0
  105. package/templates/wholesale-store/tier5-src/_shared/inbox-rooms.ts +101 -11
  106. package/templates/wholesale-store/tier5-src/business-chat/index.ts +73 -22
  107. package/templates/yoga-studio/tier5-src/_shared/business-chat-transport.ts +20 -4
  108. package/templates/yoga-studio/tier5-src/_shared/engine-intl.ts +6 -0
  109. package/templates/yoga-studio-owner/tier5-src/_shared/engine-intl.ts +6 -0
@@ -29,6 +29,19 @@ async function fenced<T>(identity: ChatIdentity, run: () => Promise<T>): Promise
29
29
  /** Any other member-scoped call (the AI chat's) goes through the same fence. */
30
30
  export const fence = fenced;
31
31
 
32
+ /** A signed-out visitor's Smart Chat calls are fenced the other way: still signed out before the request goes
33
+ * out and again before its response is used, so signing in mid-request never mixes the visitor's chat into
34
+ * the member's. Fails as `MemberAccessChanged`, like the member fence, so callers handle both alike. */
35
+ async function assertStillVisitor(): Promise<void> {
36
+ if ((await memberAccess()).email) throw Object.assign(new Error("visitor_signed_in"), { name: "MemberAccessChanged" });
37
+ }
38
+ export async function visitorFence<T>(run: () => Promise<T>): Promise<T> {
39
+ await assertStillVisitor();
40
+ const result = await run();
41
+ await assertStillVisitor();
42
+ return result;
43
+ }
44
+
32
45
  // Minting a chat token is a network round trip, and every chat call used to mint its own. One token
33
46
  // per member is reused until the member changes or a request using it is refused.
34
47
  let cachedToken: { key: string; token: string } | null = null;
@@ -44,7 +57,7 @@ async function chatTokenFor(identity: ChatIdentity): Promise<string> {
44
57
  return chatToken;
45
58
  }
46
59
  /** Runs `run` with the member's cached token; a refused request mints a fresh token and tries once more. */
47
- async function withToken<T>(identity: ChatIdentity, run: (chatToken: string) => Promise<T>): Promise<T> {
60
+ export async function withToken<T>(identity: ChatIdentity, run: (chatToken: string) => Promise<T>): Promise<T> {
48
61
  const reused = cachedToken?.key === tokenKey(identity);
49
62
  try {
50
63
  return await run(await chatTokenFor(identity));
@@ -80,7 +93,7 @@ export const unreadRoomCount = (identity: ChatIdentity): Promise<number> => fenc
80
93
  export const messagesPage = (identity: ChatIdentity, roomId: string): Promise<Raw[]> => fenced(identity, async () =>
81
94
  (await withToken(identity, (chatToken) => getMessagesPage(roomId, { ...MEMBER, chatToken, pageSize: 50, ordering: "Desc" }))).items as unknown as Raw[]);
82
95
 
83
- function bridge(): Bridge {
96
+ export function bridge(): Bridge {
84
97
  const api = (globalThis as unknown as { himalaya?: { wixApi?: Bridge } }).himalaya?.wixApi;
85
98
  if (!api) throw new Error("wix_api_bridge_unavailable");
86
99
  return api;
@@ -89,7 +102,10 @@ function bridge(): Bridge {
89
102
  * Wix Smart Chat and the AI can answer it; a message posted straight into the room has no channel, so the AI never
90
103
  * saw it and the owner's reply went out by email. Smart Chat chooses the conversation and stored message id.
91
104
  * The bridge resolves once the AI has finished answering, not when the message is stored. */
92
- export const sendMessage = (identity: ChatIdentity, text: string): Promise<string | undefined> => fenced(identity, async () => {
105
+ export const sendMessage = (identity: ChatIdentity, text: string): Promise<string | undefined> => fenced(identity, () => postQuestion(text));
106
+ /** The same Smart Chat send for a signed-out visitor: Smart Chat accepts the anonymous visitor token. */
107
+ export const sendVisitorMessage = (text: string): Promise<string | undefined> => visitorFence(() => postQuestion(text));
108
+ async function postQuestion(text: string): Promise<string | undefined> {
93
109
  const response = await bridge().call("POST", "/wix-assistant-widget/v1/messages/stream", {
94
110
  message: { sender: "SITE_VISITOR", messageType: "QUESTION", body: { mainText: text } },
95
111
  });
@@ -123,7 +139,7 @@ export const sendMessage = (identity: ChatIdentity, text: string): Promise<strin
123
139
  if (input?.sender === "SITE_VISITOR" && input.messageType === "QUESTION" && typeof input.id === "string" && input.id) return `smart-chat:${input.id}`;
124
140
  }
125
141
  return undefined;
126
- });
142
+ }
127
143
  /** A tapped button is a silent, ephemeral message carrying the button's chat action. */
128
144
  export const sendButton = (identity: ChatIdentity, roomId: string, input: { id: string; text: string; appId: string; interactionId: string }): Promise<void> => fenced(identity, async () => {
129
145
  await withToken(identity, (chatToken) => bridge().call("POST", `${MANAGE}/_api/chat-web/v2/chatrooms/${encodeURIComponent(roomId)}/messages`, {
@@ -119,6 +119,12 @@ export function formatMonthDayLong(date: Date, locale = appLocale(), timeZone?:
119
119
 
120
120
  const WEEKDAYS_LONG = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] as const;
121
121
 
122
+ /** `{ weekday: "short" }` — "Mon". */
123
+ export function formatWeekdayShort(date: Date, locale = appLocale(), timeZone?: string): string {
124
+ if (hasIntl()) return dateFormat(locale, { weekday: "short" }, timeZone).format(date);
125
+ return WEEKDAYS_SHORT[date.getDay()]!;
126
+ }
127
+
122
128
  /** `{ weekday: "short", month: "short", day: "numeric" }` — "Mon, Jan 5". */
123
129
  export function formatWeekdayMonthDay(date: Date, locale = appLocale(), timeZone?: string): string {
124
130
  if (hasIntl()) {
@@ -1,5 +1,6 @@
1
1
  // The member's Inbox rows: every chatroom the member-role chat list returns, business and member alike.
2
2
  // Pure, so the worker and its tests share one classification of what a room is.
3
+ import { calendarDay, formatClock, formatMonthDay, formatWeekdayShort } from "./engine-intl.js";
3
4
 
4
5
  type RecordValue = Record<string, unknown>;
5
6
  const object = (value: unknown): RecordValue =>
@@ -15,6 +16,8 @@ export function isBusinessRoom(value: unknown): boolean {
15
16
  Object.keys(object(room.businessContext)).length > 0;
16
17
  }
17
18
 
19
+ export const BUSINESS_SCREEN = "himi_business_chat";
20
+
18
21
  export interface InboxRow {
19
22
  id: string;
20
23
  title: string;
@@ -24,14 +27,78 @@ export interface InboxRow {
24
27
  /** `chatroom` makes the thread use `id` as the room instead of resolving it as a member id. */
25
28
  kind: "chatroom" | "";
26
29
  photo: string;
30
+ /** No photo: the screen draws the initial instead (`!photo`, kept with the photo by completeRow). */
31
+ noPhoto: boolean;
27
32
  initial: string;
33
+ /** Has unread messages, or the member marked it unread. */
28
34
  unread: boolean;
35
+ /** "●" when unread, else "". Kept for the screens that bind the glyph. */
29
36
  unreadDot: string;
37
+ /** The server's unread count; 0 when none, or when the member marked a room unread (the count is then unknown). */
38
+ unreadCount: number;
39
+ /** The count as text: "" for 0 or unknown, "99+" above 99. */
40
+ unreadText: string;
41
+ /** hiddenWhen gates in both polarities: a count badge when the count is known, a plain dot when the room is
42
+ * unread but the count is not. */
43
+ showCount: boolean; hideCount: boolean; showDot: boolean; hideDot: boolean;
44
+ /** Last activity: the time today, "Yesterday", the weekday within the last six calendar days (as chat lists show it,
45
+ * not the calendar week), else the day. "" when unknown. */
46
+ dateLabel: string;
47
+ isArchived: boolean;
48
+ /** Only a private room can be deleted by a member (the Wix app's rule). */
49
+ isPrivate: boolean;
50
+ /** Swipe-action gates (hiddenWhen hides on TRUE). */
51
+ hideArchive: boolean; hideUnarchive: boolean; hideDelete: boolean; hideMarkRead: boolean; hideMarkUnread: boolean;
30
52
  /** Sort key only; not bound to the screen. */
31
53
  at: number;
32
54
  }
33
55
 
34
56
  const text = (value: unknown): string => (typeof value === "string" ? value.trim() : "");
57
+ const MAX_COUNT = 99;
58
+
59
+ /** "" for 0 or an unknown count, "99+" above 99. */
60
+ export const unreadCountText = (count: number): string => (count > MAX_COUNT ? `${MAX_COUNT}+` : count > 0 ? String(count) : "");
61
+
62
+ /** Everything that follows from a row's base fields. The one place a flag is derived, so a row that changes
63
+ * (marked read, archived) can never carry a flag that disagrees with its base fields. */
64
+ export type RowBase = Pick<InboxRow, "id" | "title" | "subtitle" | "screenId" | "kind" | "photo" | "initial" | "unread" | "unreadCount" | "dateLabel" | "isArchived" | "isPrivate" | "at">;
65
+ export function completeRow(base: RowBase): InboxRow {
66
+ const unreadText = unreadCountText(base.unreadCount);
67
+ const showCount = base.unread && unreadText !== "";
68
+ const showDot = base.unread && !showCount;
69
+ return {
70
+ ...base,
71
+ noPhoto: !base.photo,
72
+ unreadDot: base.unread ? "●" : "",
73
+ unreadText,
74
+ showCount, hideCount: !showCount, showDot, hideDot: !showDot,
75
+ hideArchive: base.isArchived, hideUnarchive: !base.isArchived,
76
+ hideDelete: !base.isPrivate,
77
+ hideMarkRead: !base.unread, hideMarkUnread: base.unread,
78
+ };
79
+ }
80
+
81
+ /** A row's read state changed: `count` is the server's count (0 = unknown or none). */
82
+ export function withUnread(row: InboxRow, unread: boolean, count: number): InboxRow {
83
+ const { id, title, subtitle, screenId, kind, photo, initial, dateLabel, isArchived, isPrivate, at } = row;
84
+ return completeRow({ id, title, subtitle, screenId, kind, photo, initial, dateLabel, isArchived, isPrivate, at, unread, unreadCount: unread ? count : 0 });
85
+ }
86
+
87
+ /** Last-activity label in the device's zone: today → the time, yesterday → [yesterday] (the caller passes the localised
88
+ * word), within the last six calendar days → the weekday, otherwise the day. "" for an unknown time. Days are calendar
89
+ * days (local midnight to midnight), never 24-hour spans, so one day never gets two label formats and DST cannot shift them. */
90
+ export function dateLabel(at: number, yesterday: string, now: number = Date.now()): string {
91
+ if (!Number.isFinite(at) || at <= 0) return "";
92
+ const date = new Date(at);
93
+ const day = calendarDay(date);
94
+ if (day === calendarDay(new Date(now))) return formatClock(date);
95
+ const today = new Date(now);
96
+ // Noon of the previous calendar day: a 23- or 25-hour day around DST cannot move it to another day.
97
+ if (day === calendarDay(new Date(today.getFullYear(), today.getMonth(), today.getDate() - 1, 12))) return yesterday;
98
+ const sixDaysBack = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 6).getTime();
99
+ if (at >= sixDaysBack && at <= now) return formatWeekdayShort(date);
100
+ return formatMonthDay(date);
101
+ }
35
102
 
36
103
  function titleOf(room: RecordValue, business: boolean): string {
37
104
  const display = text(object(room.displayData).name);
@@ -39,30 +106,53 @@ function titleOf(room: RecordValue, business: boolean): string {
39
106
  return display;
40
107
  }
41
108
 
42
- /** Newest conversation first; archived rooms and rooms without an id are dropped. `fallbackTitle` names a
43
- * room that carries no name (the caller passes the localised word, not a hard-coded English one). */
44
- export function inboxRows(rooms: unknown[], fallbackTitle: string): InboxRow[] {
109
+ export interface InboxRowsOptions {
110
+ /** `inbox` (default): archived rooms are dropped. `archive`: the list is the archive, every room is kept and marked
111
+ * archived. `all`: search results, kept as they are. */
112
+ scope?: "inbox" | "archive" | "all";
113
+ /** The localised word for yesterday; "Yesterday" when absent. */
114
+ yesterday?: string;
115
+ now?: number;
116
+ /** Rooms the server lists as unread (`unreadChatroomIds`): a room the member marked unread has no count, only this. */
117
+ unreadIds?: ReadonlySet<string>;
118
+ }
119
+
120
+ /** Newest conversation first; rooms without an id are dropped, and so are archived rooms in the inbox. `fallbackTitle`
121
+ * names a room that carries no name (the caller passes the localised word, not a hard-coded English one). */
122
+ export function inboxRows(rooms: unknown[], fallbackTitle: string, options: InboxRowsOptions = {}): InboxRow[] {
123
+ const { scope = "inbox", yesterday = "Yesterday", now, unreadIds } = options;
45
124
  const rows: InboxRow[] = [];
46
125
  for (const value of rooms) {
47
126
  const room = object(value);
48
127
  const id = text(room.id);
49
- if (!id || room.isArchived === true) continue;
128
+ if (!id) continue;
129
+ if (scope === "inbox" && room.isArchived === true) continue;
50
130
  const business = isBusinessRoom(room);
51
131
  const title = titleOf(room, business) || fallbackTitle;
52
132
  const last = object(room.lastMessage);
53
- const unread = typeof room.unreadCount === "number" && room.unreadCount > 0;
54
- rows.push({
133
+ const count = typeof room.unreadCount === "number" && Number.isFinite(room.unreadCount) && room.unreadCount > 0 ? Math.floor(room.unreadCount) : 0;
134
+ const at = typeof last.createdAt === "number" ? last.createdAt : typeof room.createdAt === "number" ? room.createdAt : 0;
135
+ rows.push(completeRow({
55
136
  id,
56
137
  title,
57
138
  subtitle: text(last.summary),
58
- screenId: business ? "himi_business_chat" : "himi_chat_thread",
139
+ screenId: business ? BUSINESS_SCREEN : "himi_chat_thread",
59
140
  kind: business ? "" : "chatroom",
60
141
  photo: text(object(object(room.displayData).image).url),
61
142
  initial: (title[0] ?? "#").toUpperCase(),
62
- unread,
63
- unreadDot: unread ? "●" : "",
64
- at: typeof last.createdAt === "number" ? last.createdAt : typeof room.createdAt === "number" ? room.createdAt : 0,
65
- });
143
+ unread: count > 0 || unreadIds?.has(id) === true,
144
+ unreadCount: count,
145
+ dateLabel: dateLabel(at, yesterday, now),
146
+ isArchived: scope === "archive" || room.isArchived === true,
147
+ isPrivate: room.isPrivate === true,
148
+ at,
149
+ }));
66
150
  }
67
151
  return rows.sort((a, b) => b.at - a.at);
68
152
  }
153
+
154
+ /** The newest message sequence a room's list entry carries, when it carries one (marking a room read needs it). */
155
+ export function lastSequenceOf(value: unknown): number | undefined {
156
+ const sequence = object(object(value).lastMessage).sequence;
157
+ return typeof sequence === "number" && Number.isSafeInteger(sequence) && sequence >= 0 ? sequence : undefined;
158
+ }
@@ -0,0 +1,119 @@
1
+ // The member Inbox search: the request body and the reading of the answer of
2
+ // `POST https://manage.wix.com/_serverless/chat-search/v2/search` (the call the Wix app's own Inbox search makes).
3
+ //
4
+ // The REQUEST is the Wix app's (`{query, participantIds, chatroomsPaginator, messagesPaginator}`). The ANSWER's shape has
5
+ // NOT been read live: only the request was recovered from the app's source. The reader below accepts the shapes that
6
+ // service family uses for lists (`{items}` or a bare array, an entry that is the record or wraps it) and for cursors
7
+ // (`next.before`, `nextPointer`), and reads a field it does not find as absent, never as an error. Probe the answer with a
8
+ // member session and pin the real shape in the test before relying on a field.
9
+ import { BUSINESS_SCREEN, dateLabel, inboxRows, isBusinessRoom, type InboxRow, type InboxRowsOptions } from "./inbox-rooms.js";
10
+
11
+ type RecordValue = Record<string, unknown>;
12
+ const object = (value: unknown): RecordValue =>
13
+ value !== null && typeof value === "object" && !Array.isArray(value) ? value as RecordValue : {};
14
+ const text = (value: unknown): string => (typeof value === "string" ? value.trim() : "");
15
+
16
+ export const SEARCH_CHATS_PAGE = 15;
17
+ export const SEARCH_MESSAGES_PAGE = 10;
18
+ /** The last message the server returns with each matching chat. */
19
+ const LAST_MESSAGE_LIMIT = 1;
20
+
21
+ export interface SearchCursors { chats?: string; messages?: string }
22
+
23
+ export function searchBody(query: string, cursors: SearchCursors = {}): Record<string, unknown> {
24
+ return {
25
+ query,
26
+ participantIds: [],
27
+ chatroomsPaginator: { pageSize: SEARCH_CHATS_PAGE, lastMessageLimit: LAST_MESSAGE_LIMIT, ...(cursors.chats ? { nextPointer: cursors.chats } : {}) },
28
+ messagesPaginator: { pageSize: SEARCH_MESSAGES_PAGE, ...(cursors.messages ? { nextPointer: cursors.messages } : {}) },
29
+ };
30
+ }
31
+
32
+ /** One matching message: flat, so a list row can bind it. `id` is unique per hit (a room can match many times);
33
+ * `roomId` is the room a tap opens, with `screenId` and `kind` exactly as an InboxRow carries them. */
34
+ export interface SearchHit {
35
+ id: string; roomId: string; title: string; snippet: string; dateLabel: string;
36
+ screenId: InboxRow["screenId"]; kind: InboxRow["kind"]; photo: string; noPhoto: boolean; initial: string;
37
+ }
38
+
39
+ export interface SearchPage {
40
+ chats: InboxRow[];
41
+ messages: SearchHit[];
42
+ /** "" = no more of that kind. */
43
+ chatsCursor: string;
44
+ messagesCursor: string;
45
+ }
46
+
47
+ const listOf = (value: unknown): unknown[] => {
48
+ if (Array.isArray(value)) return value;
49
+ const items = object(value).items;
50
+ return Array.isArray(items) ? items : [];
51
+ };
52
+
53
+ /** A cursor the service hands back: a string or a number; "" when the list is finished. */
54
+ function cursorOf(...candidates: unknown[]): string {
55
+ for (const value of candidates) {
56
+ if (typeof value === "string" && value) return value;
57
+ if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0) return String(value);
58
+ }
59
+ return "";
60
+ }
61
+
62
+ /** The matched message's text: its summary, else the text part of its data. */
63
+ function snippetOf(message: RecordValue): string {
64
+ const summary = text(message.summary);
65
+ if (summary) return summary;
66
+ for (const part of listOf(message.data)) {
67
+ const value = text(object(object(part).data).text);
68
+ if (value) return value;
69
+ }
70
+ return "";
71
+ }
72
+
73
+ export interface ReadSearchOptions extends InboxRowsOptions {
74
+ fallbackTitle: string;
75
+ /** Names for rooms the answer gives only an id for (the rooms already on screen). */
76
+ knownRooms?: ReadonlyMap<string, InboxRow>;
77
+ }
78
+
79
+ export function readSearch(response: unknown, options: ReadSearchOptions): SearchPage {
80
+ const root = object(response);
81
+ const chatsNode = object(root.chatrooms);
82
+ const messagesNode = object(root.messages);
83
+ // A chat entry is the chatroom, or a wrapper holding it.
84
+ const rooms = listOf(root.chatrooms).map((entry) => (object(entry).chatroom ? object(entry).chatroom : entry));
85
+ const chats = inboxRows(rooms, options.fallbackTitle, { scope: "all", yesterday: options.yesterday, now: options.now });
86
+ const known = new Map<string, InboxRow>([...(options.knownRooms ?? []), ...chats.map((row): [string, InboxRow] => [row.id, row])]);
87
+ const messages: SearchHit[] = [];
88
+ const seen = new Set<string>();
89
+ for (const entry of listOf(root.messages)) {
90
+ const wrapper = object(entry);
91
+ const message = object(wrapper.message ?? entry);
92
+ const roomId = text(wrapper.chatroomId) || text(message.chatroomId) || text(object(wrapper.chatroom).id);
93
+ if (!roomId) continue;
94
+ const messageId = text(message.id) || text(message._id) || text(wrapper.id);
95
+ const id = `${roomId}:${messageId || messages.length}`;
96
+ if (seen.has(id)) continue;
97
+ seen.add(id);
98
+ const room = known.get(roomId);
99
+ // A room not on screen and not among the chat results: the hit's own room record says whether it is the business's.
100
+ const business = !room && isBusinessRoom(wrapper.chatroom);
101
+ const title = room?.title || text(object(object(wrapper.chatroom).displayData).name) || options.fallbackTitle;
102
+ const at = typeof message.createdAt === "number" ? message.createdAt : 0;
103
+ messages.push({
104
+ id, roomId, title,
105
+ snippet: snippetOf(message),
106
+ dateLabel: dateLabel(at, options.yesterday ?? "Yesterday", options.now),
107
+ screenId: room?.screenId ?? (business ? BUSINESS_SCREEN : "himi_chat_thread"),
108
+ kind: room ? room.kind : business ? "" : "chatroom",
109
+ photo: room?.photo ?? "",
110
+ noPhoto: !room?.photo,
111
+ initial: room?.initial ?? (title[0] ?? "#").toUpperCase(),
112
+ });
113
+ }
114
+ return {
115
+ chats, messages,
116
+ chatsCursor: cursorOf(object(chatsNode.next).before, chatsNode.nextPointer, root.chatroomsNextPointer, object(root.chatroomsPaginator).nextPointer),
117
+ messagesCursor: cursorOf(object(messagesNode.next).before, messagesNode.nextPointer, root.messagesNextPointer, object(root.messagesPaginator).nextPointer),
118
+ };
119
+ }
@@ -0,0 +1,64 @@
1
+ // The member Inbox's Wix calls, on the same fenced, token-cached transport as the business chat
2
+ // (business-chat-transport.ts): the member-role chat-web SDK for the list and the per-room actions, plus the two calls the
3
+ // SDK has no helper for (mark every room read, and search). Every call is fenced: the member is re-checked before the
4
+ // request goes out and before its answer is used, so a sign-out or account switch never leaks one member's rooms to the next.
5
+ import { archiveChatroom, deleteChatroom, getMessagesPage, listChatroomsPage, markChatroomRead, markChatroomUnread, type Chatroom } from "@himalaya/wix-chat-web";
6
+ import { bridge, fence, withToken, type ChatIdentity } from "./business-chat-transport.js";
7
+ import { searchBody, type SearchCursors } from "./inbox-search.js";
8
+
9
+ const MANAGE = "https://manage.wix.com";
10
+ const MEMBER = { role: "member" } as const;
11
+ export const INBOX_PAGE_SIZE = 30;
12
+
13
+ /** `unreadIds`: rooms the server lists as unread (`unreadChatroomIds`), which includes a room the member marked unread
14
+ * (its `unreadCount` stays 0). */
15
+ export interface InboxPage { items: Chatroom[]; nextPointer?: number | string; unreadIds: string[] }
16
+
17
+ /** One page of the member's conversations (the archive when `archived`), from `cursor` when given. */
18
+ export const listInboxPage = (identity: ChatIdentity, query: { archived: boolean; cursor?: string }): Promise<InboxPage> =>
19
+ fence(identity, async () => {
20
+ const page = await withToken(identity, (chatToken) => listChatroomsPage({
21
+ ...MEMBER, chatToken, pageSize: INBOX_PAGE_SIZE,
22
+ ...(query.archived ? { archived: true } : {}),
23
+ ...(query.cursor ? { nextPointer: query.cursor } : {}),
24
+ }));
25
+ return { items: page.items, nextPointer: page.nextPointer, unreadIds: page.unreadChatroomIds ?? [] };
26
+ });
27
+
28
+ /** Does the member have any archived conversation? One row is enough to know. */
29
+ export const hasArchivedRooms = (identity: ChatIdentity): Promise<boolean> => fence(identity, async () =>
30
+ (await withToken(identity, (chatToken) => listChatroomsPage({ ...MEMBER, chatToken, pageSize: 1, archived: true }))).items.length > 0);
31
+
32
+ export const setRoomArchived = (identity: ChatIdentity, roomId: string, archived: boolean): Promise<void> =>
33
+ fence(identity, () => withToken(identity, (chatToken) => archiveChatroom(roomId, archived, { ...MEMBER, chatToken })));
34
+
35
+ export const deleteRoom = (identity: ChatIdentity, roomId: string): Promise<void> =>
36
+ fence(identity, () => withToken(identity, (chatToken) => deleteChatroom(roomId, { ...MEMBER, chatToken })));
37
+
38
+ export const markRoomUnread = (identity: ChatIdentity, roomId: string): Promise<void> =>
39
+ fence(identity, () => withToken(identity, (chatToken) => markChatroomUnread(roomId, undefined, { ...MEMBER, chatToken })));
40
+
41
+ /** Marking read needs the room's newest message sequence. The list entry usually carries it (`knownSequence`); when it
42
+ * does not, the newest message is read for it. A room with no message has nothing to read. */
43
+ export const markRoomRead = (identity: ChatIdentity, roomId: string, knownSequence?: number): Promise<void> =>
44
+ fence(identity, () => withToken(identity, async (chatToken) => {
45
+ let sequence = knownSequence;
46
+ if (sequence === undefined) {
47
+ const newest = (await getMessagesPage(roomId, { ...MEMBER, chatToken, pageSize: 1, ordering: "Desc" })).items[0];
48
+ if (!newest) return;
49
+ sequence = newest.sequence;
50
+ }
51
+ if (sequence === undefined) throw new Error("inbox_room_has_no_message_sequence");
52
+ await markChatroomRead(roomId, sequence, { ...MEMBER, chatToken });
53
+ }));
54
+
55
+ /** Every room read: `PUT chat-web/v1/chatrooms/mark-all-read`, the call the Wix app's "Mark all as read" makes (chat-sdk
56
+ * `setAllRoomsAsRead`). Not yet probed with a member session. */
57
+ export const markAllRoomsRead = (identity: ChatIdentity): Promise<void> =>
58
+ fence(identity, () => withToken(identity, async (chatToken) => {
59
+ await bridge().call("PUT", `${MANAGE}/_api/chat-web/v1/chatrooms/mark-all-read?chatToken=${encodeURIComponent(chatToken)}`, {});
60
+ }));
61
+
62
+ /** The raw search answer (read by `readSearch`). The host authorises the call as the member. */
63
+ export const searchInbox = (identity: ChatIdentity, query: string, cursors: SearchCursors = {}): Promise<unknown> =>
64
+ fence(identity, () => bridge().call("POST", `${MANAGE}/_serverless/chat-search/v2/search`, searchBody(query, cursors)));
@@ -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
+ }