@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.
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 +25 -6
  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
@@ -1,43 +1,104 @@
1
1
  // himi-branded-lite-inbox — the member's Inbox: every conversation the member-role chat list returns, the
2
2
  // business's and other members'. Only the member-role list is used (`GET inbox/v2/conversations`, the call the
3
- // first Inbox made, is an OWNER endpoint that answers a member with 404). A failed query is an error with Retry
4
- // (or Sign in for a visitor) and an empty one is a real empty state — never sample rows presented as the
3
+ // first Inbox made, is an OWNER endpoint that answers a member with 404). A failed query is a classified error with
4
+ // Retry (or Sign in for a visitor) and an empty one is a real empty state — never sample rows presented as the
5
5
  // customer's own. Samples appear only in the host's explicit sample preview (_shared/branded-load-state.ts).
6
+ //
7
+ // What the worker offers the screen (the contract is written out in the PR description and the design hand-off):
8
+ // • the list, one page at a time (`nextCursor` + `loadMore`), the inbox or the archive (`mode`), the business's room
9
+ // lifted out of the list into its own fields (the screen pins it);
10
+ // • per-room actions with an optimistic update, an Undo where one exists, and a rollback with a classified error
11
+ // message when Wix refuses: archive, unarchive, markRead, markUnread, delete (private rooms only), markAllRead;
12
+ // • search across chats and messages (`search`, `searchLoadMore`, `clearSearch`).
13
+ // An async action publishes no state until it returns, so every write is a SYNC reducer that paints the optimistic
14
+ // state and starts the request, and the request reports back through `settleOp` (the business chat's send does the same).
15
+ import { classifyLoadError } from "@himalaya/state";
6
16
  import { defineService } from "../_shared/collection-service.js";
7
- import { LOADING, loaded, loadFailed, type LoadCopy, type LoadFlags } from "../_shared/branded-load-state.js";
8
- import { getChatToken, listChatroomsPage } from "@himalaya/wix-chat-web";
9
- import { assertMemberAccess, memberAccess } from "../_shared/member-access.js";
10
- import { inboxRows, type InboxRow } from "../_shared/inbox-rooms.js";
17
+ import { LOADING, loaded, loadFailed, samplesRequested, type LoadCopy, type LoadFlags } from "../_shared/branded-load-state.js";
18
+ import { chatIdentity, type ChatIdentity } from "../_shared/business-chat-transport.js";
19
+ import { memberAccess, memberAccessChanged } from "../_shared/member-access.js";
20
+ import { BUSINESS_SCREEN, completeRow, inboxRows, lastSequenceOf, withUnread, type InboxRow } from "../_shared/inbox-rooms.js";
21
+ import { readSearch, type SearchHit, type SearchPage } from "../_shared/inbox-search.js";
22
+ import {
23
+ deleteRoom, hasArchivedRooms, listInboxPage, markAllRoomsRead, markRoomRead, markRoomUnread, searchInbox, setRoomArchived,
24
+ type InboxPage,
25
+ } from "../_shared/member-inbox-transport.js";
11
26
  import { copyParam, stashCopy } from "../_shared/himi-copy.js";
12
27
 
13
28
  type Row = Omit<InboxRow, "at">;
29
+ const strip = ({ at: _at, ...row }: InboxRow): Row => row;
30
+ /** A room's read state changed (the count is the server's; 0 = unknown). */
31
+ const withRead = (row: Row, unread: boolean, count: number): Row => strip(withUnread({ ...row, at: 0 }, unread, count));
32
+ type Mode = "inbox" | "archive";
33
+ type FailureKind = "offline" | "server" | "signIn" | "permission";
34
+ type ErrorKind = "" | FailureKind;
35
+ type SearchStatus = "idle" | "loading" | "ready" | "error";
36
+
14
37
  interface S extends LoadFlags {
38
+ /** Every conversation but the business's room (inbox mode), newest first; the archive's rooms in archive mode. */
15
39
  conversations: Row[]; emptyText: string;
16
- isMock: boolean; notMock: boolean; /** #2849 — hiddenWhen() hides on TRUE, so these are inverted: the empty-state banner
17
- * shows only when the site really has none, and the unavailable one only when the query failed. A failed
18
- * query must never render the sentence that claims the customer has no conversations. */
19
- notMockEmpty: boolean; notMockUnavailable: boolean;
20
- }
21
40
 
22
- const MEMBER = { role: "member" } as const;
23
- const PAGE_SIZE = 50;
24
- // 2000 conversations: far beyond a real member. The cap only stops a runaway cursor from looping, and reaching it is an
25
- // error, never a quietly shorter list.
26
- const MAX_PAGES = 40;
41
+ /** `inbox` or `archive`. Always one of the two. */
42
+ mode: Mode; isArchive: boolean; notArchive: boolean;
43
+ /** Archive mode, loaded, no room in it. Both polarities. The inbox's own empty state stays off in archive mode. */
44
+ archiveEmpty: boolean; notArchiveEmpty: boolean;
45
+ /** The member has archived conversations (known after the first inbox load, or once they archive one). */
46
+ hasArchived: boolean;
47
+ /** The "Go to Archive" entry: inbox mode, loaded, and there is an archive to go to. Both polarities. */
48
+ showArchiveEntry: boolean; hideArchiveEntry: boolean;
49
+
50
+ /** The business's room, lifted out of `conversations` (inbox mode only; null when the member has none). */
51
+ businessRow: Row | null;
52
+ hasBusinessRoom: boolean; noBusinessRoom: boolean;
53
+ businessRoomId: string; businessPreview: string; businessDate: string;
54
+ /** "" for none or unknown, "99+" above 99. */
55
+ businessUnreadText: string; businessUnreadCount: number;
56
+ businessHasUnread: boolean; businessNoUnread: boolean;
57
+
58
+ /** Paging. `nextCursor` is "" when the list is finished (the list's `pagination.cursor` binds it). A failed page keeps
59
+ * the rows, ends `nextCursor` and keeps the cursor that failed in `failedCursor` for `retryLoadMore`. */
60
+ nextCursor: string; failedCursor: string; loadMoreError: boolean; hideLoadMoreError: boolean;
61
+
62
+ /** Why the last load failed ("" if it did not). Flags for the full-screen error, one per class, true = hide. They show
63
+ * only when there is nothing to keep on screen; a refresh that fails over kept rows sets `refreshError` instead. */
64
+ errorKind: ErrorKind;
65
+ hideOfflineError: boolean; hideServerError: boolean; hideSignInError: boolean; hidePermissionError: boolean;
66
+ refreshError: boolean; hideRefreshError: boolean;
67
+
68
+ /** The last write that Wix refused, as a customer sentence ("" none). The row is already back as it was. */
69
+ actionError: string; hideActionError: boolean;
70
+ /** The last undoable write: what it was, its room, a message for the snackbar. "" none. */
71
+ undoKind: string; undoRoomId: string; undoMessage: string; hasUndo: boolean; hideUndo: boolean;
72
+ /** "Mark all as read" has nothing to do when no loaded room is unread. */
73
+ hideMarkAllRead: boolean;
74
+
75
+ /** Search. `query` is the text last searched ("" = not searching). */
76
+ query: string; isSearching: boolean; notSearching: boolean;
77
+ searchStatus: SearchStatus;
78
+ searchChats: Row[]; searchMessages: SearchHit[];
79
+ searchError: string; searchErrorKind: ErrorKind;
80
+ hideSearchLoading: boolean; hideSearchError: boolean; hideSearchEmpty: boolean; hideSearchResults: boolean;
81
+ /** "" when there is no more to load; changes with every page (the list's `pagination.cursor` binds it). */
82
+ searchCursor: string; searchMoreError: boolean; hideSearchMoreError: boolean;
83
+ searchChatsCursor: string; searchMessagesCursor: string;
84
+ }
27
85
 
