@shotik/react-native 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/client.ts ADDED
@@ -0,0 +1,685 @@
1
+ // Shotik Support client: the platform-free core of the SDK. Identify (anonymous id persisted, merged on sign-in),
2
+ // conversations and messages over HTTP, live replies over the /support/v1/stream WebSocket with reconnect and backoff,
3
+ // an offline send queue with optimistic messages, and a pull for anything missed. No React Native imports, so it runs
4
+ // (and is tested) under plain Node as well as in the app.
5
+
6
+ export type Author = 'user' | 'ai' | 'founder' | 'system'
7
+ export type ConversationStatus = 'open' | 'needs_human' | 'resolved' | 'closed' | string
8
+ export type Status = 'idle' | 'identifying' | 'connecting' | 'live' | 'offline' | 'error'
9
+
10
+ export interface Conversation {
11
+ id: string
12
+ status: ConversationStatus
13
+ subject: string | null
14
+ lastMessageAt: number
15
+ lastPreview: string | null
16
+ lastAuthor: Author | null
17
+ createdAt: number
18
+ // User messages the founder has not read yet; 0 means everything you sent was seen.
19
+ founderUnread?: number
20
+ }
21
+
22
+ // A picked photo or screenshot before upload (uri: file:// or data:), and the uploaded form in message meta.
23
+ export interface LocalAttachment {
24
+ uri: string
25
+ type?: string
26
+ name?: string
27
+ width?: number
28
+ height?: number
29
+ }
30
+
31
+ export interface Attachment {
32
+ id: string
33
+ type: string
34
+ size: number
35
+ width: number | null
36
+ height: number | null
37
+ path: string
38
+ }
39
+
40
+ export type Receipt = 'sending' | 'queued' | 'failed' | 'sent' | 'delivered' | 'seen'
41
+ export type Typing = 'ai' | 'founder'
42
+
43
+ export interface Message {
44
+ id: string
45
+ conversationId: string
46
+ author: Author
47
+ body: string
48
+ createdAt: number
49
+ meta?: Record<string, unknown> | null
50
+ // When the message reached the other side (Shotik for yours, the device for replies).
51
+ deliveredAt?: number | null
52
+ localId?: string
53
+ pending?: 'sending' | 'waiting' | 'failed'
54
+ }
55
+
56
+ export interface UserInfo {
57
+ userId?: string
58
+ name?: string
59
+ email?: string
60
+ attributes?: Record<string, unknown>
61
+ }
62
+
63
+ export interface DeviceInfo {
64
+ platform?: string
65
+ osVersion?: string
66
+ model?: string
67
+ appVersion?: string
68
+ build?: string
69
+ locale?: string
70
+ timezone?: string
71
+ }
72
+
73
+ export interface KeyValueStorage {
74
+ get(key: string): Promise<string | null>
75
+ set(key: string, value: string): Promise<void>
76
+ remove(key: string): Promise<void>
77
+ }
78
+
79
+ export interface SupportConfig {
80
+ appKey: string
81
+ serverUrl: string
82
+ storage?: KeyValueStorage
83
+ device?: () => DeviceInfo | Promise<DeviceInfo>
84
+ }
85
+
86
+ export interface SupportState {
87
+ status: Status
88
+ userId: string | null
89
+ conversations: Conversation[]
90
+ messages: Record<string, Message[]>
91
+ unread: number
92
+ unreadBy: Record<string, number>
93
+ open: boolean
94
+ activeConversationId: string | null
95
+ error: string | null
96
+ // Who is typing in each conversation right now (the AI drafting or the founder in Shotik).
97
+ typing: Record<string, Typing>
98
+ }
99
+
100
+ interface QueueItem {
101
+ localId: string
102
+ conversationId: string
103
+ body: string
104
+ createdAt: number
105
+ attempts: number
106
+ attachments?: (LocalAttachment & { remote?: Attachment })[]
107
+ }
108
+
109
+ // Receipt for one of your messages: sending -> sent -> delivered (reached Shotik) -> seen (the founder read it).
110
+ // queued = waiting to send: offline, or the last attempt hit a network error, 5xx or 429 (it goes out on its own).
111
+ export function receiptOf(m: Message, list: Message[], conv: Conversation | undefined, offline = false): Receipt | null {
112
+ if (m.author !== 'user') return null
113
+ if (m.pending === 'failed') return 'failed'
114
+ if (m.pending) return offline || m.pending === 'waiting' ? 'queued' : 'sending'
115
+ const unseen = conv?.founderUnread ?? null
116
+ if (unseen !== null) {
117
+ const mine = list.filter((x) => x.author === 'user' && !x.pending)
118
+ if (mine.indexOf(m) < mine.length - unseen) return 'seen'
119
+ }
120
+ return m.deliveredAt ? 'delivered' : 'sent'
121
+ }
122
+
123
+ export const attachmentsOf = (m: Message): (Partial<Attachment> & { uri?: string })[] => (Array.isArray(m.meta?.['attachments']) ? (m.meta['attachments'] as Attachment[]) : [])
124
+
125
+ interface Session {
126
+ userToken: string
127
+ userId: string
128
+ externalId: string | null
129
+ }
130
+
131
+ export class HttpError extends Error {
132
+ status: number
133
+ constructor(status: number, message: string) {
134
+ super(message)
135
+ this.status = status
136
+ }
137
+ }
138
+
139
+ const K = { anon: 'shotik.support.anon', session: 'shotik.support.session', queue: 'shotik.support.queue', read: 'shotik.support.read', push: 'shotik.support.push' }
140
+ const LOCAL_CONV = 'local_conv_'
141
+
142
+ export function memoryStorage(): KeyValueStorage {
143
+ const m = new Map<string, string>()
144
+ return {
145
+ get: async (k) => m.get(k) ?? null,
146
+ set: async (k, v) => void m.set(k, v),
147
+ remove: async (k) => void m.delete(k)
148
+ }
149
+ }
150
+
151
+ const isReactNative = () => typeof navigator !== 'undefined' && (navigator as { product?: string }).product === 'ReactNative'
152
+
153
+ function localId(prefix: string): string {
154
+ return prefix + Date.now().toString(36) + Math.random().toString(36).slice(2, 10)
155
+ }
156
+
157
+ export class SupportClient {
158
+ readonly config: SupportConfig
159
+ private storage: KeyValueStorage
160
+ private listeners = new Set<(s: SupportState) => void>()
161
+ private state: SupportState = { status: 'idle', userId: null, conversations: [], messages: {}, unread: 0, unreadBy: {}, open: false, activeConversationId: null, error: null, typing: {} }
162
+ private typingTimers = new Map<string, ReturnType<typeof setTimeout>>()
163
+ private session: Session | null = null
164
+ private anonId: string | null = null
165
+ private user: UserInfo = {}
166
+ private queue: QueueItem[] = []
167
+ private readAt: Record<string, number> = {}
168
+ private pushToken: { token: string; platform: string } | null = null
169
+ private ws: WebSocket | null = null
170
+ private backoffStep = 0
171
+ private reconnectTimer: ReturnType<typeof setTimeout> | null = null
172
+ private flushTimer: ReturnType<typeof setTimeout> | null = null
173
+ private ping: ReturnType<typeof setInterval> | null = null
174
+ private flushing: Promise<void> | null = null
175
+ private identifying: Promise<void> | null = null
176
+ private loaded: Promise<void> | null = null
177
+ private full = new Set<string>()
178
+ private stopped = false
179
+
180
+ constructor(config: SupportConfig) {
181
+ this.config = { ...config, serverUrl: config.serverUrl.replace(/\/+$/, '') }
182
+ this.storage = config.storage ?? memoryStorage()
183
+ }
184
+
185
+ getState = (): SupportState => this.state
186
+
187
+ subscribe = (fn: (s: SupportState) => void): (() => void) => {
188
+ this.listeners.add(fn)
189
+ return () => void this.listeners.delete(fn)
190
+ }
191
+
192
+ private set(p: Partial<SupportState>): void {
193
+ const next = { ...this.state, ...p }
194
+ next.unreadBy = this.countUnread(next)
195
+ next.unread = Object.values(next.unreadBy).reduce((a, b) => a + b, 0)
196
+ this.state = next
197
+ for (const fn of this.listeners) fn(next)
198
+ }
199
+
200
+ private countUnread(s: SupportState): Record<string, number> {
201
+ const out: Record<string, number> = {}
202
+ for (const c of s.conversations) {
203
+ const seen = this.readAt[c.id] ?? 0
204
+ const msgs = s.messages[c.id]
205
+ const n = msgs ? msgs.filter((m) => m.author !== 'user' && m.createdAt > seen).length : c.lastAuthor && c.lastAuthor !== 'user' && c.lastMessageAt > seen ? 1 : 0
206
+ if (n) out[c.id] = n
207
+ }
208
+ return out
209
+ }
210
+
211
+ private load(): Promise<void> {
212
+ this.loaded ??= (async () => {
213
+ const [anon, session, queue, read, push] = await Promise.all([K.anon, K.session, K.queue, K.read, K.push].map((k) => this.storage.get(k).catch(() => null)))
214
+ this.anonId = anon ?? localId('anon_')
215
+ if (!anon) await this.storage.set(K.anon, this.anonId).catch(() => {})
216
+ this.session = session ? (JSON.parse(session) as Session) : null
217
+ this.queue = queue ? (JSON.parse(queue) as QueueItem[]) : []
218
+ this.readAt = read ? (JSON.parse(read) as Record<string, number>) : {}
219
+ this.pushToken = push ? (JSON.parse(push) as { token: string; platform: string }) : null
220
+ if (this.queue.length) {
221
+ const messages = { ...this.state.messages }
222
+ for (const q of this.queue) messages[q.conversationId] = [...(messages[q.conversationId] ?? []), this.optimistic(q, q.attempts ? 'waiting' : 'sending')]
223
+ this.set({ messages, conversations: this.withLocalConversations(this.state.conversations, messages) })
224
+ }
225
+ })()
226
+ return this.loaded
227
+ }
228
+
229
+ private persist(key: string, value: unknown): void {
230
+ this.storage.set(key, JSON.stringify(value)).catch(() => {})
231
+ }
232
+
233
+ async request<T>(method: 'GET' | 'POST', path: string, body?: unknown): Promise<T> {
234
+ const form = typeof FormData !== 'undefined' && body instanceof FormData
235
+ const headers: Record<string, string> = { 'x-shotik-key': this.config.appKey }
236
+ if (!form) headers['content-type'] = 'application/json'
237
+ if (this.session) headers['x-shotik-user'] = this.session.userToken
238
+ const url = this.config.serverUrl + path
239
+ // Expo replaces the global fetch with one that can't send React Native's { uri, type, name } file parts, so uploads
240
+ // go through XMLHttpRequest, which uses React Native's own networking.
241
+ const res: { status: number; text: string } =
242
+ form && isReactNative()
243
+ ? await new Promise((resolve, reject) => {
244
+ const x = new XMLHttpRequest()
245
+ x.open(method, url)
246
+ for (const [k, v] of Object.entries(headers)) x.setRequestHeader(k, v)
247
+ x.onload = () => resolve({ status: x.status, text: x.responseText })
248
+ x.onerror = () => reject(new TypeError('Network request failed'))
249
+ x.send(body as FormData)
250
+ })
251
+ : await fetch(url, { method, headers, body: body === undefined ? undefined : form ? (body as FormData) : JSON.stringify(body) }).then(async (r) => ({ status: r.status, text: await r.text().catch(() => '') }))
252
+ let json = {} as T & { error?: string }
253
+ try {
254
+ json = JSON.parse(res.text)
255
+ } catch {}
256
+ if (res.status < 200 || res.status >= 300) throw new HttpError(res.status, json.error ?? 'HTTP ' + res.status)
257
+ return json
258
+ }
259
+
260
+ // Identify the app user. Without a userId the persisted anonymous id is used; with one, the anonymous user's
261
+ // conversations move to the signed-in user on the server.
262
+ identify(user: UserInfo = {}): Promise<void> {
263
+ this.user = { ...this.user, ...user }
264
+ const run = async () => {
265
+ await this.load()
266
+ this.set({ status: this.state.status === 'live' ? 'live' : 'identifying', error: null })
267
+ const device = await Promise.resolve(this.config.device?.()).catch(() => undefined)
268
+ const r = await this.request<{ user: { id: string }; userToken: string; conversations: Conversation[] }>('POST', '/support/v1/identify', {
269
+ anonymousId: this.anonId,
270
+ userId: this.user.userId,
271
+ name: this.user.name,
272
+ email: this.user.email,
273
+ attributes: this.user.attributes,
274
+ device: device ?? undefined,
275
+ appVersion: device?.appVersion ? device.appVersion + (device.build ? ' (' + device.build + ')' : '') : undefined,
276
+ locale: device?.locale
277
+ })
278
+ const changed = this.session?.userId !== r.user.id
279
+ this.session = { userToken: r.userToken, userId: r.user.id, externalId: this.user.userId ?? null }
280
+ this.persist(K.session, this.session)
281
+ this.set({ userId: r.user.id, conversations: this.withLocalConversations(r.conversations) })
282
+ if (this.pushToken) await this.sendPushToken().catch(() => {})
283
+ if (changed || !this.ws) this.connect(true)
284
+ this.scheduleFlush(0)
285
+ }
286
+ const p = (this.identifying ?? Promise.resolve()).then(run, run)
287
+ this.identifying = p.catch((e: Error) => {
288
+ if (e instanceof HttpError && e.status === 401) return this.set({ status: 'error', error: e.message })
289
+ this.set({ status: 'offline', error: e.message })
290
+ this.scheduleReconnect()
291
+ })
292
+ return p
293
+ }
294
+
295
+ // Identify anonymously unless the app already did.
296
+ ensureIdentified(): Promise<void> {
297
+ return this.identifying ? this.identifying : this.identify()
298
+ }
299
+
300
+ async setPushToken(token: string | null, platform = 'ios'): Promise<void> {
301
+ await this.load()
302
+ this.pushToken = token ? { token, platform } : null
303
+ this.persist(K.push, this.pushToken)
304
+ if (this.session) await this.sendPushToken()
305
+ }
306
+
307
+ private sendPushToken(): Promise<unknown> {
308
+ return this.request('POST', '/support/v1/push-token', this.pushToken ?? { token: null })
309
+ }
310
+
311
+ open(conversationId?: string | null): void {
312
+ this.set({ open: true, activeConversationId: conversationId === undefined ? this.state.activeConversationId : conversationId })
313
+ if (conversationId) this.select(conversationId)
314
+ }
315
+
316
+ close(): void {
317
+ this.set({ open: false })
318
+ }
319
+
320
+ // Show one thread (or the list with null), load its messages and mark it read.
321
+ select(conversationId: string | null): void {
322
+ this.set({ activeConversationId: conversationId })
323
+ if (!conversationId) return
324
+ this.markRead(conversationId)
325
+ if (!conversationId.startsWith(LOCAL_CONV)) this.loadMessages(conversationId).catch(() => {})
326
+ }
327
+
328
+ markRead(conversationId: string): void {
329
+ const msgs = this.state.messages[conversationId] ?? []
330
+ const conv = this.state.conversations.find((c) => c.id === conversationId)
331
+ this.readAt[conversationId] = Math.max(conv?.lastMessageAt ?? 0, ...msgs.filter((m) => !m.pending).map((m) => m.createdAt))
332
+ this.persist(K.read, this.readAt)
333
+ this.set({})
334
+ if (!conversationId.startsWith(LOCAL_CONV) && this.state.userId) this.request('POST', '/support/v1/conversations/' + conversationId + '/read', {}).catch(() => {})
335
+ }
336
+
337
+ async loadMessages(conversationId: string): Promise<Message[]> {
338
+ const have = (this.state.messages[conversationId] ?? []).filter((m) => !m.pending)
339
+ const after = this.full.has(conversationId) && have.length ? have[have.length - 1].createdAt - 1 : 0
340
+ const r = await this.request<{ messages: Message[] }>('GET', '/support/v1/conversations/' + conversationId + '/messages?after=' + after)
341
+ this.full.add(conversationId)
342
+ this.mergeMessages(conversationId, r.messages)
343
+ if (this.state.open && this.state.activeConversationId === conversationId) this.markRead(conversationId)
344
+ return this.state.messages[conversationId] ?? []
345
+ }
346
+
347
+ // Send a message. Without a conversation id (or with a local one) a new conversation is started. The message shows
348
+ // at once; the queue delivers it now or once the server is reachable again.
349
+ send(body: string, conversationId?: string | null, attachments: LocalAttachment[] = []): Message | null {
350
+ const text = body.trim()
351
+ if (!text && !attachments.length) return null
352
+ const convId = conversationId || this.state.activeConversationId || LOCAL_CONV + localId('')
353
+ const item: QueueItem = { localId: localId('local_'), conversationId: convId, body: text, createdAt: Date.now(), attempts: 0, ...(attachments.length ? { attachments: attachments.slice(0, 4) } : {}) }
354
+ this.queue.push(item)
355
+ this.persist(K.queue, this.queue)
356
+ const msg = this.optimistic(item, 'sending')
357
+ const messages = { ...this.state.messages, [convId]: [...(this.state.messages[convId] ?? []), msg] }
358
+ this.set({
359
+ messages,
360
+ conversations: this.withLocalConversations(this.state.conversations, messages),
361
+ activeConversationId: this.state.open ? convId : this.state.activeConversationId
362
+ })
363
+ this.scheduleFlush(0)
364
+ return msg
365
+ }
366
+
367
+ // Retry a failed message now.
368
+ retry(localMessageId: string): void {
369
+ let item = this.queue.find((q) => q.localId === localMessageId)
370
+ if (!item) {
371
+ const m = Object.values(this.state.messages).flat().find((x) => x.localId === localMessageId && x.pending === 'failed')
372
+ if (!m) return
373
+ const atts = attachmentsOf(m).filter((a) => a.uri).map((a) => ({ uri: a.uri!, type: a.type, width: a.width ?? undefined, height: a.height ?? undefined }))
374
+ item = { localId: localMessageId, conversationId: m.conversationId, body: m.body, createdAt: m.createdAt, attempts: 0, ...(atts.length ? { attachments: atts } : {}) }
375
+ this.queue.push(item)
376
+ this.persist(K.queue, this.queue)
377
+ }
378
+ item.attempts = 0
379
+ this.markPending(item, 'sending')
380
+ this.scheduleFlush(0)
381
+ }
382
+
383
+ get pendingCount(): number {
384
+ return this.queue.length
385
+ }
386
+
387
+ // Deliver queued messages in order. Network errors, 5xx and 429 keep them queued as 'waiting' with backoff; another 4xx
388
+ // fails the message.
389
+ flush(): Promise<void> {
390
+ this.flushing ??= (async () => {
391
+ try {
392
+ await this.load()
393
+ if (!this.session) return
394
+ while (this.queue.length && !this.stopped) {
395
+ const item = this.queue[0]
396
+ try {
397
+ await this.deliver(item)
398
+ this.queue.shift()
399
+ this.persist(K.queue, this.queue)
400
+ } catch (e) {
401
+ const status = e instanceof HttpError ? e.status : 0
402
+ if (status === 401) {
403
+ this.session = null
404
+ this.identify().catch(() => {})
405
+ return
406
+ }
407
+ if (status >= 400 && status < 500 && status !== 429) {
408
+ this.queue.shift()
409
+ this.persist(K.queue, this.queue)
410
+ this.markPending(item, 'failed')
411
+ continue
412
+ }
413
+ item.attempts++
414
+ this.persist(K.queue, this.queue)
415
+ this.markPending(item, 'waiting')
416
+ this.set({ status: this.ws ? this.state.status : 'offline', error: (e as Error).message })
417
+ this.scheduleFlush(Math.min(30_000, 500 * 2 ** item.attempts))
418
+ return
419
+ }
420
+ }
421
+ } finally {
422
+ this.flushing = null
423
+ }
424
+ })()
425
+ return this.flushing
426
+ }
427
+
428
+ private scheduleFlush(ms: number): void {
429
+ if (this.flushTimer) clearTimeout(this.flushTimer)
430
+ this.flushTimer = setTimeout(() => {
431
+ this.flushTimer = null
432
+ this.flush().catch(() => {})
433
+ }, ms)
434
+ }
435
+
436
+ // Uploads each picked image once (the result is kept on the queue item, so a retry does not upload again).
437
+ private async upload(item: QueueItem): Promise<Attachment[]> {
438
+ const out: Attachment[] = []
439
+ for (const a of item.attachments ?? []) {
440
+ if (!a.remote) {
441
+ const form = new FormData()
442
+ const type = a.type ?? 'image/jpeg'
443
+ const name = a.name ?? 'image.' + (type.split('/')[1] ?? 'jpg')
444
+ if (isReactNative()) form.append('file', { uri: a.uri, type, name } as unknown as Blob)
445
+ else form.append('file', new Blob([await (await fetch(a.uri)).arrayBuffer()], { type }), name)
446
+ if (a.width) form.append('width', String(a.width))
447
+ if (a.height) form.append('height', String(a.height))
448
+ a.remote = (await this.request<{ attachment: Attachment }>('POST', '/support/v1/attachments', form)).attachment
449
+ this.persist(K.queue, this.queue)
450
+ }
451
+ out.push(a.remote)
452
+ }
453
+ return out
454
+ }
455
+
456
+ // A server path (attachment) as a full URL.
457
+ url(path: string): string {
458
+ return /^[a-z]+:/i.test(path) ? path : this.config.serverUrl + path
459
+ }
460
+
461
+ // "Talk to a person": the conversation goes to the founder's Needs-human list and the AI stops answering it.
462
+ async handoff(conversationId: string): Promise<void> {
463
+ if (conversationId.startsWith(LOCAL_CONV)) return
464
+ const r = await this.request<{ conversation: Conversation }>('POST', '/support/v1/conversations/' + conversationId + '/handoff', {})
465
+ this.upsertConversation(r.conversation)
466
+ this.loadMessages(conversationId).catch(() => {})
467
+ }
468
+
469
+ private setTyping(conversationId: string, who: Typing | null, ttl = 0): void {
470
+ const t = this.typingTimers.get(conversationId)
471
+ if (t) clearTimeout(t)
472
+ this.typingTimers.delete(conversationId)
473
+ const typing = { ...this.state.typing }
474
+ if (who && ttl > 0) {
475
+ typing[conversationId] = who
476
+ this.typingTimers.set(conversationId, setTimeout(() => this.setTyping(conversationId, null), ttl))
477
+ } else {
478
+ if (!typing[conversationId]) return
479
+ delete typing[conversationId]
480
+ }
481
+ this.set({ typing })
482
+ }
483
+
484
+ private async deliver(item: QueueItem): Promise<void> {
485
+ const meta: Record<string, unknown> = { localId: item.localId }
486
+ if (item.attachments?.length) meta['attachments'] = (await this.upload(item)).map((a) => ({ id: a.id }))
487
+ if (item.conversationId.startsWith(LOCAL_CONV)) {
488
+ const r = await this.request<{ conversation: Conversation; message: Message }>('POST', '/support/v1/conversations', { body: item.body, meta })
489
+ this.remapConversation(item.conversationId, r.conversation)
490
+ this.mergeMessages(r.conversation.id, [r.message])
491
+ return
492
+ }
493
+ const r = await this.request<{ message: Message }>('POST', '/support/v1/conversations/' + item.conversationId + '/messages', { body: item.body, meta })
494
+ this.mergeMessages(item.conversationId, [r.message])
495
+ }
496
+
497
+ private remapConversation(from: string, conv: Conversation): void {
498
+ for (const q of this.queue) if (q.conversationId === from) q.conversationId = conv.id
499
+ this.persist(K.queue, this.queue)
500
+ const messages = { ...this.state.messages }
501
+ messages[conv.id] = (messages[from] ?? []).map((m) => ({ ...m, conversationId: conv.id }))
502
+ delete messages[from]
503
+ this.full.add(conv.id)
504
+ this.readAt[conv.id] = conv.lastMessageAt
505
+ const conversations = this.state.conversations.filter((c) => c.id !== from && c.id !== conv.id)
506
+ this.set({ messages, conversations: this.sortConvs([conv, ...conversations]), activeConversationId: this.state.activeConversationId === from ? conv.id : this.state.activeConversationId })
507
+ }
508
+
509
+ private optimistic(q: QueueItem, pending: NonNullable<Message['pending']>): Message {
510
+ const meta = q.attachments?.length ? { attachments: q.attachments.map((a) => ({ uri: a.uri, width: a.width ?? null, height: a.height ?? null, type: a.type ?? 'image/jpeg' })) } : null
511
+ return { id: q.localId, localId: q.localId, conversationId: q.conversationId, author: 'user', body: q.body, createdAt: q.createdAt, pending, meta }
512
+ }
513
+
514
+ private markPending(item: QueueItem, pending: NonNullable<Message['pending']>): void {
515
+ const list = this.state.messages[item.conversationId] ?? []
516
+ this.set({ messages: { ...this.state.messages, [item.conversationId]: list.map((m) => (m.localId === item.localId ? { ...m, pending } : m)) } })
517
+ }
518
+
519
+ private withLocalConversations(server: Conversation[], messages = this.state.messages): Conversation[] {
520
+ const local = Object.keys(messages)
521
+ .filter((id) => id.startsWith(LOCAL_CONV) && !server.some((c) => c.id === id))
522
+ .map((id): Conversation => {
523
+ const msgs = messages[id]
524
+ const last = msgs[msgs.length - 1]
525
+ return { id, status: 'open', subject: msgs[0]?.body.slice(0, 80) ?? null, lastMessageAt: last?.createdAt ?? Date.now(), lastPreview: last?.body ?? null, lastAuthor: 'user', createdAt: msgs[0]?.createdAt ?? Date.now() }
526
+ })
527
+ return this.sortConvs([...local, ...server])
528
+ }
529
+
530
+ private sortConvs(list: Conversation[]): Conversation[] {
531
+ return [...list].sort((a, b) => b.lastMessageAt - a.lastMessageAt)
532
+ }
533
+
534
+ private mergeMessages(conversationId: string, incoming: Message[]): void {
535
+ if (!incoming.length) return
536
+ const list = [...(this.state.messages[conversationId] ?? [])]
537
+ for (const m of incoming) {
538
+ const lid = typeof m.meta?.['localId'] === 'string' ? (m.meta['localId'] as string) : null
539
+ const at = list.findIndex((x) => x.id === m.id || (lid !== null && x.localId === lid))
540
+ const msg: Message = { ...m, ...(lid ? { localId: lid } : {}) }
541
+ const local = at >= 0 ? attachmentsOf(list[at]) : []
542
+ if (local.some((a) => a.uri)) msg.meta = { ...msg.meta, attachments: attachmentsOf(msg).map((a, i) => ({ ...a, uri: local[i]?.uri })) }
543
+ if (at >= 0) list[at] = msg
544
+ else list.push(msg)
545
+ }
546
+ list.sort((a, b) => a.createdAt - b.createdAt)
547
+ this.set({ messages: { ...this.state.messages, [conversationId]: list } })
548
+ }
549
+
550
+ private upsertConversation(conv: Conversation): void {
551
+ this.set({ conversations: this.sortConvs([conv, ...this.state.conversations.filter((c) => c.id !== conv.id)]) })
552
+ }
553
+
554
+ // Catch up after a reconnect or when the app comes to the foreground.
555
+ async pull(): Promise<void> {
556
+ if (!this.session) return
557
+ const r = await this.request<{ conversations: Conversation[] }>('GET', '/support/v1/conversations')
558
+ this.set({ conversations: this.withLocalConversations(r.conversations) })
559
+ const ids = new Set(Object.keys(this.state.messages).filter((id) => !id.startsWith(LOCAL_CONV)))
560
+ if (this.state.activeConversationId && !this.state.activeConversationId.startsWith(LOCAL_CONV)) ids.add(this.state.activeConversationId)
561
+ await Promise.all([...ids].map((id) => this.loadMessages(id).catch(() => [])))
562
+ }
563
+
564
+ // App came back to the foreground: reconnect now, deliver the queue and fetch what was missed.
565
+ foreground(): void {
566
+ if (this.stopped || !this.session) {
567
+ if (!this.stopped && this.state.status !== 'identifying') this.identify().catch(() => {})
568
+ return
569
+ }
570
+ if (!this.ws) this.connect(true)
571
+ else this.pull().catch(() => {})
572
+ this.scheduleFlush(0)
573
+ }
574
+
575
+ private connect(resetBackoff = false): void {
576
+ if (this.stopped || !this.session) return
577
+ if (resetBackoff) this.backoffStep = 0
578
+ if (this.reconnectTimer) clearTimeout(this.reconnectTimer)
579
+ this.reconnectTimer = null
580
+ const old = this.ws
581
+ this.ws = null
582
+ old?.close()
583
+ const url = this.config.serverUrl.replace(/^http/, 'ws') + '/support/v1/stream?key=' + encodeURIComponent(this.config.appKey) + '&user=' + encodeURIComponent(this.session.userToken)
584
+ let ws: WebSocket
585
+ try {
586
+ ws = new WebSocket(url)
587
+ } catch (e) {
588
+ this.set({ status: 'offline', error: (e as Error).message })
589
+ return this.scheduleReconnect()
590
+ }
591
+ this.ws = ws
592
+ if (this.state.status !== 'live') this.set({ status: 'connecting' })
593
+ ws.onmessage = (ev) => {
594
+ if (this.ws !== ws || ev.data === 'pong') return
595
+ let m: { t: string; message?: Message; conversation?: Conversation; conversationId?: string; who?: Typing; ttl?: number }
596
+ try {
597
+ m = JSON.parse(String(ev.data))
598
+ } catch {
599
+ return
600
+ }
601
+ if (m.t === 'ready') {
602
+ this.backoffStep = 0
603
+ this.set({ status: 'live', error: null })
604
+ if (this.ping) clearInterval(this.ping)
605
+ this.ping = setInterval(() => ws.readyState === 1 && ws.send('ping'), 25_000)
606
+ this.pull().catch(() => {})
607
+ this.scheduleFlush(0)
608
+ } else if (m.t === 'typing' && m.conversationId) {
609
+ this.setTyping(m.conversationId, m.who ?? 'founder', m.ttl ?? 0)
610
+ } else if (m.t === 'message' && m.message) {
611
+ if (m.message.author !== 'user') this.setTyping(m.message.conversationId, null)
612
+ this.mergeMessages(m.message.conversationId, [m.message])
613
+ const conv = this.state.conversations.find((c) => c.id === m.message!.conversationId)
614
+ if (conv) this.upsertConversation({ ...conv, lastMessageAt: Math.max(conv.lastMessageAt, m.message.createdAt), lastPreview: m.message.body.slice(0, 140), lastAuthor: m.message.author })
615
+ if (this.state.open && this.state.activeConversationId === m.message.conversationId) this.markRead(m.message.conversationId)
616
+ } else if (m.t === 'conversation' && m.conversation) {
617
+ this.upsertConversation(m.conversation)
618
+ }
619
+ }
620
+ ws.onclose = (ev) => {
621
+ if (this.ws !== ws) return
622
+ this.ws = null
623
+ if (this.ping) clearInterval(this.ping)
624
+ this.ping = null
625
+ if (this.stopped) return
626
+ if (ev.code === 4003) {
627
+ this.session = null
628
+ this.set({ status: 'error', error: 'unauthorized' })
629
+ return void this.identify().catch(() => {})
630
+ }
631
+ this.set({ status: 'offline' })
632
+ this.scheduleReconnect()
633
+ }
634
+ ws.onerror = () => {
635
+ if (this.ws === ws) this.set({ error: 'cannot reach ' + this.config.serverUrl })
636
+ }
637
+ }
638
+
639
+ private scheduleReconnect(): void {
640
+ if (this.stopped || this.reconnectTimer) return
641
+ const delay = Math.min(30_000, 500 * 2 ** this.backoffStep++) * (0.8 + Math.random() * 0.4)
642
+ this.reconnectTimer = setTimeout(() => {
643
+ this.reconnectTimer = null
644
+ if (this.session) this.connect()
645
+ else this.identify().catch(() => {})
646
+ }, delay)
647
+ }
648
+
649
+ get reconnectAttempts(): number {
650
+ return this.backoffStep
651
+ }
652
+
653
+ // Drop the live socket without stopping (tests, and the app going to the background).
654
+ disconnect(): void {
655
+ const ws = this.ws
656
+ this.ws = null
657
+ if (this.ping) clearInterval(this.ping)
658
+ this.ping = null
659
+ ws?.close()
660
+ if (!this.stopped) this.set({ status: 'offline' })
661
+ }
662
+
663
+ stop(): void {
664
+ this.stopped = true
665
+ for (const t of [this.reconnectTimer, this.flushTimer, ...this.typingTimers.values()]) if (t) clearTimeout(t)
666
+ this.typingTimers.clear()
667
+ this.reconnectTimer = this.flushTimer = null
668
+ this.disconnect()
669
+ this.set({ status: 'idle' })
670
+ }
671
+
672
+ // Sign-out: forget the identified user and start over as a new anonymous user.
673
+ async reset(): Promise<void> {
674
+ await this.load()
675
+ this.disconnect()
676
+ this.session = null
677
+ this.user = {}
678
+ this.queue = []
679
+ this.readAt = {}
680
+ this.full.clear()
681
+ this.anonId = localId('anon_')
682
+ await Promise.all([this.storage.set(K.anon, this.anonId), this.storage.remove(K.session), this.storage.remove(K.queue), this.storage.remove(K.read)]).catch(() => {})
683
+ this.set({ userId: null, conversations: [], messages: {}, activeConversationId: null, status: 'idle', error: null, typing: {} })
684
+ }
685
+ }