@sippulse/niva-sdk 0.1.0-rc.9 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/chat.js ADDED
@@ -0,0 +1,1083 @@
1
+ import {
2
+ NivaError2
3
+ } from "./chunk-50ad2r7x.js";
4
+
5
+ // src/chat/emitter.ts
6
+ class Emitter {
7
+ sets = new Map;
8
+ on(event, listener) {
9
+ const set = this.sets.get(event) ?? new Set;
10
+ this.sets.set(event, set);
11
+ const wrapper = (arg) => {
12
+ listener(arg);
13
+ };
14
+ set.add(wrapper);
15
+ return () => void set.delete(wrapper);
16
+ }
17
+ async once(event) {
18
+ return new Promise((resolve) => {
19
+ const stop = this.on(event, (arg) => {
20
+ stop();
21
+ resolve(arg);
22
+ });
23
+ });
24
+ }
25
+ emit(event, arg) {
26
+ for (const listener of Array.from(this.sets.get(event) ?? [])) {
27
+ try {
28
+ listener(arg);
29
+ } catch (error) {
30
+ queueMicrotask(() => {
31
+ throw error;
32
+ });
33
+ }
34
+ }
35
+ }
36
+ }
37
+
38
+ // src/chat/error.ts
39
+ class NivaChatError extends NivaError2 {
40
+ name = "NivaChatError";
41
+ code;
42
+ fatal;
43
+ constructor(code, message, options) {
44
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
45
+ this.code = code;
46
+ this.fatal = options.fatal;
47
+ }
48
+ }
49
+
50
+ // src/chat/transfer.ts
51
+ function uploadTarget(wsUrl) {
52
+ try {
53
+ const url = new URL(wsUrl);
54
+ const session = url.searchParams.get("session");
55
+ if (session === null || session === "")
56
+ return null;
57
+ if (url.protocol !== "wss:" && url.protocol !== "ws:")
58
+ return null;
59
+ const protocol = url.protocol === "wss:" ? "https:" : "http:";
60
+ const base = `${protocol}//${url.host}/api/v1/chat`;
61
+ return { base, url: `${base}/media`, session };
62
+ } catch {
63
+ return null;
64
+ }
65
+ }
66
+ function refusalCode(code) {
67
+ switch (code) {
68
+ case "CHAT_MEDIA_TOO_LARGE":
69
+ case "CHAT_MEDIA_UNSUPPORTED":
70
+ case "WEBCHAT_SESSION_INVALID":
71
+ case "WEBCHAT_ORIGIN_DENIED":
72
+ case "CHAT_MEDIA_NOT_FOUND":
73
+ case "CHAT_SESSION_NOT_FOUND":
74
+ return code;
75
+ default:
76
+ return "UPLOAD_FAILED";
77
+ }
78
+ }
79
+ var UPLOAD_FAILURE = { code: "UPLOAD_FAILED", message: "The file could not be uploaded" };
80
+ function refusal(body, status, failure = UPLOAD_FAILURE) {
81
+ const record = typeof body === "object" && body !== null ? body : {};
82
+ const message = Reflect.get(record, "message");
83
+ const given = refusalCode(Reflect.get(record, "code"));
84
+ const code = given === "UPLOAD_FAILED" ? failure.code : given;
85
+ return new NivaChatError(status === 429 ? "RATE_LIMITED" : code, typeof message === "string" ? message : failure.message, {
86
+ fatal: false
87
+ });
88
+ }
89
+
90
+ // src/chat/end.ts
91
+ var FAILURE = { code: "END_FAILED", message: "The conversation could not be ended" };
92
+ async function endSession(host) {
93
+ const target = host.wsUrl === null ? null : uploadTarget(host.wsUrl);
94
+ if (target === null) {
95
+ throw new NivaChatError("OFFLINE", "There is no chat session to end", { fatal: false });
96
+ }
97
+ const url = `${target.base}/sessions/${encodeURIComponent(target.session)}`;
98
+ const init = {
99
+ method: "DELETE",
100
+ headers: { authorization: `Bearer ${target.session}` },
101
+ keepalive: true
102
+ };
103
+ let response;
104
+ try {
105
+ response = await (host.fetch === undefined ? globalThis.fetch(url, init) : host.fetch(url, init));
106
+ } catch (error) {
107
+ throw new NivaChatError(FAILURE.code, FAILURE.message, { fatal: false, cause: error });
108
+ }
109
+ if (!response.ok)
110
+ throw refusal(await response.json().catch(() => null), response.status, FAILURE);
111
+ }
112
+
113
+ // src/chat/input.ts
114
+ function isChatFile(input) {
115
+ return typeof input === "object" && "file" in input;
116
+ }
117
+ function nameOf(blob) {
118
+ const name = Reflect.get(blob, "name");
119
+ return typeof name === "string" && name !== "" ? name : "file";
120
+ }
121
+ function fileMessage(input) {
122
+ return {
123
+ type: "file",
124
+ name: nameOf(input.file),
125
+ content_type: input.file.type,
126
+ size_bytes: input.file.size,
127
+ ...input.caption === undefined || input.caption === "" ? {} : { caption: input.caption },
128
+ file: input.file
129
+ };
130
+ }
131
+ function toInput(input) {
132
+ if (typeof input !== "string")
133
+ return input;
134
+ const text = input.trim();
135
+ return text === "" ? null : { type: "text", text };
136
+ }
137
+ function replyFor(option) {
138
+ if ("label" in option)
139
+ return { type: "button_reply", button_id: option.id, button_text: option.label };
140
+ return { type: "list_reply", list_id: option.id, list_title: option.title };
141
+ }
142
+ function queuedEntry(message, counter) {
143
+ return Object.freeze({
144
+ author: "visitor",
145
+ id: `local-${Date.now().toString(36)}-${counter}`,
146
+ ts: Date.now(),
147
+ message,
148
+ delivery: message.type === "file" ? "uploading" : "queued"
149
+ });
150
+ }
151
+
152
+ // src/chat/policy.ts
153
+ var PING_INTERVAL_MS = 25000;
154
+ var MAX_RECONNECT_ATTEMPTS = 8;
155
+ var OPEN = 1;
156
+ var backoffMs = (attempt) => Math.min(30000, 1000 * 2 ** attempt);
157
+ function softCode(code) {
158
+ if (code === "CAPACITY_EXCEEDED" || code === "RATE_LIMITED" || code === "INVALID_MESSAGE" || code === "MEDIA_NOT_FOUND") {
159
+ return code;
160
+ }
161
+ if (code === "INVALID_JSON")
162
+ return "INVALID_MESSAGE";
163
+ return "EXECUTION_ERROR";
164
+ }
165
+ var rejectsSend = (code) => code === "RATE_LIMITED" || code === "INVALID_MESSAGE" || code === "INVALID_JSON" || code === "MEDIA_NOT_FOUND";
166
+ function watchOnline(handler) {
167
+ const target = globalThis;
168
+ if (typeof target !== "object" || target === null || typeof Reflect.get(target, "addEventListener") !== "function" || typeof Reflect.get(target, "removeEventListener") !== "function") {
169
+ return null;
170
+ }
171
+ globalThis.addEventListener("online", handler);
172
+ return () => globalThis.removeEventListener("online", handler);
173
+ }
174
+ var FATAL_CLOSES = {
175
+ 4009: ["SUPERSEDED", "Another connection took over this chat session"],
176
+ 1008: ["UNAVAILABLE", "The chat is no longer available for this session"]
177
+ };
178
+
179
+ // src/chat/queue.ts
180
+ var isFileEntry = (entry) => entry.author === "visitor" && entry.message.type === "file";
181
+ var uploadingIds = (messages) => messages.filter((entry) => isFileEntry(entry) && entry.delivery === "uploading").map((entry) => entry.id);
182
+ var nextInQueue = (messages) => messages.find((entry) => entry.author === "visitor" && (entry.delivery === "queued" || entry.delivery === "uploading"));
183
+ function frameOf(entry, mediaId) {
184
+ if (entry.message.type !== "file")
185
+ return entry.message;
186
+ if (mediaId === null)
187
+ return null;
188
+ return {
189
+ type: "media",
190
+ media_id: mediaId,
191
+ ...entry.message.caption === undefined ? {} : { caption: entry.message.caption }
192
+ };
193
+ }
194
+ function withMediaId(entry, mediaId) {
195
+ if (entry.message.type !== "file")
196
+ return entry;
197
+ const { media_id: _previous, ...message } = entry.message;
198
+ return { ...entry, message: mediaId === null ? message : { ...message, media_id: mediaId } };
199
+ }
200
+ var failedIfUnsent = (entry) => isFileEntry(entry) && (entry.delivery === "uploading" || entry.delivery === "queued") ? Object.freeze({ ...entry, delivery: "failed" }) : entry;
201
+ var afterSessionLoss = (messages) => messages.filter((entry) => entry.author === "visitor" && (entry.delivery === "queued" || isFileEntry(entry) && entry.delivery === "uploading")).map((entry) => failedIfUnsent(entry)).map((entry) => isFileEntry(entry) ? withMediaId(entry, null) : entry);
202
+ var afterReload = (stored) => stored.map((entry) => Object.freeze(failedIfUnsent(entry)));
203
+ function planEntry(envelope) {
204
+ return Object.freeze({
205
+ author: "plan",
206
+ id: envelope.id,
207
+ seq: envelope.seq,
208
+ ts: envelope.ts,
209
+ message: envelope.message
210
+ });
211
+ }
212
+
213
+ // src/chat/socket.ts
214
+ function openSocket(url, factory, current, handlers) {
215
+ let created;
216
+ try {
217
+ created = factory === undefined ? new WebSocket(url) : factory(url);
218
+ } catch {
219
+ return null;
220
+ }
221
+ created.onopen = () => {
222
+ if (current())
223
+ handlers.open();
224
+ };
225
+ created.onmessage = (event) => {
226
+ const data = event.data;
227
+ if (current())
228
+ handlers.message(data);
229
+ };
230
+ created.onclose = (event) => {
231
+ if (current())
232
+ handlers.close(event.code);
233
+ };
234
+ created.onerror = () => {};
235
+ return created;
236
+ }
237
+
238
+ // src/chat/storage.ts
239
+ var VERSION = 1;
240
+ function isStorage(value) {
241
+ return typeof value === "object" && value !== null && typeof Reflect.get(value, "getItem") === "function" && typeof Reflect.get(value, "setItem") === "function" && typeof Reflect.get(value, "removeItem") === "function";
242
+ }
243
+ function openStorage(persist) {
244
+ if (persist === "none")
245
+ return null;
246
+ try {
247
+ const found = Reflect.get(globalThis, persist === "tab" ? "sessionStorage" : "localStorage");
248
+ return isStorage(found) ? found : null;
249
+ } catch {
250
+ return null;
251
+ }
252
+ }
253
+ function isEntry(value) {
254
+ if (typeof value !== "object" || value === null)
255
+ return false;
256
+ const author = Reflect.get(value, "author");
257
+ const message = Reflect.get(value, "message");
258
+ return (author === "plan" || author === "visitor") && typeof Reflect.get(value, "id") === "string" && typeof Reflect.get(value, "ts") === "number" && typeof message === "object" && message !== null;
259
+ }
260
+ function loadStored(storage, key) {
261
+ try {
262
+ const text = storage.getItem(key);
263
+ if (text === null)
264
+ return null;
265
+ const raw = JSON.parse(text);
266
+ if (typeof raw !== "object" || raw === null || Reflect.get(raw, "v") !== VERSION)
267
+ return null;
268
+ const wsUrl = Reflect.get(raw, "wsUrl");
269
+ const started = Reflect.get(raw, "started");
270
+ const lastSeq = Reflect.get(raw, "lastSeq");
271
+ const status = Reflect.get(raw, "status");
272
+ const messages = Reflect.get(raw, "messages");
273
+ if (typeof wsUrl !== "string" || typeof started !== "boolean" || typeof lastSeq !== "number")
274
+ return null;
275
+ if (!Array.isArray(messages))
276
+ return null;
277
+ const known = status === "active" || status === "waiting_input" || status === "ended" ? status : null;
278
+ const entries = messages;
279
+ return { wsUrl, started, lastSeq, status: known, messages: entries.filter((entry) => isEntry(entry)) };
280
+ } catch {
281
+ return null;
282
+ }
283
+ }
284
+ function withoutBytes(entry) {
285
+ if (entry.author !== "visitor" || entry.message.type !== "file")
286
+ return entry;
287
+ const { file: _bytes, ...message } = entry.message;
288
+ return { ...entry, message };
289
+ }
290
+ function saveStored(storage, key, chat) {
291
+ try {
292
+ storage.setItem(key, JSON.stringify({ v: VERSION, ...chat, messages: chat.messages.map((entry) => withoutBytes(entry)) }));
293
+ } catch {}
294
+ }
295
+ function clearStored(storage, key) {
296
+ try {
297
+ storage.removeItem(key);
298
+ } catch {}
299
+ }
300
+
301
+ // src/chat/timers.ts
302
+ class Timers {
303
+ stops = new Map;
304
+ has(name) {
305
+ return this.stops.has(name);
306
+ }
307
+ after(name, ms, run) {
308
+ this.clear(name);
309
+ const handle = setTimeout(() => {
310
+ this.stops.delete(name);
311
+ run();
312
+ }, ms);
313
+ this.stops.set(name, () => clearTimeout(handle));
314
+ }
315
+ every(name, ms, run) {
316
+ this.clear(name);
317
+ const handle = setInterval(run, ms);
318
+ this.stops.set(name, () => clearInterval(handle));
319
+ }
320
+ clear(name) {
321
+ this.stops.get(name)?.();
322
+ this.stops.delete(name);
323
+ }
324
+ clearAll() {
325
+ for (const stop of this.stops.values())
326
+ stop();
327
+ this.stops.clear();
328
+ }
329
+ }
330
+
331
+ // src/chat/download.ts
332
+ var FAILURE2 = { code: "DOWNLOAD_FAILED", message: "The file could not be downloaded" };
333
+ var aborted = () => new DOMException("The download was aborted", "AbortError");
334
+ function createDownloads(host) {
335
+ const inFlight = new Set;
336
+ let closed = false;
337
+ async function get(mediaId, options) {
338
+ if (closed || options?.signal?.aborted === true)
339
+ throw aborted();
340
+ const wsUrl = host.wsUrl();
341
+ const target = wsUrl === null ? null : uploadTarget(wsUrl);
342
+ if (target === null) {
343
+ throw new NivaChatError("OFFLINE", "There is no chat session to download the file with", { fatal: false });
344
+ }
345
+ const controller = new AbortController;
346
+ const forward = () => controller.abort();
347
+ options?.signal?.addEventListener("abort", forward, { once: true });
348
+ inFlight.add(controller);
349
+ try {
350
+ const url = `${target.url}/${encodeURIComponent(mediaId)}`;
351
+ const init = {
352
+ method: "GET",
353
+ headers: { authorization: `Bearer ${target.session}` },
354
+ signal: controller.signal
355
+ };
356
+ const response = await (host.fetch === undefined ? globalThis.fetch(url, init) : host.fetch(url, init));
357
+ if (!response.ok)
358
+ throw refusal(await response.json().catch(() => null), response.status, FAILURE2);
359
+ const blob = await response.blob();
360
+ if (controller.signal.aborted)
361
+ throw aborted();
362
+ return blob;
363
+ } catch (error) {
364
+ if (controller.signal.aborted)
365
+ throw aborted();
366
+ if (error instanceof NivaChatError)
367
+ throw error;
368
+ throw new NivaChatError(FAILURE2.code, FAILURE2.message, { fatal: false, cause: error });
369
+ } finally {
370
+ inFlight.delete(controller);
371
+ options?.signal?.removeEventListener("abort", forward);
372
+ }
373
+ }
374
+ return {
375
+ get,
376
+ abortAll() {
377
+ for (const controller of inFlight)
378
+ controller.abort();
379
+ inFlight.clear();
380
+ },
381
+ close() {
382
+ closed = true;
383
+ }
384
+ };
385
+ }
386
+
387
+ // src/chat/upload.ts
388
+ async function uploadFile(params) {
389
+ const form = new FormData;
390
+ form.set("file", params.file, params.name);
391
+ const init = {
392
+ method: "POST",
393
+ headers: { authorization: `Bearer ${params.target.session}` },
394
+ body: form,
395
+ signal: params.signal
396
+ };
397
+ let response;
398
+ try {
399
+ response = await (params.fetch === undefined ? globalThis.fetch(params.target.url, init) : params.fetch(params.target.url, init));
400
+ } catch (error) {
401
+ if (params.signal.aborted)
402
+ throw error;
403
+ throw new NivaChatError("UPLOAD_FAILED", "The file could not be uploaded", { fatal: false, cause: error });
404
+ }
405
+ const body = await response.json().catch(() => null);
406
+ if (!response.ok)
407
+ throw refusal(body, response.status);
408
+ const id = typeof body === "object" && body !== null ? Reflect.get(body, "id") : undefined;
409
+ if (typeof id !== "string")
410
+ throw refusal(null);
411
+ return id;
412
+ }
413
+ function createUploads(host) {
414
+ const records = new Map;
415
+ const downloads = createDownloads(host);
416
+ let generation = 0;
417
+ function start(entryId) {
418
+ const upload = records.get(entryId);
419
+ const wsUrl = host.wsUrl();
420
+ if (upload?.controller !== null || wsUrl === null)
421
+ return;
422
+ const target = uploadTarget(wsUrl);
423
+ if (target === null) {
424
+ host.settle(entryId, new NivaChatError("UPLOAD_FAILED", "The file could not be uploaded", { fatal: false }));
425
+ return;
426
+ }
427
+ const controller = new AbortController;
428
+ upload.controller = controller;
429
+ const started = generation;
430
+ const stale = () => host.stopped() || started !== generation || controller.signal.aborted;
431
+ uploadFile({ target, file: upload.file, name: upload.name, signal: controller.signal, fetch: host.fetch }).then((mediaId) => {
432
+ if (stale())
433
+ return;
434
+ upload.controller = null;
435
+ upload.mediaId = mediaId;
436
+ host.settle(entryId, "queued");
437
+ }, (error) => {
438
+ if (stale())
439
+ return;
440
+ upload.controller = null;
441
+ host.settle(entryId, error instanceof NivaChatError ? error : new NivaChatError("UPLOAD_FAILED", "The file could not be uploaded", { fatal: false, cause: error }));
442
+ });
443
+ }
444
+ return {
445
+ add(entryId, file, name) {
446
+ records.set(entryId, { file, name, mediaId: null, controller: null });
447
+ },
448
+ start,
449
+ has: (entryId) => records.has(entryId),
450
+ mediaId: (entryId) => records.get(entryId)?.mediaId ?? null,
451
+ retryAs: (entryId) => records.get(entryId)?.mediaId === null ? "uploading" : "queued",
452
+ dropMediaId(entryId) {
453
+ const upload = records.get(entryId);
454
+ if (upload !== undefined)
455
+ upload.mediaId = null;
456
+ },
457
+ dropAllMediaIds() {
458
+ for (const upload of records.values())
459
+ upload.mediaId = null;
460
+ },
461
+ getFile: downloads.get,
462
+ closeDownloads: () => downloads.close(),
463
+ abortAll() {
464
+ generation += 1;
465
+ downloads.abortAll();
466
+ for (const upload of records.values()) {
467
+ upload.controller?.abort();
468
+ upload.controller = null;
469
+ }
470
+ }
471
+ };
472
+ }
473
+
474
+ // src/chat/wire.ts
475
+ var MESSAGE_TYPES = new Set(["text", "media", "location", "buttons", "list", "carousel", "template"]);
476
+ var STATUSES = new Set(["active", "waiting_input", "ended"]);
477
+ function isRecord(value) {
478
+ return typeof value === "object" && value !== null && !Array.isArray(value);
479
+ }
480
+ function isChatMessage(value) {
481
+ return isRecord(value) && typeof value["type"] === "string" && MESSAGE_TYPES.has(value["type"]);
482
+ }
483
+ function isStatus(value) {
484
+ return typeof value === "string" && STATUSES.has(value);
485
+ }
486
+ function parseMessage(raw, seq) {
487
+ const { id, ts, message } = raw;
488
+ if (typeof id !== "string" || typeof ts !== "number" || !isChatMessage(message))
489
+ return null;
490
+ return { type: "message", seq, id, ts, message };
491
+ }
492
+ function parseError(raw, seq) {
493
+ const { code, message } = raw;
494
+ if (typeof code !== "string")
495
+ return null;
496
+ return { type: "error", seq, code, message: typeof message === "string" ? message : code };
497
+ }
498
+ function parseReplayable(raw) {
499
+ if (!isRecord(raw))
500
+ return null;
501
+ const type = raw["type"];
502
+ if (type === "trace")
503
+ return { type };
504
+ const seq = raw["seq"];
505
+ if (typeof seq !== "number")
506
+ return null;
507
+ switch (type) {
508
+ case "connected":
509
+ case "pong":
510
+ return { type, seq };
511
+ case "typing":
512
+ return typeof raw["active"] === "boolean" ? { type, seq, active: raw["active"] } : null;
513
+ case "state":
514
+ return isStatus(raw["status"]) ? { type, seq, status: raw["status"] } : null;
515
+ case "error":
516
+ return parseError(raw, seq);
517
+ case "message":
518
+ return parseMessage(raw, seq);
519
+ default:
520
+ return null;
521
+ }
522
+ }
523
+ function parseEnvelope(raw) {
524
+ if (isRecord(raw) && raw["type"] === "replay") {
525
+ const seq = raw["seq"];
526
+ const inner = raw["messages"];
527
+ if (typeof seq !== "number" || !Array.isArray(inner))
528
+ return null;
529
+ const messages = [];
530
+ const items = inner;
531
+ for (const item of items) {
532
+ const parsed = parseReplayable(item);
533
+ if (parsed !== null)
534
+ messages.push(parsed);
535
+ }
536
+ return { type: "replay", seq, messages };
537
+ }
538
+ return parseReplayable(raw);
539
+ }
540
+ function decodeFrame(data) {
541
+ if (typeof data !== "string")
542
+ return null;
543
+ try {
544
+ return parseEnvelope(JSON.parse(data));
545
+ } catch {
546
+ return null;
547
+ }
548
+ }
549
+ function unseen(missed, after) {
550
+ return missed.filter((entry) => entry.type !== "trace" && entry.seq > after).sort((a, b) => a.seq - b.seq);
551
+ }
552
+
553
+ // src/chat/client.ts
554
+ function connectChat(options) {
555
+ const storageKey = options.storageKey ?? "niva-chat";
556
+ const storage = openStorage(options.persist ?? "tab");
557
+ const emitter = new Emitter;
558
+ let messages = [];
559
+ let status = null;
560
+ let typing = false;
561
+ let connection = "connecting";
562
+ let lastSeq = 0;
563
+ let started = false;
564
+ let wsUrl = null;
565
+ let socket = null;
566
+ let socketGen = 0;
567
+ let sessionEpoch = 0;
568
+ let conversationGen = 0;
569
+ let attempt = 0;
570
+ const timers = new Timers;
571
+ let pingPending = false;
572
+ let stopped = false;
573
+ let forgotten = false;
574
+ let inFlight = false;
575
+ let awaitingReplay = false;
576
+ let pendingAck = null;
577
+ let sendReceived = false;
578
+ let starting = false;
579
+ let startAttempt = 0;
580
+ let socketConnected = false;
581
+ let failedConnects = 0;
582
+ let entryCounter = 0;
583
+ const uploads = createUploads({
584
+ wsUrl: () => wsUrl,
585
+ stopped: () => stopped,
586
+ fetch: options.fetch,
587
+ settle: (entryId, outcome) => batch(() => {
588
+ replaceEntry(entryId, (entry) => ({ ...entry, delivery: outcome === "queued" ? "queued" : "failed" }));
589
+ if (outcome !== "queued")
590
+ emitter.emit("error", outcome);
591
+ })
592
+ });
593
+ let dirty = false;
594
+ let stopWatchingOnline = null;
595
+ let snapshot = freezeState();
596
+ function freezeState() {
597
+ return Object.freeze({ messages: Object.freeze([...messages]), connection, status, typing });
598
+ }
599
+ function commit() {
600
+ persist();
601
+ if (!dirty)
602
+ return;
603
+ dirty = false;
604
+ snapshot = freezeState();
605
+ emitter.emit("change", snapshot);
606
+ }
607
+ function batch(work) {
608
+ work();
609
+ flush();
610
+ commit();
611
+ }
612
+ function persist() {
613
+ if (storage === null || forgotten || wsUrl === null)
614
+ return;
615
+ saveStored(storage, storageKey, { wsUrl, started, lastSeq, status, messages });
616
+ }
617
+ function setConnection(next) {
618
+ if (connection === next)
619
+ return;
620
+ connection = next;
621
+ dirty = true;
622
+ emitter.emit("connection", next);
623
+ }
624
+ function setTyping(next) {
625
+ if (typing === next)
626
+ return;
627
+ typing = next;
628
+ dirty = true;
629
+ emitter.emit("typing", next);
630
+ }
631
+ function setStatus(next) {
632
+ if (status === next)
633
+ return;
634
+ status = next;
635
+ dirty = true;
636
+ emitter.emit("status", next);
637
+ }
638
+ function replaceEntry(id, change) {
639
+ const changed = (entry) => Object.freeze(uploads.has(id) ? withMediaId(change(entry), uploads.mediaId(id)) : change(entry));
640
+ messages = messages.map((entry) => entry.author === "visitor" && entry.id === id ? changed(entry) : entry);
641
+ dirty = true;
642
+ }
643
+ function reportError(code, message, fatal) {
644
+ emitter.emit("error", new NivaChatError(code, message, { fatal }));
645
+ }
646
+ function sendFrame(frame) {
647
+ if (socket?.readyState !== OPEN)
648
+ return false;
649
+ try {
650
+ socket.send(JSON.stringify(frame));
651
+ return true;
652
+ } catch {
653
+ return false;
654
+ }
655
+ }
656
+ function stopTimers() {
657
+ timers.clearAll();
658
+ pingPending = false;
659
+ }
660
+ function resetStart() {
661
+ starting = false;
662
+ startAttempt = 0;
663
+ timers.clear("start");
664
+ }
665
+ const alive = () => !stopped;
666
+ function discardSocket() {
667
+ socketGen += 1;
668
+ const old = socket;
669
+ socket = null;
670
+ awaitingReplay = false;
671
+ resetStart();
672
+ if (old === null)
673
+ return;
674
+ try {
675
+ old.close(1000);
676
+ } catch {}
677
+ }
678
+ function scheduleRetry() {
679
+ setTyping(false);
680
+ if (!alive())
681
+ return;
682
+ if (attempt >= MAX_RECONNECT_ATTEMPTS) {
683
+ setConnection("offline");
684
+ reportError("OFFLINE", "Could not reach the chat; will try again when the browser is back online", false);
685
+ return;
686
+ }
687
+ const delay = backoffMs(attempt);
688
+ attempt += 1;
689
+ setConnection("reconnecting");
690
+ if (!alive())
691
+ return;
692
+ timers.after("retry", delay, () => {
693
+ if (stopped)
694
+ return;
695
+ batch(resume);
696
+ });
697
+ }
698
+ function resume() {
699
+ if (!alive())
700
+ return;
701
+ if (wsUrl === null)
702
+ acquireSession(false);
703
+ else if (failedConnects > 0 && failedConnects % 2 === 0)
704
+ acquireSession(true);
705
+ else
706
+ connectSocket();
707
+ }
708
+ function connectSocket() {
709
+ const url = wsUrl;
710
+ if (url === null || stopped)
711
+ return;
712
+ socketGen += 1;
713
+ const gen = socketGen;
714
+ pingPending = false;
715
+ awaitingReplay = false;
716
+ socketConnected = false;
717
+ const created = openSocket(url, options.webSocket, () => gen === socketGen, {
718
+ open: () => {
719
+ attempt = 0;
720
+ },
721
+ message: (data) => batch(() => onFrame(data)),
722
+ close: (code) => batch(() => onSocketClosed(code))
723
+ });
724
+ if (created === null) {
725
+ failedConnects += 1;
726
+ scheduleRetry();
727
+ return;
728
+ }
729
+ socket = created;
730
+ }
731
+ function startPing() {
732
+ pingPending = false;
733
+ timers.every("ping", PING_INTERVAL_MS, () => {
734
+ if (stopped)
735
+ return;
736
+ if (pingPending) {
737
+ batch(() => {
738
+ stopTimers();
739
+ discardSocket();
740
+ scheduleRetry();
741
+ });
742
+ return;
743
+ }
744
+ if (sendFrame({ type: "ping" }))
745
+ pingPending = true;
746
+ });
747
+ }
748
+ async function acquireSession(renewing) {
749
+ if (!alive())
750
+ return;
751
+ sessionEpoch += 1;
752
+ const epoch = sessionEpoch;
753
+ let url;
754
+ try {
755
+ url = await options.session();
756
+ } catch (error) {
757
+ if (epoch !== sessionEpoch || !alive())
758
+ return;
759
+ batch(() => {
760
+ if (renewing)
761
+ failedConnects += 1;
762
+ if (error instanceof NivaChatError)
763
+ emitter.emit("error", error);
764
+ if (error instanceof NivaChatError && error.fatal)
765
+ halt();
766
+ else
767
+ scheduleRetry();
768
+ });
769
+ return;
770
+ }
771
+ if (epoch !== sessionEpoch || !alive())
772
+ return;
773
+ batch(() => {
774
+ if (renewing) {
775
+ forgetConversation();
776
+ setConnection("connecting");
777
+ commit();
778
+ reportError("SESSION_EXPIRED", "The chat session expired; a new conversation was started", false);
779
+ if (!alive())
780
+ return;
781
+ }
782
+ wsUrl = url;
783
+ started = false;
784
+ connectSocket();
785
+ });
786
+ }
787
+ function onFrame(data) {
788
+ const envelope = decodeFrame(data);
789
+ if (envelope === null)
790
+ return;
791
+ pingPending = false;
792
+ onEnvelope(envelope);
793
+ }
794
+ function onEnvelope(envelope) {
795
+ if (envelope.type === "connected")
796
+ onConnected();
797
+ else if (envelope.type === "replay")
798
+ onReplay(envelope.messages);
799
+ else if (envelope.type === "error")
800
+ onServerError(envelope.code, envelope.message, envelope.seq);
801
+ else if (envelope.type !== "pong" && envelope.type !== "trace")
802
+ applyOne(envelope);
803
+ }
804
+ function onConnected() {
805
+ const gen = socketGen;
806
+ socketConnected = true;
807
+ failedConnects = 0;
808
+ if (started) {
809
+ awaitingReplay = true;
810
+ sendFrame({ type: "resume", last_seq: lastSeq });
811
+ } else {
812
+ sendFrame({ type: "start" });
813
+ started = true;
814
+ starting = true;
815
+ }
816
+ setConnection("connected");
817
+ if (stopped || gen !== socketGen)
818
+ return;
819
+ startPing();
820
+ }
821
+ function onReplay(missed) {
822
+ awaitingReplay = false;
823
+ applyReplay(missed);
824
+ if (pendingAck !== null && !sendReceived)
825
+ settleSend("queued");
826
+ }
827
+ function settleSend(delivery) {
828
+ if (pendingAck !== null && delivery !== null)
829
+ replaceEntry(pendingAck, (entry) => ({ ...entry, delivery }));
830
+ pendingAck = null;
831
+ inFlight = false;
832
+ }
833
+ function applyReplay(missed) {
834
+ for (const envelope of unseen(missed, lastSeq)) {
835
+ if (envelope.type === "message" || envelope.type === "typing" || envelope.type === "state")
836
+ applyOne(envelope);
837
+ else if (envelope.type === "error")
838
+ lastSeq = envelope.seq;
839
+ }
840
+ }
841
+ function applyOne(envelope) {
842
+ lastSeq = Math.max(lastSeq, envelope.seq);
843
+ if (envelope.type === "typing" ? envelope.active : envelope.type === "state" && envelope.status === "active") {
844
+ sendReceived = true;
845
+ }
846
+ if (envelope.type !== "typing") {
847
+ pendingAck = null;
848
+ resetStart();
849
+ }
850
+ switch (envelope.type) {
851
+ case "message": {
852
+ if (messages.some((entry) => entry.author === "plan" && entry.id === envelope.id))
853
+ return;
854
+ const entry = planEntry(envelope);
855
+ messages = [...messages, entry];
856
+ dirty = true;
857
+ setTyping(false);
858
+ emitter.emit("message", entry);
859
+ return;
860
+ }
861
+ case "typing":
862
+ setTyping(envelope.active);
863
+ return;
864
+ case "state":
865
+ if (envelope.status !== "active")
866
+ inFlight = false;
867
+ if (envelope.status === "ended")
868
+ setTyping(false);
869
+ setStatus(envelope.status);
870
+ return;
871
+ }
872
+ }
873
+ function onServerError(code, message, seq) {
874
+ lastSeq = Math.max(lastSeq, seq);
875
+ if (code === "TURN_IN_FLIGHT") {
876
+ settleSend("queued");
877
+ inFlight = true;
878
+ return;
879
+ }
880
+ if (code === "SESSION_EXPIRED") {
881
+ restart();
882
+ return;
883
+ }
884
+ if (code === "MODULE_DISABLED") {
885
+ fail("MODULE_DISABLED", message);
886
+ return;
887
+ }
888
+ if (code === "MEDIA_NOT_FOUND" && pendingAck !== null)
889
+ uploads.dropMediaId(pendingAck);
890
+ settleSend(rejectsSend(code) ? "failed" : null);
891
+ reportError(softCode(code), message, false);
892
+ if (starting && !stopped)
893
+ retryStart();
894
+ }
895
+ function retryStart() {
896
+ if (timers.has("start"))
897
+ return;
898
+ const delay = backoffMs(startAttempt);
899
+ startAttempt += 1;
900
+ timers.after("start", delay, () => {
901
+ if (!starting || connection !== "connected")
902
+ return;
903
+ sendFrame({ type: "start" });
904
+ });
905
+ }
906
+ function onSocketClosed(code) {
907
+ stopTimers();
908
+ socket = null;
909
+ awaitingReplay = false;
910
+ resetStart();
911
+ const fatal = FATAL_CLOSES[code];
912
+ if (fatal !== undefined) {
913
+ fail(...fatal);
914
+ return;
915
+ }
916
+ if (code === 1011) {
917
+ restart();
918
+ return;
919
+ }
920
+ if (!socketConnected)
921
+ failedConnects += 1;
922
+ scheduleRetry();
923
+ }
924
+ function halt(readOnly = false) {
925
+ stopped = true;
926
+ sessionEpoch += 1;
927
+ uploads.abortAll();
928
+ if (!readOnly)
929
+ uploads.closeDownloads();
930
+ stopTimers();
931
+ discardSocket();
932
+ stopWatchingOnline?.();
933
+ stopWatchingOnline = null;
934
+ if (!readOnly)
935
+ options.signal?.removeEventListener("abort", onAbort);
936
+ setTyping(false);
937
+ setConnection("closed");
938
+ }
939
+ function fail(code, message) {
940
+ halt();
941
+ commit();
942
+ reportError(code, message, true);
943
+ }
944
+ function forgetConversation() {
945
+ conversationGen += 1;
946
+ stopTimers();
947
+ discardSocket();
948
+ if (storage !== null)
949
+ clearStored(storage, storageKey);
950
+ uploads.abortAll();
951
+ uploads.dropAllMediaIds();
952
+ messages = afterSessionLoss(messages);
953
+ status = null;
954
+ typing = false;
955
+ lastSeq = 0;
956
+ started = false;
957
+ wsUrl = null;
958
+ inFlight = false;
959
+ pendingAck = null;
960
+ sendReceived = false;
961
+ failedConnects = 0;
962
+ dirty = true;
963
+ }
964
+ function restart() {
965
+ forgetConversation();
966
+ attempt = 0;
967
+ setConnection("connecting");
968
+ commit();
969
+ reportError("SESSION_EXPIRED", "The chat session expired; a new conversation was started", false);
970
+ acquireSession(false);
971
+ }
972
+ function onOnline() {
973
+ if (stopped || connection !== "offline")
974
+ return;
975
+ attempt = 0;
976
+ batch(() => {
977
+ setConnection("reconnecting");
978
+ resume();
979
+ });
980
+ }
981
+ function flush() {
982
+ if (stopped)
983
+ return;
984
+ for (const id of uploadingIds(messages))
985
+ uploads.start(id);
986
+ if (connection !== "connected" || awaitingReplay || inFlight || status !== "waiting_input")
987
+ return;
988
+ const next = nextInQueue(messages);
989
+ if (next === undefined || next.delivery === "uploading")
990
+ return;
991
+ const frame = frameOf(next, uploads.mediaId(next.id));
992
+ if (frame === null || !sendFrame({ type: "message", message: frame }))
993
+ return;
994
+ replaceEntry(next.id, (entry) => ({ ...entry, delivery: "sent" }));
995
+ inFlight = true;
996
+ pendingAck = next.id;
997
+ sendReceived = false;
998
+ }
999
+ function enqueue(message) {
1000
+ if (status === "ended")
1001
+ return;
1002
+ entryCounter += 1;
1003
+ const entry = queuedEntry(message, entryCounter);
1004
+ if (message.type === "file" && message.file !== undefined)
1005
+ uploads.add(entry.id, message.file, message.name);
1006
+ batch(() => {
1007
+ messages = [...messages, entry];
1008
+ dirty = true;
1009
+ });
1010
+ }
1011
+ function send(input) {
1012
+ const message = isChatFile(input) ? fileMessage(input) : toInput(input);
1013
+ if (message !== null)
1014
+ enqueue(message);
1015
+ }
1016
+ function retry(entryId) {
1017
+ const entry = messages.find((candidate) => candidate.author === "visitor" && candidate.id === entryId);
1018
+ if (entry?.author !== "visitor" || entry.delivery !== "failed")
1019
+ return;
1020
+ if (entry.message.type === "file" && !uploads.has(entryId))
1021
+ return;
1022
+ batch(() => replaceEntry(entryId, (failed) => ({ ...failed, delivery: uploads.retryAs(entryId) })));
1023
+ }
1024
+ function on(event, listener) {
1025
+ return emitter.on(event, listener);
1026
+ }
1027
+ async function end() {
1028
+ if (status === "ended")
1029
+ return;
1030
+ const asked = conversationGen;
1031
+ await endSession({ wsUrl, fetch: options.fetch });
1032
+ if (asked === conversationGen && !stopped)
1033
+ batch(() => applyOne({ type: "state", seq: lastSeq, status: "ended" }));
1034
+ }
1035
+ function close(closeOptions) {
1036
+ if (closeOptions?.forget === true) {
1037
+ if (status !== "ended")
1038
+ endSession({ wsUrl, fetch: options.fetch }).catch(() => {
1039
+ return;
1040
+ });
1041
+ forgotten = true;
1042
+ if (storage !== null)
1043
+ clearStored(storage, storageKey);
1044
+ }
1045
+ batch(halt);
1046
+ }
1047
+ const onAbort = () => close();
1048
+ const stored = storage === null ? null : loadStored(storage, storageKey);
1049
+ if (stored !== null) {
1050
+ ({ wsUrl, started, lastSeq, status } = stored);
1051
+ messages = afterReload(stored.messages);
1052
+ snapshot = freezeState();
1053
+ }
1054
+ stopWatchingOnline = watchOnline(onOnline);
1055
+ if (options.signal?.aborted === true) {
1056
+ batch(halt);
1057
+ } else {
1058
+ options.signal?.addEventListener("abort", onAbort, { once: true });
1059
+ if (stored === null)
1060
+ acquireSession(false);
1061
+ else if (stored.status === "ended")
1062
+ batch(() => halt(true));
1063
+ else
1064
+ connectSocket();
1065
+ }
1066
+ return {
1067
+ get state() {
1068
+ return snapshot;
1069
+ },
1070
+ send,
1071
+ select: (option) => enqueue(replyFor(option)),
1072
+ retry,
1073
+ getFile: uploads.getFile,
1074
+ end,
1075
+ close,
1076
+ on,
1077
+ once: async (event) => emitter.once(event)
1078
+ };
1079
+ }
1080
+ export {
1081
+ NivaChatError,
1082
+ connectChat
1083
+ };