28
- const MOCK: Row[] = [
29
- { id: "sample-support", title: "Support", subtitle: "Hi! Let us know how we can help.", screenId: "himi_business_chat", kind: "", photo: "", initial: "S", unread: false, unreadDot: "" },
30
- { id: "sample-member", title: "A member", subtitle: "Welcome 👋 Thanks for joining us!", screenId: "himi_chat_thread", kind: "chatroom", photo: "", initial: "A", unread: false, unreadDot: "" },
86
+ const PREFIX = "inbox";
87
+ const sample = (base: Pick<InboxRow, "id" | "title" | "subtitle" | "screenId" | "kind" | "initial">): Row =>
88
+ strip(completeRow({ ...base, photo: "", unread: false, unreadCount: 0, dateLabel: "", isArchived: false, isPrivate: false, at: 0 }));
89
+ const SAMPLES: Row[] = [
90
+ sample({ id: "sample-support", title: "Support", subtitle: "Hi! Let us know how we can help.", screenId: "himi_business_chat", kind: "", initial: "S" }),
91
+ sample({ id: "sample-member", title: "A member", subtitle: "Welcome 👋 Thanks for joining us!", screenId: "himi_chat_thread", kind: "chatroom", initial: "A" }),
31
92
  ];
32
93
 
33
94
  /** Sample rows reach the screen ONLY in the host's explicit sample preview; a failed or empty query is an
34
95
  * honest error / empty state (branded-load-state.ts). */
35
96
  const COPY: LoadCopy<Row> = {
36
- prefix: "inbox",
97
+ prefix: PREFIX,
37
98
  empty: "No messages yet.",
38
99
  error: "Your messages couldn't be loaded.",
39
100
  signIn: "Sign in to see your messages.",
40
- sample: () => MOCK.map((r) => ({ ...r })),
101
+ sample: () => SAMPLES.map((r) => ({ ...r })),
41
102
  };
42
103
 
43
104
  /** Where the business's conversation opens. The host may name another served screen (`businessScreenId` in the
@@ -46,46 +107,708 @@ let businessScreenId = "himi_business_chat";
46
107
 
47
108
  const signInRequired = () => new Error("Unauthenticated: sign in to see your messages");
48
109
 
49
- async function listAllRooms(): Promise<unknown[]> {
50
- // One token for every page; a refused one fails the whole load rather than showing half a list.
51
- const { chatToken } = await getChatToken(MEMBER);
52
- const rooms: unknown[] = [];
53
- let nextPointer: number | string | undefined;
54
- for (let page = 0; page < MAX_PAGES; page++) {
55
- const result = await listChatroomsPage({ ...MEMBER, chatToken, pageSize: PAGE_SIZE, ...(nextPointer !== undefined ? { nextPointer } : {}) });
56
- rooms.push(...result.items);
57
- nextPointer = result.nextPointer;
58
- if (nextPointer === undefined) return rooms;
110
+ // ---------------------------------------------------------------------------------------------------------------------
111
+ // Copy. Every sentence the worker emits goes through a copy key with its English fallback (himi-copy.ts).
112
+ // ---------------------------------------------------------------------------------------------------------------------
113
+ const offlineText = () => copyParam("inbox.offlineText", "You're offline. Check your connection and try again.");
114
+ /** The sentence for a failed LOAD. Sign-in is `loadFailed`'s own (its stock key). */
115
+ const loadText = (kind: FailureKind): string =>
116
+ kind === "offline" ? offlineText()
117
+ : kind === "permission" ? copyParam("inbox.permissionText", "You don't have access to your messages.")
118
+ // The failure sentence is the screen banner's stock key, not a second key for the same English (the extractor
119
+ // keeps one key per extracted row); loadFailed would read `inbox.errorText`, which does not exist.
120
+ : copyParam("inbox.unavailableBody", COPY.error);
121
+ const actionText = (kind: FailureKind): string =>
122
+ kind === "offline" ? offlineText()
123
+ : kind === "permission" ? copyParam("inbox.actionPermissionText", "You don't have permission to do that.")
124
+ : kind === "signIn" ? copyParam("inbox.signInText", COPY.signIn)
125
+ : copyParam("inbox.actionFailedText", "That didn't work. Please try again.");
126
+ const searchText = (kind: FailureKind): string =>
127
+ kind === "server" ? copyParam("inbox.searchFailedText", "Search isn't available right now.")
128
+ : kind === "permission" ? loadText(kind) : actionText(kind);
129
+
130
+ // ---------------------------------------------------------------------------------------------------------------------
131
+ // State. Every state change goes through shape(), which derives every flag from the base fields.
132
+ // ---------------------------------------------------------------------------------------------------------------------
133
+ function shape(s: S): S {
134
+ const business = s.businessRow;
135
+ const failed = s.status === "error";
136
+ const archiveEmpty = s.mode === "archive" && s.status === "ready" && !s.isMock && s.conversations.length === 0;
137
+ const cursor = s.searchChatsCursor || s.searchMessagesCursor ? `${s.searchChatsCursor}|${s.searchMessagesCursor}` : "";
138
+ const searchHasAny = s.searchChats.length > 0 || s.searchMessages.length > 0;
139
+ // The inbox's own empty state follows the rows (so archiving or deleting the last one shows it), never the load that set
140
+ // it; a pinned business room alone is a list, and the archive has its own empty flags.
141
+ const showEmpty = s.mode === "inbox" && s.conversations.length === 0 && !business;
142
+ return {
143
+ ...s,
144
+ ...(s.status === "ready" && !s.isMock ? { hideEmpty: !showEmpty, emptyText: showEmpty ? copyParam("inbox.emptyText", COPY.empty) : "" } : {}),
145
+ isArchive: s.mode === "archive", notArchive: s.mode !== "archive",
146
+ archiveEmpty, notArchiveEmpty: !archiveEmpty,
147
+ showArchiveEntry: s.mode === "inbox" && s.status === "ready" && s.hasArchived, hideArchiveEntry: !(s.mode === "inbox" && s.status === "ready" && s.hasArchived),
148
+ hasBusinessRoom: !!business, noBusinessRoom: !business,
149
+ businessRoomId: business?.id ?? "", businessPreview: business?.subtitle ?? "", businessDate: business?.dateLabel ?? "",
150
+ businessUnreadText: business?.unreadText ?? "", businessUnreadCount: business?.unreadCount ?? 0,
151
+ businessHasUnread: !!business?.unread, businessNoUnread: !business?.unread,
152
+ loadMoreError: s.failedCursor !== "", hideLoadMoreError: s.failedCursor === "",
153
+ hideOfflineError: !(failed && s.errorKind === "offline"), hideServerError: !(failed && s.errorKind === "server"),
154
+ hideSignInError: !(failed && s.errorKind === "signIn"), hidePermissionError: !(failed && s.errorKind === "permission"),
155
+ hideRefreshError: !s.refreshError,
156
+ hideActionError: s.actionError === "",
157
+ hasUndo: s.undoMessage !== "", hideUndo: s.undoMessage === "",
158
+ hideMarkAllRead: !(s.conversations.some((r) => r.unread) || business?.unread === true),
159
+ isSearching: s.query !== "", notSearching: s.query === "",
160
+ hideSearchLoading: s.searchStatus !== "loading", hideSearchError: s.searchStatus !== "error",
161
+ hideSearchEmpty: !(s.searchStatus === "ready" && !searchHasAny), hideSearchResults: !(s.searchStatus === "ready" && searchHasAny),
162
+ searchCursor: s.searchMoreError ? "" : cursor, hideSearchMoreError: !s.searchMoreError,
163
+ };
164
+ }
165
+
166
+ const INITIAL: S = shape({
167
+ ...LOADING, conversations: [], emptyText: "",
168
+ mode: "inbox", isArchive: false, notArchive: true, archiveEmpty: false, notArchiveEmpty: true,
169
+ hasArchived: false, showArchiveEntry: false, hideArchiveEntry: true,
170
+ businessRow: null, hasBusinessRoom: false, noBusinessRoom: true, businessRoomId: "", businessPreview: "", businessDate: "",
171
+ businessUnreadText: "", businessUnreadCount: 0, businessHasUnread: false, businessNoUnread: true,
172
+ nextCursor: "", failedCursor: "", loadMoreError: false, hideLoadMoreError: true,
173
+ errorKind: "", hideOfflineError: true, hideServerError: true, hideSignInError: true, hidePermissionError: true,
174
+ refreshError: false, hideRefreshError: true,
175
+ actionError: "", hideActionError: true,
176
+ undoKind: "", undoRoomId: "", undoMessage: "", hasUndo: false, hideUndo: true,
177
+ hideMarkAllRead: true,
178
+ query: "", isSearching: false, notSearching: true, searchStatus: "idle", searchChats: [], searchMessages: [],
179
+ searchError: "", searchErrorKind: "", hideSearchLoading: true, hideSearchError: true, hideSearchEmpty: true, hideSearchResults: true,
180
+ searchCursor: "", searchMoreError: false, hideSearchMoreError: true, searchChatsCursor: "", searchMessagesCursor: "",
181
+ });
182
+
183
+ // Worker-lifetime bookkeeping that is not screen state. `epoch` bumps whenever the member goes away, so a request that
184
+ // was started for the previous member never lands on the next one.
185
+ interface Plan {
186
+ /** The room (or `*all`) the write is about: one write per room at a time. */
187
+ id: string;
188
+ /** The list the optimistic effect applies to; an effect never touches the other mode's list. */
189
+ mode: Mode;
190
+ apply: (s: S) => S;
191
+ revert: (s: S) => S;
192
+ call: (identity: ChatIdentity) => Promise<void>;
193
+ /** Read writes: the rooms as refreshes listed them while this write was pending (see `rollbackTo`). */
194
+ listed?: Map<string, Row>;
195
+ /** The plan that reverses this one (Undo), absent for a write that cannot be undone. */
196
+ undo?: Plan;
197
+ /** The write puts a room in the archive (an archive, or the Undo of an unarchive). */
198
+ archives?: boolean;
199
+ /** The write takes a room out of the archive: it may have been the last one. */
200
+ unarchives?: boolean;
201
+ undoKind?: string;
202
+ undoMessage?: string;
203
+ }
204
+ const pending = new Map<number, Plan>();
205
+ /** Writes Wix confirmed since the last list load started. A list read before such a write landed is the list as it was:
206
+ * its effect is laid over the answer, as a pending write's is. */
207
+ const landed: Plan[] = [];
208
+ const MAX_LANDED = 50;
209
+ const sequences = new Map<string, number>();
210
+ let opSeq = 0;
211
+ let epoch = 0;
212
+ let loadGen = 0;
213
+ /** The member whose rooms the screen shows; set only once that member's list is published. */
214
+ let ownerKey = "";
215
+ /** The member has (or is archiving) a conversation in the archive: from the probe, an archive list, or a confirmed archive. */
216
+ let archiveKnown = false;
217
+ /** Counts archive and unarchive writes started or settled: a probe that began before one is out of date. */
218
+ let archiveEdits = 0;
219
+ /** The screen shows the business room as its own pinned row (`pinBusinessRoom` init param); otherwise it stays a row. */
220
+ let pinBusiness = false;
221
+ /** The screen pages the list (`nextCursor` + `loadMore`) and shows `refreshError` over kept rows (`pagedList` init
222
+ * param). Otherwise every page is read at once and a failed refresh is the error state, as before the opt-ins. */
223
+ let pagedList = false;
224
+ /** The member (`email|scope`) whose whole list was scanned without a business room. A business room with new activity is
225
+ * on the first page again, so the later pages need no second scan for that member. */
226
+ let noBusinessRoomFor = "";
227
+ let lastUndo: Plan | undefined;
228
+ let moreInFlight = false;
229
+ let searchSeq = 0;
230
+ let searchMoreInFlight = false;
231
+
232
+ /** The member went away (signed out, or another account): forget everything about the previous one. */
233
+ function forgetMember(): void {
234
+ epoch++; loadGen++; searchSeq++;
235
+ pending.clear(); landed.length = 0; sequences.clear();
236
+ lastUndo = undefined; moreInFlight = false; searchMoreInFlight = false; archiveKnown = false; archiveEdits++;
237
+ }
238
+ const archiveNow = (): boolean => archiveKnown || [...pending.values()].some((p) => p.archives === true);
239
+ function signedOutState(): S {
240
+ forgetMember();
241
+ ownerKey = ""; noBusinessRoomFor = "";
242
+ return shape({ ...INITIAL, ...loadFailed("conversations", signInRequired(), COPY), errorKind: "signIn" });
243
+ }
244
+ /** The member went away mid-request: forget them, then load for whoever is signed in now. */
245
+ function signedOutThenReload(): S {
246
+ const out = signedOutState();
247
+ void Promise.resolve().then(() => svc.load());
248
+ return out;
249
+ }
250
+
251
+ /** Who is signed in, and is it the member whose rooms are on screen? A request for a different member than the screen's
252
+ * is refused before it leaves, so one member's room ids never go out under the next member's token. */
253
+ async function memberOnScreen(): Promise<ChatIdentity> {
254
+ const identity = await chatIdentity();
255
+ if (!identity.authenticated) throw signInRequired();
256
+ if (ownerKey !== "" && ownerKey !== `${identity.email}|${identity.scope}`) throw memberAccessChanged();
257
+ return identity;
258
+ }
259
+ const isSwitch = (error: unknown): boolean => (error as { name?: string } | null)?.name === "MemberAccessChanged";
260
+ async function isSignedIn(): Promise<boolean> {
261
+ try { return !!(await memberAccess()).email; } catch { return false; }
262
+ }
263
+
264
+ /** The state as it is now. An async action's own `s` is the state it STARTED with: the runtime replaces the whole state
265
+ * with what an action returns, so a read that resolves after the member acted would otherwise put the old rows back. */
266
+ const live = (fallback: S): S => {
267
+ try { return svc.getState() ?? fallback; } catch { return fallback; }
268
+ };
269
+
270
+ async function kindOf(error: unknown): Promise<FailureKind> {
271
+ if (isSwitch(error)) return "signIn";
272
+ if (!await isSignedIn()) return "signIn";
273
+ // A chat-web helper wraps the transport's failure: the cause is what says offline or refused.
274
+ const cause = (error as { cause?: unknown } | null)?.cause ?? error;
275
+ const kind = classifyLoadError(cause, "signedIn");
276
+ return kind === "membership" ? "permission" : kind;
277
+ }
278
+
279
+ // ---------------------------------------------------------------------------------------------------------------------
280
+ // Rows
281
+ // ---------------------------------------------------------------------------------------------------------------------
282
+ const fallbackTitle = () => copyParam("inbox.conversationFallback", "Conversation");
283
+ const yesterdayWord = () => copyParam("inbox.yesterdayLabel", "Yesterday");
284
+
285
+ function rowsOf(items: unknown[], mode: Mode, unreadIds: readonly string[] = []): Row[] {
286
+ for (const item of items) {
287
+ const id = (item as { id?: unknown } | null)?.id;
288
+ const sequence = lastSequenceOf(item);
289
+ if (typeof id === "string" && sequence !== undefined) sequences.set(id, sequence);
290
+ }
291
+ return inboxRows(items, fallbackTitle(), { scope: mode, yesterday: yesterdayWord(), unreadIds: new Set(unreadIds) }).map(strip);
292
+ }
293
+
294
+ const hasRow = (s: S, id: string): boolean => s.conversations.some((r) => r.id === id) || s.businessRow?.id === id;
295
+ const findRow = (s: S, id: string): { row: Row; index: number } | undefined => {
296
+ const index = s.conversations.findIndex((r) => r.id === id);
297
+ if (index >= 0) return { row: s.conversations[index]!, index };
298
+ return s.businessRow?.id === id ? { row: s.businessRow, index: -1 } : undefined;
299
+ };
300
+ /** Sets the read state of the room with this id, on the row as it is NOW (a refresh may have given it a newer message). */
301
+ function patchRead(s: S, id: string, unread: boolean, count: number): S {
302
+ return shape({
303
+ ...s,
304
+ conversations: s.conversations.map((r) => (r.id === id ? withRead(r, unread, count) : r)),
305
+ businessRow: s.businessRow?.id === id ? withRead(s.businessRow, unread, count) : s.businessRow,
306
+ });
307
+ }
308
+ const removeRow = (s: S, id: string): S => shape({ ...s, conversations: s.conversations.filter((r) => r.id !== id) });
309
+ function insertRow(s: S, row: Row, index: number): S {
310
+ if (hasRow(s, row.id)) return s;
311
+ const at = Math.max(0, Math.min(index, s.conversations.length));
312
+ return shape({ ...s, conversations: [...s.conversations.slice(0, at), row, ...s.conversations.slice(at)] });
313
+ }
314
+
315
+ /** The business's room opens where the host says (`businessScreenId`): a site shell opens it as a thread. The room is
316
+ * still found by its own screen id first, so this runs on the rows the screen gets, never before the lookup. */
317
+ function routed<T extends Pick<Row, "screenId" | "kind">>(row: T): T {
318
+ if (row.screenId !== BUSINESS_SCREEN || businessScreenId === BUSINESS_SCREEN) return row;
319
+ return { ...row, screenId: businessScreenId as Row["screenId"], kind: businessScreenId === "himi_chat_thread" ? "chatroom" : row.kind };
320
+ }
321
+
322
+ /** Lifts the business's room out of the rows (inbox mode, and only when the screen pins it: `pinBusinessRoom`). */
323
+ function withoutBusiness(rows: Row[], mode: Mode, known: Row | null): { list: Row[]; business: Row | null } {
324
+ if (mode !== "inbox" || !pinBusiness) return { list: rows.map(routed), business: null };
325
+ const business = rows.find((r) => r.screenId === BUSINESS_SCREEN) ?? known;
326
+ return { list: rows.filter((r) => r.screenId !== BUSINESS_SCREEN), business: business && routed(business) };
327
+ }
328
+
329
+ const applyPending = (s: S): S => {
330
+ let next = s;
331
+ for (const plan of landed) next = plan.apply(next);
332
+ for (const plan of pending.values()) next = plan.apply(next);
333
+ return next;
334
+ };
335
+
336
+ /** The list as the server answered, over what the member already did: a write still in flight is not undone by a
337
+ * refresh that was read before it landed. */
338
+ function present(base: S, mode: Mode, rows: Row[], nextPointer: number | string | undefined): S {
339
+ const flags = loaded("conversations", rows, COPY);
340
+ if (mode === "archive" && !flags.isMock && flags.conversations.length > 0) archiveKnown = true;
341
+ const { list, business } = withoutBusiness(flags.conversations, mode, null);
342
+ for (const plan of pending.values()) {
343
+ if (!plan.listed) continue;
344
+ for (const row of business ? [...list, business] : list) if (plan.id === row.id || plan.id === "*all") plan.listed.set(row.id, row);
345
+ }
346
+ return shape(applyPending({
347
+ ...base, ...flags,
348
+ conversations: list, businessRow: business, mode,
349
+ hasArchived: archiveNow() || (mode === "archive" && list.length > 0),
350
+ nextCursor: nextPointer === undefined ? "" : String(nextPointer), failedCursor: "",
351
+ errorKind: "", refreshError: false,
352
+ }));
353
+ }
354
+
355
+ /** The list could not be shown at all: nothing to keep (or access is gone), so an error with its recovery. */
356
+ function failedState(base: S, kind: FailureKind): S {
357
+ if (kind === "signIn") return signedOutState();
358
+ const flags = loadFailed("conversations", new Error("inbox load failed"), COPY);
359
+ return shape({
360
+ ...base, ...flags,
361
+ ...(flags.isMock ? {} : { error: loadText(kind) }),
362
+ conversations: flags.conversations, businessRow: null, nextCursor: "", failedCursor: "", errorKind: kind, refreshError: false,
363
+ });
364
+ }
365
+
366
+ // ---------------------------------------------------------------------------------------------------------------------
367
+ // Loading
368
+ // ---------------------------------------------------------------------------------------------------------------------
369
+ const modeOf = (arg: unknown): Mode | undefined => {
370
+ const mode = (arg as { mode?: unknown } | null)?.mode;
371
+ return mode === "archive" || mode === "archived" ? "archive" : mode === "inbox" ? "inbox" : undefined;
372
+ };
373
+ const textOf = (arg: unknown, ...keys: string[]): string => {
374
+ if (typeof arg === "string") return arg.trim();
375
+ for (const key of keys) {
376
+ const value = (arg as Record<string, unknown> | null)?.[key];
377
+ if (typeof value === "string") return value.trim();
378
+ }
379
+ return "";
380
+ };
381
+ const idOf = (arg: unknown): string => textOf(arg, "id");
382
+
383
+ const PIN = new Set(["1", "true"]);
384
+ /** `undefined` = nothing to publish: a superseded read returns it rather than a snapshot, because the runtime replaces the
385
+ * whole state with what an action returns and a snapshot taken now would overwrite what the newer read publishes next. */
386
+ async function loadList(s: S, arg: unknown, retry: boolean): Promise<S | undefined> {
387
+ stashCopy(arg);
388
+ const screen = (arg as { businessScreenId?: unknown } | null)?.businessScreenId;
389
+ if (typeof screen === "string" && /^[a-z0-9_]+$/.test(screen)) businessScreenId = screen;
390
+ const pin = (arg as { pinBusinessRoom?: unknown } | null)?.pinBusinessRoom;
391
+ if (pin !== undefined) pinBusiness = pin === true || (typeof pin === "string" && PIN.has(pin));
392
+ const paged = (arg as { pagedList?: unknown } | null)?.pagedList;
393
+ if (paged !== undefined) pagedList = paged === true || (typeof paged === "string" && PIN.has(paged));
394
+ // Another account than the one the screen was showing: nothing of the previous member's is kept.
395
+ let switched = false;
396
+ let gen = -1;
397
+ try {
398
+ const identity = await chatIdentity();
399
+ if (!identity.authenticated) return signedOutState();
400
+ const key = `${identity.email}|${identity.scope}`;
401
+ switched = ownerKey !== "" && ownerKey !== key;
402
+ if (switched) forgetMember();
403
+ gen = ++loadGen;
404
+ landed.length = 0;
405
+ const mode = modeOf(arg) ?? (switched ? INITIAL : live(s)).mode;
406
+ const page = pagedList ? await listInboxPage(identity, { archived: mode === "archive" }) : await listEveryPage(identity, mode === "archive");
407
+ // A newer load owns the screen now; a sign-out or account switch meanwhile is the fence's MemberAccessChanged.
408
+ if (gen !== loadGen) return undefined;
409
+ const next = present(switched ? INITIAL : live(s), mode, rowsOf(page.items, mode, page.unreadIds), page.nextPointer);
410
+ // Only now is this member's list the one on screen; until then writes for the previous member's rows are refused.
411
+ ownerKey = key;
412
+ // Only a redesigned screen (it opts in to pinning or paging) shows the archive entry; the stock screen is spared the request.
413
+ if (mode === "inbox" && (pinBusiness || pagedList)) void probeArchive(identity, gen, epoch);
414
+ // A pinned business room older than the first page: look for it in the later pages, without adding their rows.
415
+ if (mode === "inbox" && pagedList && pinBusiness && !next.businessRow && noBusinessRoomFor !== key && page.nextPointer !== undefined && page.nextPointer !== "") {
416
+ void findBusinessRoom(identity, gen, epoch, String(page.nextPointer));
417
+ }
418
+ return next;
419
+ } catch (error) {
420
+ const kind = await kindOf(error);
421
+ // A load that was superseded (or whose member went away) while it failed says nothing about the screen now.
422
+ if (gen !== -1 && gen !== loadGen) return undefined;
423
+ if (isSwitch(error) && !retry && await isSignedIn()) {
424
+ forgetMember();
425
+ return loadList(INITIAL, arg, true);
426
+ }
427
+ const base = switched ? INITIAL : live(s);
428
+ const asked = modeOf(arg) ?? base.mode;
429
+ const keep = asked === base.mode && (base.conversations.length > 0 || base.businessRow !== null);
430
+ if (keep && pagedList && (kind === "offline" || kind === "server")) return shape({ ...base, refreshError: true, errorKind: kind, error: loadText(kind) });
431
+ return failedState({ ...base, mode: asked }, kind);
432
+ }
433
+ }
434
+
435
+ /** A screen that does not page the list gets all of it, as the worker always gave it: at most MAX_LIST_PAGES pages. */
436
+ const MAX_LIST_PAGES = 67;
437
+ async function listEveryPage(identity: ChatIdentity, archived: boolean): Promise<InboxPage> {
438
+ const items: InboxPage["items"] = [];
439
+ const unreadIds: string[] = [];
440
+ let cursor: string | undefined;
441
+ for (let page = 0; page < MAX_LIST_PAGES; page++) {
442
+ const answer = await listInboxPage(identity, { archived, ...(cursor ? { cursor } : {}) });
443
+ items.push(...answer.items);
444
+ unreadIds.push(...answer.unreadIds);
445
+ if (answer.nextPointer === undefined || answer.nextPointer === "") return { items, unreadIds };
446
+ cursor = String(answer.nextPointer);
59
447
  }
60
448
  throw new Error("Conversation list is longer than the pages read");
61
449
  }
62
450
 
63
- const svc = defineService<S, { load: (s: S, arg?: unknown) => Promise<S> }>("himiBrandedInbox", {
64
- state: { ...LOADING, conversations: [], emptyText: "" },
451
+ /** Reads the later pages for the business's room only (at most MAX_LIST_PAGES), and pins it when this list is still the
452
+ * one on screen. The rows of those pages stay for `loadMore`; a failure leaves the pinned slot as it is. */
453
+ async function findBusinessRoom(identity: ChatIdentity, gen: number, runEpoch: number, from: string): Promise<void> {
454
+ let cursor = from;
455
+ try {
456
+ for (let page = 1; page < MAX_LIST_PAGES && cursor; page++) {
457
+ const answer = await listInboxPage(identity, { archived: false, cursor });
458
+ if (gen !== loadGen || runEpoch !== epoch) return;
459
+ const business = rowsOf(answer.items, "inbox", answer.unreadIds).find((r) => r.screenId === BUSINESS_SCREEN);
460
+ if (business) { void svc.businessFound(routed(business)); return; }
461
+ cursor = answer.nextPointer === undefined ? "" : String(answer.nextPointer);
462
+ }
463
+ if (!cursor) noBusinessRoomFor = `${identity.email}|${identity.scope}`;
464
+ } catch { /* the pinned slot keeps what it was */ }
465
+ }
466
+
467
+ /** Is there an archive to go to? Asked after the list is on screen, never in its way; a failure is "not known". An answer
468
+ * read before an archive write was started or confirmed is not the answer now, so it is dropped. */
469
+ async function probeArchive(identity: ChatIdentity, gen: number, runEpoch: number): Promise<void> {
470
+ const edits = archiveEdits;
471
+ try {
472
+ const has = await hasArchivedRooms(identity);
473
+ if ((gen !== loadGen && gen !== -1) || runEpoch !== epoch || edits !== archiveEdits) return;
474
+ archiveKnown = has;
475
+ void svc.archiveProbed(has);
476
+ } catch { /* the entry keeps what it was */ }
477
+ }
478
+
479
+ async function probeArchiveNow(): Promise<void> {
480
+ const runEpoch = epoch;
481
+ try { await probeArchive(await memberOnScreen(), -1, runEpoch); } catch { /* the entry keeps what it was */ }
482
+ }
483
+
484
+ /** Is `cursor` still where this list continues? A refresh that published meanwhile moved it. */
485
+ const stillAfter = (s: S, cursor: string): boolean => s.nextCursor === cursor || s.failedCursor === cursor;
486
+ async function loadMoreFrom(s: S, cursor: string): Promise<S | undefined> {
487
+ if (!cursor || moreInFlight) return s;
488
+ moreInFlight = true;
489
+ const gen = loadGen, runEpoch = epoch, mode = s.mode;
490
+ try {
491
+ const identity = await memberOnScreen();
492
+ const page = await listInboxPage(identity, { archived: mode === "archive", cursor });
493
+ const base = live(s);
494
+ // The list was reloaded, switched or reset while this page was coming: it is not this list's next page.
495
+ if (gen !== loadGen || runEpoch !== epoch || base.mode !== mode || !stillAfter(base, cursor)) return undefined;
496
+ const seen = new Set([...base.conversations.map((r) => r.id), ...(base.businessRow ? [base.businessRow.id] : [])]);
497
+ const fresh = rowsOf(page.items, mode, page.unreadIds).filter((r) => !seen.has(r.id));
498
+ const { list, business } = withoutBusiness(fresh, mode, base.businessRow);
499
+ return shape(applyPending({
500
+ ...base, conversations: [...base.conversations, ...list], businessRow: business,
501
+ nextCursor: page.nextPointer === undefined ? "" : String(page.nextPointer), failedCursor: "",
502
+ }));
503
+ } catch (error) {
504
+ const kind = await kindOf(error);
505
+ // The state AFTER the await: a write the member made meanwhile is in it.
506
+ const base = live(s);
507
+ if (gen !== loadGen || runEpoch !== epoch || !stillAfter(base, cursor)) return undefined;
508
+ // A lost access clears the rows with the error; a broken page 2 keeps page 1 and offers its own retry.
509
+ if (kind === "offline" || kind === "server") return shape({ ...base, nextCursor: "", failedCursor: cursor });
510
+ return kind === "signIn" && isSwitch(error) ? signedOutThenReload() : failedState(base, kind);
511
+ } finally {
512
+ moreInFlight = false;
513
+ }
514
+ }
515
+
516
+ // ---------------------------------------------------------------------------------------------------------------------
517
+ // Writes: optimistic update, Undo, rollback
518
+ // ---------------------------------------------------------------------------------------------------------------------
519
+ type RemoveVerb = "archive" | "unarchive" | "delete";
520
+ const removeCall = (verb: RemoveVerb, id: string) => (identity: ChatIdentity): Promise<void> =>
521
+ verb === "delete" ? deleteRoom(identity, id) : setRoomArchived(identity, id, verb === "archive");
522
+
523
+ /** The room leaves the list it is in (archived, restored from the archive, or deleted). */
524
+ function removalPlan(verb: RemoveVerb, row: Row, index: number, mode: Mode): Plan {
525
+ const here = (s: S) => s.mode === mode;
526
+ const archives = verb === "archive";
527
+ const message = archives ? copyParam("inbox.archivedMessage", "Conversation archived") : copyParam("inbox.unarchivedMessage", "Conversation moved to your inbox");
528
+ return {
529
+ id: row.id, mode, call: removeCall(verb, row.id), archives, unarchives: verb === "unarchive",
530
+ apply: (s) => (here(s) ? removeRow(archives ? { ...s, hasArchived: true } : s, row.id) : archives ? { ...s, hasArchived: true } : s),
531
+ // The archive entry follows what is settled (a confirmed archive, the probe, other archives still going), never a snapshot.
532
+ revert: (s) => { const back = here(s) ? insertRow(s, row, index) : s; return archives ? { ...back, hasArchived: archiveNow() } : back; },
533
+ ...(verb === "delete" ? {} : { undo: restorationPlan(verb === "archive" ? "unarchive" : "archive", row, index, mode), undoKind: verb, undoMessage: message }),
534
+ };
535
+ }
536
+ /** Undo of a removal: the room comes back where it was and the opposite request goes out. Not itself undoable. */
537
+ function restorationPlan(verb: "archive" | "unarchive", row: Row, index: number, mode: Mode): Plan {
538
+ const here = (s: S) => s.mode === mode;
539
+ const archives = verb === "archive";
540
+ return {
541
+ id: row.id, mode, call: removeCall(verb, row.id), archives, unarchives: verb === "unarchive",
542
+ apply: (s) => (here(s) ? insertRow(archives ? { ...s, hasArchived: true } : s, row, index) : archives ? { ...s, hasArchived: true } : s),
543
+ revert: (s) => { const back = here(s) ? removeRow(s, row.id) : s; return archives ? { ...back, hasArchived: archiveNow() } : back; },
544
+ };
545
+ }
546
+
547
+ /** The room's read state flips. Undo flips it back. */
548
+ /** What a refused read write puts back: the row at the tap, unless a refresh while it was pending saw NEW messages (the
549
+ * room unread with a higher count). Only that is taken from the refresh: a listing may predate a write that already landed,
550
+ * or reflect this very write, so its read state is never trusted on its own. */
551
+ function rollbackTo(from: Row, listed: Row | undefined): Pick<Row, "unread" | "unreadCount"> {
552
+ return listed && listed.unread && listed.unreadCount > from.unreadCount ? listed : from;
553
+ }
554
+
555
+ function readPlan(verb: "read" | "unread", from: Row, to: Row, mode: Mode, undoable: boolean): Plan {
556
+ const listed = new Map<string, Row>();
557
+ const call = (identity: ChatIdentity) => (verb === "read" ? markRoomRead(identity, from.id, sequences.get(from.id)) : markRoomUnread(identity, from.id));
558
+ return {
559
+ id: from.id, mode, call,
560
+ apply: (s) => patchRead(s, from.id, to.unread, to.unreadCount),
561
+ listed,
562
+ revert: (s) => { const back = rollbackTo(from, listed.get(from.id)); return patchRead(s, from.id, back.unread, back.unreadCount); },
563
+ ...(undoable ? {
564
+ undo: readPlan(verb === "read" ? "unread" : "read", to, from, mode, false),
565
+ undoKind: verb === "read" ? "markRead" : "markUnread",
566
+ undoMessage: verb === "read" ? copyParam("inbox.markedReadMessage", "Marked as read") : copyParam("inbox.markedUnreadMessage", "Marked as unread"),
567
+ } : {}),
568
+ };
569
+ }
570
+
571
+ /** Every unread room on screen reads; one request marks them all. */
572
+ function allReadPlan(s: S, mode: Mode): Plan {
573
+ const before = [...s.conversations, ...(s.businessRow ? [s.businessRow] : [])].filter((r) => r.unread);
574
+ const listed = new Map<string, Row>();
575
+ return {
576
+ id: "*all", mode, call: markAllRoomsRead, listed,
577
+ apply: (state) => before.reduce((next, row) => patchRead(next, row.id, false, 0), state),
578
+ revert: (state) => before.reduce((next, row) => { const back = rollbackTo(row, listed.get(row.id)); return patchRead(next, row.id, back.unread, back.unreadCount); }, state),
579
+ };
580
+ }
581
+
582
+ const clearUndo = (s: S): S => shape({ ...s, undoKind: "", undoRoomId: "", undoMessage: "" });
583
+
584
+ /** Paints the write's effect, remembers how to take it back, and starts the request. One request per room in flight: a
585
+ * second write on the same room while the first is pending is ignored (the contract's rule; the swipe gates flip with
586
+ * the first write's paint, so the screen does not offer a conflicting one). Mark-all-read covers every room's read
587
+ * state, so it and a per-room read or unread write never run together either: each one's rollback would overwrite the
588
+ * other's result. */
589
+ function startWrite(s: S, plan: Plan): S {
590
+ const readsState = (p: Plan): boolean => p.listed !== undefined;
591
+ for (const other of pending.values()) {
592
+ if (other.id === plan.id) return s;
593
+ if (readsState(plan) && readsState(other) && (plan.id === "*all" || other.id === "*all")) return s;
594
+ }
595
+ const opId = ++opSeq;
596
+ pending.set(opId, plan);
597
+ if (plan.archives || plan.unarchives) archiveEdits++;
598
+ lastUndo = plan.undo;
599
+ void sendWrite(opId, plan, epoch);
600
+ const painted = plan.apply({ ...s, actionError: "" });
601
+ return plan.undo
602
+ ? shape({ ...painted, undoKind: plan.undoKind ?? "", undoRoomId: plan.id, undoMessage: plan.undoMessage ?? "" })
603
+ : clearUndo(painted);
604
+ }
605
+
606
+ /** The request. Never throws: it reports how it ended. The caller has already painted the change. */
607
+ async function sendWrite(opId: number, plan: Plan, runEpoch: number): Promise<void> {
608
+ let outcome: "ok" | FailureKind = "ok";
609
+ try {
610
+ await Promise.resolve();
611
+ if (!samplesRequested()) await plan.call(await memberOnScreen());
612
+ } catch (error) {
613
+ outcome = await kindOf(error);
614
+ }
615
+ if (runEpoch === epoch) void svc.settleWrite({ opId, outcome });
616
+ }
617
+
618
+ const refuse = (s: S, message: string): S => shape({ ...s, actionError: message });
619
+
620
+ /** The room an action names, if it is on screen. */
621
+ function target(s: S, arg: unknown): { row: Row; index: number } | undefined {
622
+ const id = idOf(arg);
623
+ return id ? findRow(s, id) : undefined;
624
+ }
625
+
626
+ // ---------------------------------------------------------------------------------------------------------------------
627
+ // Search
628
+ // ---------------------------------------------------------------------------------------------------------------------
629
+ interface SearchSettle { seq: number; append: boolean; kind: "ok" | FailureKind; page?: SearchPage }
630
+
631
+ function knownRooms(s: S): Map<string, InboxRow> {
632
+ const rows = [...s.conversations, ...(s.businessRow ? [s.businessRow] : [])];
633
+ return new Map(rows.map((r): [string, InboxRow] => [r.id, { ...r, at: 0 }]));
634
+ }
635
+
636
+ async function runSearch(seq: number, query: string, cursors: { chats?: string; messages?: string }, append: boolean, runEpoch: number): Promise<void> {
637
+ let result: SearchSettle;
638
+ try {
639
+ await Promise.resolve();
640
+ const raw = await searchInbox(await memberOnScreen(), query, cursors);
641
+ result = { seq, append, kind: "ok", page: readSearch(raw, { fallbackTitle: fallbackTitle(), yesterday: yesterdayWord(), knownRooms: knownRooms(svc.getState()) }) };
642
+ } catch (error) {
643
+ result = { seq, append, kind: await kindOf(error) };
644
+ }
645
+ if (runEpoch === epoch && seq === searchSeq) void svc.searchSettled(result);
646
+ }
647
+
648
+ const SEARCH_CLEARED = {
649
+ query: "", searchStatus: "idle" as const, searchChats: [] as Row[], searchMessages: [] as SearchHit[],
650
+ searchError: "", searchErrorKind: "" as ErrorKind, searchMoreError: false, searchChatsCursor: "", searchMessagesCursor: "",
651
+ };
652
+
653
+ // ---------------------------------------------------------------------------------------------------------------------
654
+ const svc = defineService<S, {
655
+ /** The screen's onAppear (carries the copy pack; `mode` = "archive" | "inbox" picks the list). Retry sends no params. */
656
+ load: (s: S, arg?: unknown) => Promise<S | undefined>;
657
+ loadMore: (s: S) => Promise<S | undefined>;
658
+ retryLoadMore: (s: S) => Promise<S | undefined>;
659
+ showArchived: (s: S) => S;
660
+ showInbox: (s: S) => S;
661
+ archive: (s: S, arg?: unknown) => S;
662
+ unarchive: (s: S, arg?: unknown) => S;
663
+ markRead: (s: S, arg?: unknown) => S;
664
+ markUnread: (s: S, arg?: unknown) => S;
665
+ delete: (s: S, arg?: unknown) => S;
666
+ markAllRead: (s: S) => S;
667
+ undo: (s: S) => S;
668
+ dismissUndo: (s: S) => S;
669
+ dismissActionError: (s: S) => S;
670
+ search: (s: S, arg?: unknown) => S;
671
+ searchLoadMore: (s: S) => S;
672
+ searchRetryMore: (s: S) => S;
673
+ clearSearch: (s: S) => S;
674
+ /** Internal: a request reports back. */
675
+ settleWrite: (s: S, result?: { opId: number; outcome: "ok" | FailureKind }) => S | undefined;
676
+ searchSettled: (s: S, result?: SearchSettle) => S | undefined;
677
+ archiveProbed: (s: S, has?: boolean) => S | undefined;
678
+ businessFound: (s: S, row?: Row) => S | undefined;
679
+ }>("himiBrandedInbox", {
680
+ state: INITIAL,
681
+ // A cold boot never restores the previous run's rooms: they are the previous run's member's.
682
+ notHydrated: Object.keys(INITIAL) as (keyof S & string)[],
65
683
  actions: {
66
- load: async (s, arg) => {
67
- // The screen's onAppear carries the copy pack (Hebrew, an owner's wording). This service is not a collection, so
68
- // nothing else stashes it; a retry sends no params and keeps the pack already stashed.
69
- stashCopy(arg);
70
- const target = (arg as { businessScreenId?: unknown } | undefined)?.businessScreenId;
71
- if (typeof target === "string" && /^[a-z0-9_]+$/.test(target)) businessScreenId = target;
72
- try {
73
- const member = await memberAccess();
74
- if (!member.email) throw signInRequired();
75
- const rows = inboxRows(await listAllRooms(), copyParam("inbox.conversationFallback", "Conversation"))
76
- .map(({ at: _at, ...row }) => row.screenId === "himi_business_chat" && businessScreenId !== row.screenId
77
- ? { ...row, screenId: businessScreenId as Row["screenId"], kind: businessScreenId === "himi_chat_thread" ? "chatroom" : row.kind }
78
- : row);
79
- // A sign-out or account switch while the list loaded must not paint the previous member's rooms.
80
- await assertMemberAccess(member);
81
- return { ...s, ...loaded("conversations", rows, COPY) };
82
- } catch (err) {
83
- const failed = loadFailed("conversations", (await memberAccess()).email ? err : signInRequired(), COPY);
84
- // The failure sentence is the screen banner's stock key, not a second key for the same English (the extractor
85
- // keeps one key per extracted row); loadFailed would read `inbox.errorText`, which does not exist.
86
- return { ...s, ...failed, ...(failed.signInRequired ? {} : { error: copyParam("inbox.unavailableBody", COPY.error) }) };
684
+ load: (s, arg) => loadList(s, arg, false),
685
+ loadMore: (s) => loadMoreFrom(s, s.nextCursor),
686
+ retryLoadMore: (s) => loadMoreFrom(s, s.failedCursor),
687
+
688
+ // Switching list repaints at once (loading, no rows of the other list) and loads it.
689
+ showArchived: (s) => { void svc.load({ mode: "archive" }); lastUndo = undefined; return shape({ ...s, undoKind: "", undoRoomId: "", undoMessage: "", ...LOADING, mode: "archive", conversations: [], emptyText: "", businessRow: null, nextCursor: "", failedCursor: "", errorKind: "", refreshError: false }); },
690
+ showInbox: (s) => { void svc.load({ mode: "inbox" }); lastUndo = undefined; return shape({ ...s, undoKind: "", undoRoomId: "", undoMessage: "", ...LOADING, mode: "inbox", conversations: [], emptyText: "", businessRow: null, nextCursor: "", failedCursor: "", errorKind: "", refreshError: false }); },
691
+
692
+ archive: (s, arg) => {
693
+ const found = target(s, arg);
694
+ // The inbox's rooms are archived; the business's pinned room and the archive's own rooms are not.
695
+ if (!found || s.mode !== "inbox" || found.index < 0) return found ? refuse(s, actionText("server")) : s;
696
+ return startWrite(s, removalPlan("archive", found.row, found.index, s.mode));
697
+ },
698
+ unarchive: (s, arg) => {
699
+ const found = target(s, arg);
700
+ if (!found || s.mode !== "archive" || found.index < 0) return s;
701
+ return startWrite(s, removalPlan("unarchive", found.row, found.index, s.mode));
702
+ },
703
+ markRead: (s, arg) => {
704
+ const found = target(s, arg);
705
+ if (!found || !found.row.unread) return s;
706
+ return startWrite(s, readPlan("read", found.row, withRead(found.row, false, 0), s.mode, true));
707
+ },
708
+ markUnread: (s, arg) => {
709
+ const found = target(s, arg);
710
+ if (!found || found.row.unread) return s;
711
+ return startWrite(s, readPlan("unread", found.row, withRead(found.row, true, 0), s.mode, true));
712
+ },
713
+ // Only a private room can be deleted by a member; the business's pinned room never. There is no Undo: deleting is final,
714
+ // so the screen asks first.
715
+ delete: (s, arg) => {
716
+ const found = target(s, arg);
717
+ if (!found) return s;
718
+ if (!found.row.isPrivate || found.index < 0) return refuse(s, copyParam("inbox.deleteRefusedText", "This conversation can't be deleted."));
719
+ return startWrite(s, removalPlan("delete", found.row, found.index, s.mode));
720
+ },
721
+ markAllRead: (s) => (s.hideMarkAllRead ? s : startWrite(s, allReadPlan(s, s.mode))),
722
+
723
+ // Undo is a write of its own: the room comes back at once and the opposite request goes out.
724
+ undo: (s) => {
725
+ const plan = lastUndo;
726
+ if (!plan) return clearUndo(s);
727
+ // The first request is still going: Undo stays on offer for a second tap.
728
+ for (const other of pending.values()) if (other.id === plan.id) return s;
729
+ lastUndo = undefined;
730
+ return startWrite(clearUndo(s), plan);
731
+ },
732
+ dismissUndo: (s) => { lastUndo = undefined; return clearUndo(s); },
733
+ dismissActionError: (s) => shape({ ...s, actionError: "" }),
734
+
735
+ search: (s, arg) => {
736
+ const query = textOf(arg, "query", "value", "text");
737
+ if (!query) { searchSeq++; searchMoreInFlight = false; return shape({ ...s, ...SEARCH_CLEARED }); }
738
+ const seq = ++searchSeq;
739
+ searchMoreInFlight = false;
740
+ void runSearch(seq, query, {}, false, epoch);
741
+ // A new query starts over; the same query again (a retry) keeps nothing either, so it can never show stale rows.
742
+ return shape({ ...s, ...SEARCH_CLEARED, query, searchStatus: "loading" });
743
+ },
744
+ searchLoadMore: (s) => {
745
+ if (!s.query || s.searchMoreError || searchMoreInFlight || (!s.searchChatsCursor && !s.searchMessagesCursor)) return s;
746
+ searchMoreInFlight = true;
747
+ void runSearch(searchSeq, s.query, { chats: s.searchChatsCursor, messages: s.searchMessagesCursor }, true, epoch);
748
+ return s;
749
+ },
750
+ searchRetryMore: (s) => {
751
+ if (!s.searchMoreError) return s;
752
+ searchMoreInFlight = true;
753
+ void runSearch(searchSeq, s.query, { chats: s.searchChatsCursor, messages: s.searchMessagesCursor }, true, epoch);
754
+ return shape({ ...s, searchMoreError: false });
755
+ },
756
+ clearSearch: (s) => { searchSeq++; searchMoreInFlight = false; return shape({ ...s, ...SEARCH_CLEARED }); },
757
+
758
+ settleWrite: (s, result) => {
759
+ const plan = result ? pending.get(result.opId) : undefined;
760
+ if (!result || !plan) return undefined;
761
+ pending.delete(result.opId);
762
+ if (result.outcome === "ok") {
763
+ if (plan.archives) archiveKnown = true;
764
+ if (plan.archives || plan.unarchives) archiveEdits++;
765
+ // The archive may be empty now: ask.
766
+ if (plan.unarchives) void probeArchiveNow();
767
+ landed.push(plan);
768
+ if (landed.length > MAX_LANDED) landed.shift();
769
+ return undefined;
770
+ }
771
+ // Wix refused (or the member is gone): the room is back as it was, with a sentence that says why.
772
+ // Another account may be signed in now: load for whoever it is.
773
+ if (result.outcome === "signIn") return signedOutThenReload();
774
+ if (lastUndo && lastUndo === plan.undo) lastUndo = undefined;
775
+ const reverted = plan.revert(s);
776
+ const undoLost = plan.undo !== undefined && s.undoRoomId === plan.id;
777
+ return shape({ ...(undoLost ? clearUndo(reverted) : reverted), actionError: actionText(result.outcome) });
778
+ },
779
+
780
+ searchSettled: (s, result) => {
781
+ if (!result || result.seq !== searchSeq) return undefined;
782
+ searchMoreInFlight = false;
783
+ if (result.kind !== "ok" || !result.page) {
784
+ const kind = result.kind === "ok" ? "server" : result.kind;
785
+ if (kind === "signIn") return signedOutThenReload();
786
+ // A page 2 that fails keeps page 1 and offers its own retry; a first page that fails is the error.
787
+ if (result.append) return shape({ ...s, searchMoreError: true });
788
+ return shape({ ...s, ...SEARCH_CLEARED, query: s.query, searchStatus: "error", searchError: searchText(kind), searchErrorKind: kind });
87
789
  }
790
+ const { page } = result;
791
+ // A list the first pages already finished is not requested again by the server's reading (no cursor means page 1):
792
+ // what comes back for it is ignored and its cursor stays empty.
793
+ const chatsDone = result.append && s.searchChatsCursor === "";
794
+ const hitsDone = result.append && s.searchMessagesCursor === "";
795
+ // Search results open where the list rows open (a site shell routes the business room to the thread).
796
+ const chats = chatsDone ? [] : page.chats.map(strip).map(routed);
797
+ const hits = hitsDone ? [] : page.messages.map(routed);
798
+ const seenChats = new Set(s.searchChats.map((r) => r.id));
799
+ const seenHits = new Set(s.searchMessages.map((h) => h.id));
800
+ return shape({
801
+ ...s, searchStatus: "ready", searchError: "", searchErrorKind: "", searchMoreError: false,
802
+ searchChats: result.append ? [...s.searchChats, ...chats.filter((r) => !seenChats.has(r.id))] : chats,
803
+ searchMessages: result.append ? [...s.searchMessages, ...hits.filter((h) => !seenHits.has(h.id))] : hits,
804
+ searchChatsCursor: chatsDone ? "" : page.chatsCursor, searchMessagesCursor: hitsDone ? "" : page.messagesCursor,
805
+ });
88
806
  },
807
+
808
+ // Only into an inbox list that still has no business row (a loadMore may have reached it first).
809
+ businessFound: (s, row) => (row && s.mode === "inbox" && !s.businessRow && !s.conversations.some((r) => r.id === row.id)
810
+ ? shape(applyPending({ ...s, businessRow: row })) : undefined),
811
+ archiveProbed: (s, has) => { const now = archiveNow(); return now !== s.hasArchived ? shape({ ...s, hasArchived: now }) : undefined; },
89
812
  },
90
813
  });
91
814
  svc.load();