@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
@@ -4,7 +4,8 @@ import { defineService } from "@himalaya/state";
4
4
  import { withEmptyFlags } from "../_shared/empty-flags.js";
5
5
  import { queryMembers, type WixMember } from "@himalaya/wix-members";
6
6
 
7
- interface Row { id: string; name: string; subtitle: string; initial: string; photo: string }
7
+ /** `noPhoto`: the member has no photo, so the screen draws the initial instead (an Avatar with no photo would draw "?"). */
8
+ interface Row { id: string; name: string; subtitle: string; initial: string; photo: string; noPhoto: boolean }
8
9
  interface S { status: "loading" | "ready"; members: Row[]; emptyText: string }
9
10
 
10
11
  function name(m: WixMember): string {
@@ -22,7 +23,8 @@ const svc = defineService<S, { load: (s: S) => Promise<S> }>("spacesNewMessage",
22
23
  const r = await queryMembers({ query: { paging: { limit: 50 } } });
23
24
  const members = (r.members ?? []).map((m) => {
24
25
  const n = name(m);
25
- return { id: m.id, name: n, subtitle: m.loginEmail || "", initial: (n[0] || "#").toUpperCase(), photo: m.profile?.photo?.url || "" };
26
+ const photo = m.profile?.photo?.url || "";
27
+ return { id: m.id, name: n, subtitle: m.loginEmail || "", initial: (n[0] || "#").toUpperCase(), photo, noPhoto: !photo };
26
28
  });
27
29
  return { status: "ready", members, emptyText: members.length ? "" : "No members to message" };
28
30
  } catch { return { ...s, status: "ready", emptyText: "No members to message" }; }
@@ -0,0 +1,177 @@
1
+ /** Read-only presentation model. HTML stays text; remote actions require a separate dispatcher. */
2
+ export type PartKind = 'text' | 'image' | 'file' | 'audio' | 'video' | 'card' | 'form' | 'system' | 'unsupported';
3
+ export interface MessageButton { id: string; label: string; url: string; interactionId?: string; unavailableReason?: string }
4
+ export interface PartRow {
5
+ id: string; kind: PartKind; text: string; url: string; fileName: string; caption: string;
6
+ buttons?: MessageButton[]; fields?: { name: string; value: string }[];
7
+ mimeType?: string; iconUrl?: string; mediaId?: string; urlExpiration?: string; unavailableReason?: string;
8
+ mediaProvider?: string; thumbnailUrl?: string;
9
+ }
10
+ export interface MessageRow {
11
+ id: string; sequence: string; sender: string; senderId: string; when: string; createdDate: string;
12
+ mine: boolean; status: string; direction: string; parts: PartRow[]; plainText: string;
13
+ }
14
+ type Obj = Record<string, unknown>;
15
+ function obj(value: unknown): Obj { return value !== null && typeof value === 'object' && !Array.isArray(value) ? value as Obj : {}; }
16
+ function str(value: unknown): string { return typeof value === 'string' ? value : typeof value === 'number' && Number.isFinite(value) ? String(value) : ''; }
17
+ function first(...values: unknown[]): string { for (const value of values) { const s = str(value); if (s) return s; } return ''; }
18
+ function stable(value: unknown, ancestors: unknown[] = []): string {
19
+ if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? String(value);
20
+ if (ancestors.includes(value)) return '[circular]';
21
+ const next = [...ancestors, value];
22
+ return Array.isArray(value) ? '[' + value.map(v => stable(v, next)).join(',') + ']' : '{' + Object.keys(value as Obj).sort().map(k => JSON.stringify(k) + ':' + stable((value as Obj)[k], next)).join(',') + '}';
23
+ }
24
+ function hash(value: unknown): string {
25
+ const text = stable(value); let a = 2166136261; let b = 5381;
26
+ for (let i = 0; i < text.length; i++) { a = Math.imul(a ^ text.charCodeAt(i), 16777619); b = Math.imul(b, 33) ^ text.charCodeAt(i); }
27
+ return (a >>> 0).toString(16).padStart(8, '0') + (b >>> 0).toString(16).padStart(8, '0');
28
+ }
29
+ /** HTTPS only, no credentials/control characters/backslashes. Does not depend on worker URL globals. */
30
+ function safeUrl(value: unknown): string {
31
+ if (typeof value !== 'string' || /[\s\\\u0000-\u001f\u007f-\u009f]/u.test(value)) return '';
32
+ const match = /^https:\/\/([^/?#]+)(?:[/?#].*)?$/iu.exec(value);
33
+ if (!match) return '';
34
+ const authority = match[1];
35
+ if (authority.includes('@') || !/^(?:[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?|\[[0-9a-f:]+\])(?::[0-9]{1,5})?$/iu.test(authority)) return '';
36
+ const port = /:([0-9]+)$/.exec(authority);
37
+ if (port && Number(port[1]) > 65535) return '';
38
+ return value;
39
+ }
40
+ function htmlText(value: string): string {
41
+ // Output is plain text, never markup. No href/src extraction or HTML insertion.
42
+ return value.replace(/<!--[\s\S]*?-->/g, '').replace(/<(script|style)\b[^>]*>[\s\S]*?<\/\1\s*>/gi, '')
43
+ .replace(/<\s*br\s*\/?\s*>/gi, '\n').replace(/<\/(p|div|li|h[1-6])\s*>/gi, '\n').replace(/<[^>]*>/g, '')
44
+ .replace(/&(#x[0-9a-f]+|#[0-9]+|amp|lt|gt|quot|apos|nbsp);/gi, (whole, entity: string) => {
45
+ const names: Record<string, string> = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' };
46
+ if (entity[0] !== '#') return names[entity.toLowerCase()] ?? whole;
47
+ const n = entity[1]?.toLowerCase() === 'x' ? parseInt(entity.slice(2), 16) : Number(entity.slice(1));
48
+ return n > 0 && n <= 0x10ffff && !(n >= 0xd800 && n <= 0xdfff) ? String.fromCodePoint(n) : whole;
49
+ });
50
+ }
51
+ function base(id: string, kind: PartKind, text = ''): PartRow { return { id, kind, text, url: '', fileName: '', caption: '' }; }
52
+ function unsupported(id: string, value: unknown, reason = 'Unsupported message content'): PartRow {
53
+ return { ...base(id, 'unsupported', typeof value === 'string' ? value : stable(value)), caption: reason, unavailableReason: reason };
54
+ }
55
+ function media(id: string, kind: 'image' | 'file' | 'audio' | 'video', input: unknown): PartRow {
56
+ const m = obj(input); const candidate = first(m.url, m.uri, m.downloadUrl, m.src, typeof input === 'string' ? input : '');
57
+ const url = safeUrl(candidate); const mime = first(m.mimeType, m.contentType);
58
+ const resolvedKind = kind === 'file' && /^audio\//i.test(mime) ? 'audio' : kind === 'file' && /^video\//i.test(mime) ? 'video' : kind;
59
+ const missing = url ? '' : candidate ? 'Attachment URL is unavailable: only safe HTTPS links are supported.' : 'Attachment requires a download URL.';
60
+ return { ...base(id, resolvedKind, first(m.text, m.title)), url, fileName: first(m.filename, m.fileName, m.name), caption: first(m.caption, m.alt, missing), mimeType: mime, mediaId: first(m.mediaFileId, m.id, m._id, m.fileId), mediaProvider: str(m.mediaProvider), thumbnailUrl: safeUrl(m.thumbnailUrl), urlExpiration: str(m.urlExpiration), ...(missing ? { unavailableReason: missing } : {}) };
61
+ }
62
+ function buttons(value: unknown, prefix: string): MessageButton[] {
63
+ if (!Array.isArray(value)) return [];
64
+ return value.map((value, i) => {
65
+ const b = obj(value); const raw = first(b.launchUrl, b.url, b.href, obj(b.action).url); const url = safeUrl(raw);
66
+ const interactionId = first(obj(b.postbackProperties).interactionId, b.interactionId);
67
+ return { id: prefix + '-button-' + i, label: first(b.label, b.title, b.text, 'Action'), url,
68
+ ...(interactionId ? { interactionId } : {}),
69
+ ...(!url ? { unavailableReason: raw ? 'Only safe HTTPS links are supported.' : interactionId ? 'This interaction requires a supported server action.' : 'Action has no supported link.' } : {}) };
70
+ });
71
+ }
72
+ function card(id: string, input: unknown, kind: 'card' | 'form' | 'system' = 'card'): PartRow[] {
73
+ const c = obj(input); const lines = Array.isArray(c.textLines) ? c.textLines.map(str) : [];
74
+ const text = [first(c.title, c.name), first(c.text, c.description, c.body), ...lines].filter(Boolean).join('\n');
75
+ const fields = Array.isArray(c.fields) ? c.fields.map(f => ({ name: first(obj(f).name, obj(f).label), value: typeof obj(f).value === 'string' ? obj(f).value as string : stable(obj(f).value) })) : [];
76
+ const result: PartRow = { ...base(id, kind, text), buttons: buttons(c.buttons, id), ...(fields.length ? { fields } : {}) };
77
+ const image = first(c.imageUrl, c.iconUrl, obj(c.image).url, obj(c.image).uri);
78
+ if (image) { result.url = safeUrl(image); if (!result.url) result.unavailableReason = 'Card image requires a safe HTTPS URL.'; }
79
+ const parts = [result];
80
+ if (Array.isArray(c.media)) c.media.forEach((v, i) => parts.push(...basicItem(`${id}-media-${i}`, v)));
81
+ if (!text && !fields.length && !result.buttons?.length && !image && parts.length === 1) return [unsupported(id, input)];
82
+ return parts;
83
+ }
84
+ function basicItem(id: string, value: unknown): PartRow[] {
85
+ if (typeof value === 'string') return [base(id, 'text', value)];
86
+ const v = obj(value); const parts: PartRow[] = [];
87
+ if (typeof v.text === 'string') parts.push(base(id + '-text', 'text', v.text));
88
+ for (const kind of ['image', 'file', 'audio', 'video'] as const) if (v[kind] !== undefined && v[kind] !== null) parts.push(media(id + '-' + kind, kind, v[kind]));
89
+ for (const key of Object.keys(v).filter(k => !['text', 'image', 'file', 'audio', 'video', 'id', '_id', 'type'].includes(k))) parts.push(unsupported(id + '-extra-' + key, { [key]: v[key] }));
90
+ return parts.length ? parts : [unsupported(id, value)];
91
+ }
92
+ function publicParts(content: Obj, id: string): PartRow[] {
93
+ const parts: PartRow[] = [];
94
+ if (content.basic !== undefined) {
95
+ const items = obj(content.basic).items;
96
+ if (Array.isArray(items) && items.length) items.forEach((v, i) => parts.push(...basicItem(`${id}-basic-${i}`, v)));
97
+ else parts.push(unsupported(id + '-basic', content.basic));
98
+ }
99
+ for (const key of ['template', 'form', 'system'] as const) if (content[key] !== undefined) parts.push(...card(id + '-' + key, content[key], key === 'template' ? 'card' : key));
100
+ if (content.minimal !== undefined) {
101
+ const m = obj(content.minimal); const part = base(id + '-minimal', 'system', str(m.text)); const rawUrl = str(m.url);
102
+ if (rawUrl) { part.url = safeUrl(rawUrl); if (!part.url) part.unavailableReason = 'Only safe HTTPS links are supported.'; }
103
+ const icon = str(m.iconUrl);
104
+ if (icon) { part.iconUrl = safeUrl(icon); if (!part.iconUrl) part.caption = 'Activity icon requires a safe HTTPS URL.'; }
105
+ parts.push(part.text || part.url ? part : unsupported(part.id, content.minimal));
106
+ }
107
+ const unknown = Object.keys(content).filter(k => !['basic', 'template', 'form', 'system', 'minimal', 'title', 'previewText'].includes(k));
108
+ for (const key of unknown) parts.push(unsupported(id + '-content-' + key, { [key]: content[key] }));
109
+ return parts;
110
+ }
111
+ function chatPart(id: string, value: unknown): PartRow[] {
112
+ const v = obj(value); const mime = first(v.mimeType, v.contentType).toLowerCase().split(';')[0].trim(); const d = v.data;
113
+ const data = obj(d);
114
+ if (Array.isArray(data.cards)) return data.cards.length ? data.cards.flatMap((item, i) => card(`${id}-card-${i}`, item)) : [unsupported(id, value)];
115
+ if (mime === 'text/plain') return [base(id, 'text', typeof d === 'string' ? d : first(data.text, v.text))];
116
+ if (mime === 'text/html') return [{ ...base(id, 'text', htmlText(typeof d === 'string' ? d : first(data.html, data.text, v.text))), caption: 'HTML message shown as plain text' }];
117
+ // Branded chat separates the outer message-part kind from the file's MIME.
118
+ // mobile-apps-inbox MIME_TYPE: uri/image, uri/file; actual MIME lives in data.type.
119
+ if (mime === 'uri/image' || mime === 'uri/file') {
120
+ return [media(id, mime === 'uri/image' ? 'image' : 'file', typeof d === 'string' ? d : {
121
+ ...data, mimeType: first(data.type, data.mimeType, data.contentType),
122
+ })];
123
+ }
124
+ if (/^(image|audio|video)\//.test(mime)) {
125
+ const kind = mime.split('/')[0] as 'image' | 'audio' | 'video';
126
+ return [media(id, kind, typeof d === 'string' ? d : { ...data, mimeType: mime })];
127
+ }
128
+ if (/card|template|form|system/.test(mime)) {
129
+ let payload: unknown = d;
130
+ if (typeof payload === 'string') { try { payload = JSON.parse(payload); } catch { return [unsupported(id, payload)]; } }
131
+ return card(id, payload, /form/.test(mime) ? 'form' : /system/.test(mime) ? 'system' : 'card');
132
+ }
133
+ if (typeof d === 'string' && /^application\//.test(mime) && safeUrl(d)) return [media(id, 'file', { url: d, mimeType: mime })];
134
+ if (first(data.uri, data.url, data.downloadUrl) && (first(data.fileName, data.filename, data.name) || /^(application|text)\//.test(mime))) return [media(id, 'file', { ...data, mimeType: mime })];
135
+ return [unsupported(id, value, mime ? `Unsupported message part (${mime})` : 'Unsupported message part')];
136
+ }
137
+ function decimal(value: string): { negative: boolean; digits: string } | null {
138
+ if (!/^-?\d+$/.test(value)) return null;
139
+ const digits = value.replace(/^-/, '').replace(/^0+(?=\d)/, ''); return { negative: value[0] === '-' && digits !== '0', digits };
140
+ }
141
+ /** Exact decimal ordering, including int64 values beyond JavaScript's safe integer range. */
142
+ export function compareSequence(a: string, b: string): number {
143
+ const x = decimal(a); const y = decimal(b);
144
+ if (x && y) { if (x.negative !== y.negative) return x.negative ? -1 : 1; const n = x.digits.length === y.digits.length ? x.digits < y.digits ? -1 : x.digits > y.digits ? 1 : 0 : x.digits.length < y.digits.length ? -1 : 1; return x.negative ? -n : n; }
145
+ return a < b ? -1 : a > b ? 1 : 0;
146
+ }
147
+ function dateText(raw: unknown): string {
148
+ if (typeof raw === 'string') return raw;
149
+ if (typeof raw === 'number' && Number.isFinite(raw)) { const date = new Date(raw); return Number.isFinite(date.getTime()) ? date.toISOString() : ''; }
150
+ return '';
151
+ }
152
+ function normalize(value: unknown, myMemberId?: string): MessageRow {
153
+ const m = obj(value); const sender = obj(m.sender); const display = obj(m.senderDisplayData);
154
+ const id = typeof m.id === 'string' && m.id ? m.id : typeof m._id === 'string' && m._id ? m._id : typeof m.id === 'number' && Number.isSafeInteger(m.id) ? String(m.id) : 'local-' + hash(value);
155
+ const senderId = first(sender.memberId, sender.userId, sender.wixUserId, sender.contactId, sender.anonymousVisitorId, m.senderId);
156
+ const direction = str(m.direction); const senderName = first(display.name, obj(m.senderDisplayData).displayName, sender.name, typeof m.sender === 'string' ? m.sender : '', sender.type);
157
+ let parts: PartRow[] = publicParts(obj(m.content), id);
158
+ if (Array.isArray(m.data)) m.data.forEach((v, i) => parts.push(...chatPart(`${id}-chat-${i}`, v)));
159
+ if (!parts.length) { // A chat-web template message (a card) keeps its visible text in the top-level templateData.
160
+ const body = first(m.body, m.text, obj(m.templateData).text, m.summary, obj(m.content).previewText); parts = body ? [base(id + '-text', 'text', body)] : [unsupported(id + '-unknown', m.content ?? m.data ?? { messageType: m.messageType ?? 'unknown' })]; }
161
+ const sequence = typeof m.sequence === 'string' ? m.sequence : typeof m.sequence === 'number' && Number.isSafeInteger(m.sequence) ? String(m.sequence) : '';
162
+ const createdDate = dateText(m.createdDate ?? m._createdDate ?? m.createdAt);
163
+ const mine = !!myMemberId && [sender.memberId, sender.userId, sender.wixUserId, sender.contactId, sender.anonymousVisitorId, m.senderId].includes(myMemberId);
164
+ const status = first(m.status, m.deliveryStatus, obj(m.transit).status, obj(m.transit).state, 'stored');
165
+ return { id, sequence, sender: senderName || (senderId ? senderId : 'Unknown sender'), senderId, when: createdDate, createdDate, mine, status, direction, parts, plainText: parts.map(p => [p.text, ...(p.fields ?? []).map(f => `${f.name}: ${f.value}`), p.fileName || p.caption].filter(Boolean).join('\n')).filter(Boolean).join('\n') };
166
+ }
167
+ /** Newest representation replaces the same message ID; deterministic tie ordering never uses wall clock. */
168
+ export function mergeMessages(oldRows: MessageRow[], newRows: MessageRow[]): MessageRow[] {
169
+ const byId = new Map<string, MessageRow>(); for (const row of [...oldRows, ...newRows]) byId.set(row.id, row);
170
+ return [...byId.values()].sort((a, b) => {
171
+ if (!!a.sequence !== !!b.sequence) return a.sequence ? 1 : -1;
172
+ if (a.sequence && b.sequence) { const order = compareSequence(a.sequence, b.sequence); if (order) return order; }
173
+ if (a.createdDate !== b.createdDate) return a.createdDate < b.createdDate ? -1 : 1;
174
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
175
+ });
176
+ }
177
+ export function normalizeMessages(raw: unknown[], myMemberId?: string): MessageRow[] { return mergeMessages([], raw.map(value => normalize(value, myMemberId))); }
@@ -0,0 +1,164 @@
1
+ // The business chat's Wix calls: the member-role chat-web SDK for rooms and history, plus the calls the SDKs have
2
+ // no helper for (a typed message sent through Smart Chat, a tapped button, a private attachment's download URL).
3
+ import { getChatToken, getMessagesPage, listChatroomsPage } from "@himalaya/wix-chat-web";
4
+ import { assertMemberAccess, memberAccess } from "./member-access.js";
5
+
6
+ const MANAGE = "https://manage.wix.com";
7
+ const MEMBER = { role: "member" } as const;
8
+ type Raw = Record<string, unknown>;
9
+ type Bridge = { call(method: string, path: string, body?: unknown, headers?: Record<string, string>): Promise<unknown> };
10
+
11
+ /** Who is signed in. `userId` is empty until the host reports it; the chat then tells the business
12
+ * side apart by the room's participant id instead. */
13
+ export interface ChatIdentity { authenticated: boolean; userId: string; email: string; scope: string }
14
+ export async function chatIdentity(): Promise<ChatIdentity> {
15
+ const member = await memberAccess();
16
+ return { authenticated: !!member.email, userId: "", email: member.email, scope: member.scope };
17
+ }
18
+ export const assertChatIdentity = (identity: ChatIdentity): Promise<void> => assertMemberAccess(identity);
19
+
20
+ /** Every request is fenced: the member is re-checked before it goes out and again before its response is
21
+ * used, so a sign-out or account switch mid-request never leaks one member's data to the next. */
22
+ async function fenced<T>(identity: ChatIdentity, run: () => Promise<T>): Promise<T> {
23
+ await assertChatIdentity(identity);
24
+ const result = await run();
25
+ await assertChatIdentity(identity);
26
+ return result;
27
+ }
28
+
29
+ /** Any other member-scoped call (the AI chat's) goes through the same fence. */
30
+ export const fence = fenced;
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
+
45
+ // Minting a chat token is a network round trip, and every chat call used to mint its own. One token
46
+ // per member is reused until the member changes or a request using it is refused.
47
+ let cachedToken: { key: string; token: string } | null = null;
48
+ const tokenKey = (identity: ChatIdentity): string => `${identity.email}|${identity.scope}`;
49
+ async function chatTokenFor(identity: ChatIdentity): Promise<string> {
50
+ const key = tokenKey(identity);
51
+ if (cachedToken?.key === key) return cachedToken.token;
52
+ const { chatToken } = await getChatToken(MEMBER);
53
+ // The host mints for whoever is signed in NOW: a token minted while the member switched belongs to the
54
+ // new member and must not be cached under the old one.
55
+ await assertChatIdentity(identity);
56
+ cachedToken = { key, token: chatToken };
57
+ return chatToken;
58
+ }
59
+ /** Runs `run` with the member's cached token; a refused request mints a fresh token and tries once more. */
60
+ export async function withToken<T>(identity: ChatIdentity, run: (chatToken: string) => Promise<T>): Promise<T> {
61
+ const reused = cachedToken?.key === tokenKey(identity);
62
+ try {
63
+ return await run(await chatTokenFor(identity));
64
+ } catch (error) {
65
+ cachedToken = null;
66
+ if (!reused || !/\b(?:401|403)\b|token/i.test(String((error as Error)?.message ?? error))) throw error;
67
+ return run(await chatTokenFor(identity));
68
+ }
69
+ }
70
+
71
+ const MAX_ROOM_PAGES = 20;
72
+ /** Every chatroom the member can see: the cursor is followed so the business room is found on any page. */
73
+ export const listRooms = (identity: ChatIdentity): Promise<{ items: Raw[]; more: boolean }> => fenced(identity, async () => {
74
+ const items: Raw[] = [];
75
+ let nextPointer: number | string | undefined;
76
+ for (let page = 0; page < MAX_ROOM_PAGES; page++) {
77
+ const result = await withToken(identity, (chatToken) => listChatroomsPage({ ...MEMBER, chatToken, pageSize: 50, ...(nextPointer !== undefined ? { nextPointer } : {}) }));
78
+ items.push(...(result.items as unknown as Raw[]));
79
+ nextPointer = result.nextPointer;
80
+ if (nextPointer === undefined) return { items, more: false };
81
+ }
82
+ return { items, more: true };
83
+ });
84
+ /** How many of the member's BUSINESS chatrooms have unread messages, as the server counts them (capped at 100).
85
+ * Not the rooms themselves: the header badge needs only the total. A response without a valid count is
86
+ * unavailable, never zero. */
87
+ export const unreadRoomCount = (identity: ChatIdentity): Promise<number> => fenced(identity, async () => {
88
+ const page = await withToken(identity, (chatToken) => listChatroomsPage({ ...MEMBER, chatToken, pageSize: 1, onlyUnread: true, participantType: "business" }));
89
+ const count = page.unreadChatroomCount;
90
+ if (typeof count !== "number" || !Number.isSafeInteger(count) || count < 0) throw new Error("unavailable unread chat count");
91
+ return count;
92
+ });
93
+ export const messagesPage = (identity: ChatIdentity, roomId: string): Promise<Raw[]> => fenced(identity, async () =>
94
+ (await withToken(identity, (chatToken) => getMessagesPage(roomId, { ...MEMBER, chatToken, pageSize: 50, ordering: "Desc" }))).items as unknown as Raw[]);
95
+
96
+ export function bridge(): Bridge {
97
+ const api = (globalThis as unknown as { himalaya?: { wixApi?: Bridge } }).himalaya?.wixApi;
98
+ if (!api) throw new Error("wix_api_bridge_unavailable");
99
+ return api;
100
+ }
101
+ /** A typed message goes through Smart Chat, exactly as the site's chat widget sends it. The Inbox then files it under
102
+ * Wix Smart Chat and the AI can answer it; a message posted straight into the room has no channel, so the AI never
103
+ * saw it and the owner's reply went out by email. Smart Chat chooses the conversation and stored message id.
104
+ * The bridge resolves once the AI has finished answering, not when the message is stored. */
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> {
109
+ const response = await bridge().call("POST", "/wix-assistant-widget/v1/messages/stream", {
110
+ message: { sender: "SITE_VISITOR", messageType: "QUESTION", body: { mainText: text } },
111
+ });
112
+ // The first stream frame names the persisted question. Keep its exact id so a send
113
+ // that moves from an old Members transcript to Smart Chat never relies on a text match.
114
+ let frames: unknown = response;
115
+ if (typeof frames === "string") {
116
+ const raw = frames;
117
+ try { frames = JSON.parse(raw); }
118
+ catch {
119
+ frames = [];
120
+ // The bridge buffers SSE verbatim. Ignore event/comment lines and decode the
121
+ // data of each frame; some hosts instead hand over NDJSON or parsed frames.
122
+ for (const block of raw.split(/\r?\n\r?\n/)) {
123
+ const lines = block.split(/\r?\n/);
124
+ const event = lines.find(line => line.startsWith('event:'))?.slice(6).trim();
125
+ const data = lines.filter(line => line.startsWith('data:')).map(line => line.slice(5).trimStart()).join('\n');
126
+ try {
127
+ const value = JSON.parse(data || block);
128
+ (frames as unknown[]).push(event === 'inputMessage' && !value?.inputMessage ? { inputMessage: value } : value);
129
+ } catch { /* Comments and other non-JSON frames carry no stored question id. */ }
130
+ }
131
+ // A buffered NDJSON response has no SSE separators.
132
+ if (!(frames as unknown[]).length) {
133
+ try { frames = [JSON.parse(raw.split('\n', 1)[0]!)]; } catch { return undefined; }
134
+ }
135
+ }
136
+ }
137
+ for (const frame of Array.isArray(frames) ? frames : [frames]) {
138
+ const input = (frame as { inputMessage?: { id?: unknown; sender?: unknown; messageType?: unknown } } | null)?.inputMessage;
139
+ if (input?.sender === "SITE_VISITOR" && input.messageType === "QUESTION" && typeof input.id === "string" && input.id) return `smart-chat:${input.id}`;
140
+ }
141
+ return undefined;
142
+ }
143
+ /** A tapped button is a silent, ephemeral message carrying the button's chat action. */
144
+ export const sendButton = (identity: ChatIdentity, roomId: string, input: { id: string; text: string; appId: string; interactionId: string }): Promise<void> => fenced(identity, async () => {
145
+ await withToken(identity, (chatToken) => bridge().call("POST", `${MANAGE}/_api/chat-web/v2/chatrooms/${encodeURIComponent(roomId)}/messages`, {
146
+ sendMessageBody: { id: input.id, messageType: "message", messageTypeVersion: 1, summary: input.text, isEphemeral: true, isSilent: true, data: [{ mimeType: "text/plain", data: { text: input.text } }] },
147
+ sendMessageOptions: { chatAction: { actionType: "BUTTON_INTERACTION", appId: input.appId, interactionId: input.interactionId } },
148
+ }, { ChatToken: chatToken }));
149
+ });
150
+
151
+ const https = (value: unknown): string => (typeof value === "string" && /^https:\/\/[^\s\\]+$/.test(value) ? value : "");
152
+ /** A fresh, authorized URL for an attachment. A private file is always fetched by its id. */
153
+ export const attachmentUrl = (identity: ChatIdentity, media: { mediaId?: string; mediaProvider?: string; url?: string; fileName?: string }): Promise<string> => fenced(identity, async () => {
154
+ if (media.mediaProvider === "WixMediaPrivate") {
155
+ if (!media.mediaId) throw new Error("attachment_has_no_media_id");
156
+ const response = await bridge().call("POST", "/communication-channels-media/v1/download-url", {
157
+ fileId: media.mediaId, ...(media.fileName ? { downloadFileName: media.fileName } : {}),
158
+ }) as Raw | null;
159
+ const url = https(response?.downloadUrl);
160
+ if (!url) throw new Error("attachment_download_url_invalid");
161
+ return url;
162
+ }
163
+ return https(media.url);
164
+ });
@@ -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
+ }