@diegoaltoworks/chatter 0.44.0 → 0.45.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/dist/client/index.js +615 -0
- package/dist/client/index.mjs +592 -0
- package/dist/core/session.d.ts +1 -0
- package/dist/core/session.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.mjs +2 -1
- package/dist/server.js +1526 -0
- package/dist/server.mjs +1497 -0
- package/package.json +9 -5
- package/dist/auth/apikeys.test.d.ts +0 -2
- package/dist/auth/apikeys.test.d.ts.map +0 -1
- package/dist/channels/gates.test.d.ts +0 -2
- package/dist/channels/gates.test.d.ts.map +0 -1
- package/dist/channels/senders.test.d.ts +0 -2
- package/dist/channels/senders.test.d.ts.map +0 -1
- package/dist/channels/whatsapp/authState.test.d.ts +0 -2
- package/dist/channels/whatsapp/authState.test.d.ts.map +0 -1
- package/dist/channels/whatsapp/baileys.test.d.ts +0 -2
- package/dist/channels/whatsapp/baileys.test.d.ts.map +0 -1
- package/dist/channels/whatsapp/channel.test.d.ts +0 -2
- package/dist/channels/whatsapp/channel.test.d.ts.map +0 -1
- package/dist/channels/whatsapp/crypto.test.d.ts +0 -2
- package/dist/channels/whatsapp/crypto.test.d.ts.map +0 -1
- package/dist/channels/whatsapp/images.test.d.ts +0 -2
- package/dist/channels/whatsapp/images.test.d.ts.map +0 -1
- package/dist/channels/whatsapp/inbound.test.d.ts +0 -2
- package/dist/channels/whatsapp/inbound.test.d.ts.map +0 -1
- package/dist/channels/whatsapp/lease.test.d.ts +0 -2
- package/dist/channels/whatsapp/lease.test.d.ts.map +0 -1
- package/dist/channels/whatsapp/pairing.test.d.ts +0 -2
- package/dist/channels/whatsapp/pairing.test.d.ts.map +0 -1
- package/dist/channels/whatsapp/qr.test.d.ts +0 -2
- package/dist/channels/whatsapp/qr.test.d.ts.map +0 -1
- package/dist/client/__tests__/markdown.test.d.ts +0 -5
- package/dist/client/__tests__/markdown.test.d.ts.map +0 -1
- package/dist/client/__tests__/mobile-chat.test.d.ts +0 -6
- package/dist/client/__tests__/mobile-chat.test.d.ts.map +0 -1
- package/dist/client/examples/node.d.ts +0 -5
- package/dist/client/examples/node.d.ts.map +0 -1
- package/dist/core/answer.test.d.ts +0 -8
- package/dist/core/answer.test.d.ts.map +0 -1
- package/dist/core/buckets.test.d.ts +0 -10
- package/dist/core/buckets.test.d.ts.map +0 -1
- package/dist/core/guardrails.test.d.ts +0 -2
- package/dist/core/guardrails.test.d.ts.map +0 -1
- package/dist/core/loaders.test.d.ts +0 -2
- package/dist/core/loaders.test.d.ts.map +0 -1
- package/dist/core/messages.test.d.ts +0 -8
- package/dist/core/messages.test.d.ts.map +0 -1
- package/dist/core/pipeline.test.d.ts +0 -8
- package/dist/core/pipeline.test.d.ts.map +0 -1
- package/dist/core/prompts.test.d.ts +0 -2
- package/dist/core/prompts.test.d.ts.map +0 -1
- package/dist/core/retrieval.test.d.ts +0 -8
- package/dist/core/retrieval.test.d.ts.map +0 -1
- package/dist/core/session.test.d.ts +0 -2
- package/dist/core/session.test.d.ts.map +0 -1
- package/dist/core/widgets.test.d.ts +0 -2
- package/dist/core/widgets.test.d.ts.map +0 -1
- package/dist/flows/__fixtures__/broken/handler.d.ts +0 -3
- package/dist/flows/__fixtures__/broken/handler.d.ts.map +0 -1
- package/dist/flows/__fixtures__/greeting/handler.d.ts +0 -3
- package/dist/flows/__fixtures__/greeting/handler.d.ts.map +0 -1
- package/dist/flows/__fixtures__/greeting/prefill.d.ts +0 -3
- package/dist/flows/__fixtures__/greeting/prefill.d.ts.map +0 -1
- package/dist/flows/engine.test.d.ts +0 -9
- package/dist/flows/engine.test.d.ts.map +0 -1
- package/dist/flows/intent.test.d.ts +0 -6
- package/dist/flows/intent.test.d.ts.map +0 -1
- package/dist/flows/loader.test.d.ts +0 -8
- package/dist/flows/loader.test.d.ts.map +0 -1
- package/dist/flows/params.test.d.ts +0 -2
- package/dist/flows/params.test.d.ts.map +0 -1
- package/dist/flows/registry.test.d.ts +0 -2
- package/dist/flows/registry.test.d.ts.map +0 -1
- package/dist/flows/session.test.d.ts +0 -7
- package/dist/flows/session.test.d.ts.map +0 -1
- package/dist/flows/utils.test.d.ts +0 -2
- package/dist/flows/utils.test.d.ts.map +0 -1
- package/dist/images/cache.test.d.ts +0 -2
- package/dist/images/cache.test.d.ts.map +0 -1
- package/dist/images/cacheStore.test.d.ts +0 -8
- package/dist/images/cacheStore.test.d.ts.map +0 -1
- package/dist/images/captionComposer.test.d.ts +0 -2
- package/dist/images/captionComposer.test.d.ts.map +0 -1
- package/dist/images/cloudinaryClient.test.d.ts +0 -2
- package/dist/images/cloudinaryClient.test.d.ts.map +0 -1
- package/dist/images/cloudinaryConfig.test.d.ts +0 -2
- package/dist/images/cloudinaryConfig.test.d.ts.map +0 -1
- package/dist/images/cloudinarySignature.test.d.ts +0 -2
- package/dist/images/cloudinarySignature.test.d.ts.map +0 -1
- package/dist/images/config.test.d.ts +0 -2
- package/dist/images/config.test.d.ts.map +0 -1
- package/dist/images/generator.test.d.ts +0 -2
- package/dist/images/generator.test.d.ts.map +0 -1
- package/dist/images/openaiClient.test.d.ts +0 -2
- package/dist/images/openaiClient.test.d.ts.map +0 -1
- package/dist/images/uploader.test.d.ts +0 -2
- package/dist/images/uploader.test.d.ts.map +0 -1
- package/dist/mcp-server/conversation-id.test.d.ts +0 -2
- package/dist/mcp-server/conversation-id.test.d.ts.map +0 -1
- package/dist/mcp-server/cost-tracker.test.d.ts +0 -2
- package/dist/mcp-server/cost-tracker.test.d.ts.map +0 -1
- package/dist/mcp-server/logger.test.d.ts +0 -2
- package/dist/mcp-server/logger.test.d.ts.map +0 -1
- package/dist/mcp-server/rate-limiter.test.d.ts +0 -2
- package/dist/mcp-server/rate-limiter.test.d.ts.map +0 -1
- package/dist/middleware/auth.test.d.ts +0 -2
- package/dist/middleware/auth.test.d.ts.map +0 -1
- package/dist/middleware/cors.test.d.ts +0 -2
- package/dist/middleware/cors.test.d.ts.map +0 -1
- package/dist/middleware/jwt.test.d.ts +0 -2
- package/dist/middleware/jwt.test.d.ts.map +0 -1
- package/dist/middleware/ratelimit.test.d.ts +0 -2
- package/dist/middleware/ratelimit.test.d.ts.map +0 -1
- package/dist/middleware/referrer.test.d.ts +0 -2
- package/dist/middleware/referrer.test.d.ts.map +0 -1
- package/dist/middleware/session.test.d.ts +0 -2
- package/dist/middleware/session.test.d.ts.map +0 -1
- package/dist/personas/greeter.test.d.ts +0 -2
- package/dist/personas/greeter.test.d.ts.map +0 -1
- package/dist/personas/resolver.test.d.ts +0 -2
- package/dist/personas/resolver.test.d.ts.map +0 -1
- package/dist/personas/timeContext.test.d.ts +0 -2
- package/dist/personas/timeContext.test.d.ts.map +0 -1
- package/dist/routes/chat.test.d.ts +0 -9
- package/dist/routes/chat.test.d.ts.map +0 -1
- package/dist/routes/openai.test.d.ts +0 -8
- package/dist/routes/openai.test.d.ts.map +0 -1
- package/dist/scheduler/claimStore.test.d.ts +0 -2
- package/dist/scheduler/claimStore.test.d.ts.map +0 -1
- package/dist/scheduler/compose.test.d.ts +0 -2
- package/dist/scheduler/compose.test.d.ts.map +0 -1
- package/dist/scheduler/deliver.test.d.ts +0 -2
- package/dist/scheduler/deliver.test.d.ts.map +0 -1
- package/dist/scheduler/dueDrops.test.d.ts +0 -2
- package/dist/scheduler/dueDrops.test.d.ts.map +0 -1
- package/dist/scheduler/scheduler.test.d.ts +0 -2
- package/dist/scheduler/scheduler.test.d.ts.map +0 -1
- package/dist/scheduler/tick.test.d.ts +0 -2
- package/dist/scheduler/tick.test.d.ts.map +0 -1
- package/dist/server.test.d.ts +0 -9
- package/dist/server.test.d.ts.map +0 -1
- package/dist/shortener.test.d.ts +0 -2
- package/dist/shortener.test.d.ts.map +0 -1
- package/dist/usage/limits.test.d.ts +0 -10
- package/dist/usage/limits.test.d.ts.map +0 -1
- package/dist/usage/tursoStore.test.d.ts +0 -9
- package/dist/usage/tursoStore.test.d.ts.map +0 -1
|
@@ -0,0 +1,592 @@
|
|
|
1
|
+
// src/ChatBot.ts
|
|
2
|
+
var ChatBot = class {
|
|
3
|
+
constructor(config) {
|
|
4
|
+
if (!config.host) {
|
|
5
|
+
throw new Error("host is required");
|
|
6
|
+
}
|
|
7
|
+
if (!config.mode || !["public", "private"].includes(config.mode)) {
|
|
8
|
+
throw new Error('mode must be either "public" or "private"');
|
|
9
|
+
}
|
|
10
|
+
if (!config.apiKey) {
|
|
11
|
+
throw new Error("apiKey is required");
|
|
12
|
+
}
|
|
13
|
+
if (config.mode === "private" && !config.token) {
|
|
14
|
+
throw new Error("token is required for private mode");
|
|
15
|
+
}
|
|
16
|
+
let host = config.host.trim();
|
|
17
|
+
if (!host.startsWith("http://") && !host.startsWith("https://")) {
|
|
18
|
+
const isLocalhost = host.startsWith("localhost") || host.startsWith("127.0.0.1");
|
|
19
|
+
const protocol = isLocalhost ? "http://" : "https://";
|
|
20
|
+
host = `${protocol}${host}`;
|
|
21
|
+
}
|
|
22
|
+
this.baseUrl = host.replace(/\/$/, "");
|
|
23
|
+
this.mode = config.mode;
|
|
24
|
+
this.apiKey = config.apiKey;
|
|
25
|
+
this.token = config.token;
|
|
26
|
+
this.endpoint = `${this.baseUrl}/api/${this.mode}/chat`;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Get authentication headers based on mode
|
|
30
|
+
*/
|
|
31
|
+
getHeaders(streaming = false) {
|
|
32
|
+
const headers = {
|
|
33
|
+
"Content-Type": "application/json"
|
|
34
|
+
};
|
|
35
|
+
if (this.apiKey) {
|
|
36
|
+
headers["x-api-key"] = this.apiKey;
|
|
37
|
+
}
|
|
38
|
+
if (this.mode === "private" && this.token) {
|
|
39
|
+
headers.Authorization = `Bearer ${this.token}`;
|
|
40
|
+
}
|
|
41
|
+
if (streaming) {
|
|
42
|
+
headers.Accept = "text/event-stream";
|
|
43
|
+
}
|
|
44
|
+
return headers;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Send a single message to the chatbot
|
|
48
|
+
*/
|
|
49
|
+
async sendMessage(message) {
|
|
50
|
+
const response = await fetch(this.endpoint, {
|
|
51
|
+
method: "POST",
|
|
52
|
+
headers: this.getHeaders(),
|
|
53
|
+
body: JSON.stringify({ message })
|
|
54
|
+
});
|
|
55
|
+
if (!response.ok) {
|
|
56
|
+
const error = await response.json().catch(() => ({ error: "Unknown error" }));
|
|
57
|
+
throw new Error(`API Error: ${error.error || response.statusText}`);
|
|
58
|
+
}
|
|
59
|
+
const data = await response.json();
|
|
60
|
+
return data.reply;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Send a conversation history (multi-turn chat)
|
|
64
|
+
*/
|
|
65
|
+
async sendConversation(messages) {
|
|
66
|
+
if (!Array.isArray(messages) || messages.length === 0) {
|
|
67
|
+
throw new Error("messages must be a non-empty array");
|
|
68
|
+
}
|
|
69
|
+
const response = await fetch(this.endpoint, {
|
|
70
|
+
method: "POST",
|
|
71
|
+
headers: this.getHeaders(),
|
|
72
|
+
body: JSON.stringify({ messages })
|
|
73
|
+
});
|
|
74
|
+
if (!response.ok) {
|
|
75
|
+
const error = await response.json().catch(() => ({ error: "Unknown error" }));
|
|
76
|
+
throw new Error(`API Error: ${error.error || response.statusText}`);
|
|
77
|
+
}
|
|
78
|
+
const data = await response.json();
|
|
79
|
+
return data.reply;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Stream a single message response
|
|
83
|
+
*/
|
|
84
|
+
async streamMessage(message, callbacks) {
|
|
85
|
+
await this.stream({ message }, callbacks);
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Stream a conversation response
|
|
89
|
+
*/
|
|
90
|
+
async streamConversation(messages, callbacks) {
|
|
91
|
+
if (!Array.isArray(messages) || messages.length === 0) {
|
|
92
|
+
throw new Error("messages must be a non-empty array");
|
|
93
|
+
}
|
|
94
|
+
await this.stream({ messages }, callbacks);
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Internal method to handle streaming
|
|
98
|
+
*/
|
|
99
|
+
async stream(body, callbacks) {
|
|
100
|
+
const { onChunk, onEnd, onError } = callbacks;
|
|
101
|
+
try {
|
|
102
|
+
const response = await fetch(`${this.endpoint}?stream=1`, {
|
|
103
|
+
method: "POST",
|
|
104
|
+
headers: this.getHeaders(true),
|
|
105
|
+
body: JSON.stringify(body)
|
|
106
|
+
});
|
|
107
|
+
if (!response.ok) {
|
|
108
|
+
const error = await response.json().catch(() => ({ error: "Unknown error" }));
|
|
109
|
+
throw new Error(`API Error: ${error.error || response.statusText}`);
|
|
110
|
+
}
|
|
111
|
+
if (!response.body) {
|
|
112
|
+
throw new Error("Response body is null");
|
|
113
|
+
}
|
|
114
|
+
const reader = response.body.getReader();
|
|
115
|
+
const decoder = new TextDecoder();
|
|
116
|
+
let buffer = "";
|
|
117
|
+
while (true) {
|
|
118
|
+
const { done, value } = await reader.read();
|
|
119
|
+
if (done) break;
|
|
120
|
+
buffer += decoder.decode(value, { stream: true });
|
|
121
|
+
const lines = buffer.split("\n");
|
|
122
|
+
buffer = lines.pop() || "";
|
|
123
|
+
for (const line of lines) {
|
|
124
|
+
if (line.startsWith("data: ")) {
|
|
125
|
+
const data = line.slice(6);
|
|
126
|
+
try {
|
|
127
|
+
const parsed = JSON.parse(data);
|
|
128
|
+
if (parsed.delta) {
|
|
129
|
+
onChunk(parsed.delta);
|
|
130
|
+
}
|
|
131
|
+
} catch {
|
|
132
|
+
}
|
|
133
|
+
} else if (line.startsWith("event: end")) {
|
|
134
|
+
if (onEnd) onEnd();
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
if (onEnd) onEnd();
|
|
140
|
+
} catch (error) {
|
|
141
|
+
if (onError) {
|
|
142
|
+
onError(error);
|
|
143
|
+
} else {
|
|
144
|
+
throw error;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
// src/markdown.ts
|
|
151
|
+
var SAFE_URL_RE = /^(https?:|mailto:|\/|#)/i;
|
|
152
|
+
var CODE_PH_OPEN = "CODE";
|
|
153
|
+
var CODE_PH_CLOSE = "ENDCODE";
|
|
154
|
+
function escapeHtml(input) {
|
|
155
|
+
return input.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
156
|
+
}
|
|
157
|
+
function sanitizeUrl(url) {
|
|
158
|
+
const trimmed = url.trim();
|
|
159
|
+
if (!SAFE_URL_RE.test(trimmed)) return "#";
|
|
160
|
+
return trimmed;
|
|
161
|
+
}
|
|
162
|
+
function renderInline(escaped) {
|
|
163
|
+
const codeSpans = [];
|
|
164
|
+
let out = escaped.replace(/`([^`\n]+)`/g, (_m, code) => {
|
|
165
|
+
const idx = codeSpans.push(code) - 1;
|
|
166
|
+
return `${CODE_PH_OPEN}${idx}${CODE_PH_CLOSE}`;
|
|
167
|
+
});
|
|
168
|
+
out = out.replace(
|
|
169
|
+
/\[([^\]]+)\]\(([^)\s]+)(?:\s+"([^&]*)")?\)/g,
|
|
170
|
+
(_m, text, url, title) => {
|
|
171
|
+
const safeUrl = sanitizeUrl(url);
|
|
172
|
+
const titleAttr = title ? ` title="${title}"` : "";
|
|
173
|
+
return `<a href="${safeUrl}" target="_blank" rel="noopener noreferrer"${titleAttr}>${text}</a>`;
|
|
174
|
+
}
|
|
175
|
+
);
|
|
176
|
+
out = out.replace(/(\*\*|__)(?=\S)([\s\S]+?)(?<=\S)\1/g, "<strong>$2</strong>");
|
|
177
|
+
out = out.replace(/(?<!\*)\*(?!\*)(?=\S)([\s\S]+?)(?<=\S)\*(?!\*)/g, "<em>$1</em>");
|
|
178
|
+
out = out.replace(/(?<![A-Za-z0-9_])_(?=\S)([\s\S]+?)(?<=\S)_(?![A-Za-z0-9_])/g, "<em>$1</em>");
|
|
179
|
+
const placeholderRe = new RegExp(`${CODE_PH_OPEN}(\\d+)${CODE_PH_CLOSE}`, "g");
|
|
180
|
+
out = out.replace(placeholderRe, (_m, idx) => {
|
|
181
|
+
const code = codeSpans[Number(idx)] ?? "";
|
|
182
|
+
return `<code>${code}</code>`;
|
|
183
|
+
});
|
|
184
|
+
return out;
|
|
185
|
+
}
|
|
186
|
+
function flushParagraph(buffer, out) {
|
|
187
|
+
if (buffer.length === 0) return;
|
|
188
|
+
const text = buffer.join("\n");
|
|
189
|
+
const html = renderInline(escapeHtml(text)).replace(/\n/g, "<br>");
|
|
190
|
+
out.push(`<p>${html}</p>`);
|
|
191
|
+
buffer.length = 0;
|
|
192
|
+
}
|
|
193
|
+
function flushList(list, out) {
|
|
194
|
+
if (!list) return null;
|
|
195
|
+
const items = list.items.map((item) => `<li>${renderInline(escapeHtml(item))}</li>`).join("");
|
|
196
|
+
out.push(`<${list.type}>${items}</${list.type}>`);
|
|
197
|
+
return null;
|
|
198
|
+
}
|
|
199
|
+
function flushQuote(quote, out) {
|
|
200
|
+
if (quote.length === 0) return;
|
|
201
|
+
const inner = renderMarkdown(quote.join("\n"));
|
|
202
|
+
out.push(`<blockquote>${inner}</blockquote>`);
|
|
203
|
+
quote.length = 0;
|
|
204
|
+
}
|
|
205
|
+
function renderMarkdown(source) {
|
|
206
|
+
if (!source) return "";
|
|
207
|
+
const lines = source.replace(/\r\n?/g, "\n").split("\n");
|
|
208
|
+
const out = [];
|
|
209
|
+
const paragraph = [];
|
|
210
|
+
const quote = [];
|
|
211
|
+
let list = null;
|
|
212
|
+
let inFence = false;
|
|
213
|
+
let fenceLang = "";
|
|
214
|
+
let fenceBuf = [];
|
|
215
|
+
const closeBlocks = () => {
|
|
216
|
+
flushParagraph(paragraph, out);
|
|
217
|
+
list = flushList(list, out);
|
|
218
|
+
flushQuote(quote, out);
|
|
219
|
+
};
|
|
220
|
+
for (const line of lines) {
|
|
221
|
+
if (inFence) {
|
|
222
|
+
if (/^\s*```\s*$/.test(line)) {
|
|
223
|
+
const code = escapeHtml(fenceBuf.join("\n"));
|
|
224
|
+
const langClass = fenceLang ? ` class="language-${escapeHtml(fenceLang)}"` : "";
|
|
225
|
+
out.push(`<pre><code${langClass}>${code}</code></pre>`);
|
|
226
|
+
fenceBuf = [];
|
|
227
|
+
fenceLang = "";
|
|
228
|
+
inFence = false;
|
|
229
|
+
} else {
|
|
230
|
+
fenceBuf.push(line);
|
|
231
|
+
}
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
const fenceMatch = line.match(/^\s*```\s*([\w+-]*)\s*$/);
|
|
235
|
+
if (fenceMatch) {
|
|
236
|
+
closeBlocks();
|
|
237
|
+
inFence = true;
|
|
238
|
+
fenceLang = fenceMatch[1] || "";
|
|
239
|
+
continue;
|
|
240
|
+
}
|
|
241
|
+
if (/^\s*$/.test(line)) {
|
|
242
|
+
closeBlocks();
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
if (/^\s*(?:---|\*\*\*|___)\s*$/.test(line) && paragraph.length === 0) {
|
|
246
|
+
closeBlocks();
|
|
247
|
+
out.push("<hr>");
|
|
248
|
+
continue;
|
|
249
|
+
}
|
|
250
|
+
const headingMatch = line.match(/^(#{1,6})\s+(.*)$/);
|
|
251
|
+
if (headingMatch) {
|
|
252
|
+
closeBlocks();
|
|
253
|
+
const level = headingMatch[1].length;
|
|
254
|
+
const content = renderInline(escapeHtml(headingMatch[2].trim()));
|
|
255
|
+
out.push(`<h${level}>${content}</h${level}>`);
|
|
256
|
+
continue;
|
|
257
|
+
}
|
|
258
|
+
const quoteMatch = line.match(/^\s*>\s?(.*)$/);
|
|
259
|
+
if (quoteMatch) {
|
|
260
|
+
flushParagraph(paragraph, out);
|
|
261
|
+
list = flushList(list, out);
|
|
262
|
+
quote.push(quoteMatch[1]);
|
|
263
|
+
continue;
|
|
264
|
+
}
|
|
265
|
+
if (quote.length > 0) flushQuote(quote, out);
|
|
266
|
+
const ulMatch = line.match(/^\s*[-*+]\s+(.*)$/);
|
|
267
|
+
const olMatch = line.match(/^\s*\d+\.\s+(.*)$/);
|
|
268
|
+
if (ulMatch || olMatch) {
|
|
269
|
+
flushParagraph(paragraph, out);
|
|
270
|
+
const type = ulMatch ? "ul" : "ol";
|
|
271
|
+
const item = ulMatch ? ulMatch[1] : olMatch[1];
|
|
272
|
+
if (!list || list.type !== type) {
|
|
273
|
+
list = flushList(list, out);
|
|
274
|
+
list = { type, items: [] };
|
|
275
|
+
}
|
|
276
|
+
list.items.push(item);
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
if (list) list = flushList(list, out);
|
|
280
|
+
paragraph.push(line);
|
|
281
|
+
}
|
|
282
|
+
if (inFence) {
|
|
283
|
+
const code = escapeHtml(fenceBuf.join("\n"));
|
|
284
|
+
const langClass = fenceLang ? ` class="language-${escapeHtml(fenceLang)}"` : "";
|
|
285
|
+
out.push(`<pre><code${langClass}>${code}</code></pre>`);
|
|
286
|
+
}
|
|
287
|
+
closeBlocks();
|
|
288
|
+
return out.join("");
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// src/Chat.ts
|
|
292
|
+
var Chat = class {
|
|
293
|
+
constructor(config) {
|
|
294
|
+
this.messages = [];
|
|
295
|
+
this.bot = new ChatBot({
|
|
296
|
+
host: config.host,
|
|
297
|
+
mode: config.mode,
|
|
298
|
+
apiKey: config.apiKey,
|
|
299
|
+
token: config.token
|
|
300
|
+
});
|
|
301
|
+
if (typeof config.container === "string") {
|
|
302
|
+
const el = document.querySelector(config.container);
|
|
303
|
+
if (!el) {
|
|
304
|
+
throw new Error(`Container element not found: ${config.container}`);
|
|
305
|
+
}
|
|
306
|
+
this.container = el;
|
|
307
|
+
} else {
|
|
308
|
+
this.container = config.container;
|
|
309
|
+
}
|
|
310
|
+
this.placeholder = config.placeholder || "Type your message...";
|
|
311
|
+
this.title = config.title || "Chat";
|
|
312
|
+
this.subtitle = config.subtitle || "";
|
|
313
|
+
this.messages = config.initialMessages || [];
|
|
314
|
+
this.onClose = config.onClose;
|
|
315
|
+
this.render();
|
|
316
|
+
this.attachEventListeners();
|
|
317
|
+
}
|
|
318
|
+
render() {
|
|
319
|
+
this.container.innerHTML = `<div class="chatter-ui-chat"><div class="chatter-ui-chat-header"><button class="chatter-ui-chat-close" type="button" aria-label="Close chat">\xD7</button><div class="chatter-ui-chat-title">${this.title}</div>${this.subtitle ? `<div class="chatter-ui-chat-subtitle">${this.subtitle}</div>` : ""}</div><div class="chatter-ui-chat-messages"></div><div class="chatter-ui-chat-input-container"><textarea class="chatter-ui-chat-input" placeholder="${this.placeholder}" rows="1"></textarea><button class="chatter-ui-chat-send" type="button"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"/></svg></button></div></div>`;
|
|
320
|
+
const messagesContainer = this.container.querySelector(".chatter-ui-chat-messages");
|
|
321
|
+
const inputElement = this.container.querySelector(".chatter-ui-chat-input");
|
|
322
|
+
const sendButton = this.container.querySelector(".chatter-ui-chat-send");
|
|
323
|
+
if (!messagesContainer || !inputElement || !sendButton) {
|
|
324
|
+
throw new Error("Required chat elements not found in container");
|
|
325
|
+
}
|
|
326
|
+
this.messagesContainer = messagesContainer;
|
|
327
|
+
this.inputElement = inputElement;
|
|
328
|
+
this.sendButton = sendButton;
|
|
329
|
+
for (const msg of this.messages) {
|
|
330
|
+
this.addMessageToUI(msg);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
attachEventListeners() {
|
|
334
|
+
const closeButton = this.container.querySelector(".chatter-ui-chat-close");
|
|
335
|
+
if (closeButton && this.onClose) {
|
|
336
|
+
closeButton.addEventListener("click", () => {
|
|
337
|
+
this.onClose?.();
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
this.sendButton.addEventListener("click", () => this.handleSend());
|
|
341
|
+
this.inputElement.addEventListener("keydown", (e) => {
|
|
342
|
+
if (e.key === "Enter" && !e.shiftKey) {
|
|
343
|
+
e.preventDefault();
|
|
344
|
+
this.handleSend();
|
|
345
|
+
}
|
|
346
|
+
});
|
|
347
|
+
this.inputElement.addEventListener("input", () => {
|
|
348
|
+
this.inputElement.style.height = "auto";
|
|
349
|
+
this.inputElement.style.height = `${Math.min(this.inputElement.scrollHeight, 120)}px`;
|
|
350
|
+
});
|
|
351
|
+
if (this.isMobile()) {
|
|
352
|
+
this.inputElement.addEventListener("focus", () => {
|
|
353
|
+
setTimeout(() => {
|
|
354
|
+
this.inputElement.scrollIntoView({ behavior: "smooth", block: "nearest" });
|
|
355
|
+
}, 300);
|
|
356
|
+
});
|
|
357
|
+
this.sendButton.addEventListener(
|
|
358
|
+
"touchend",
|
|
359
|
+
(e) => {
|
|
360
|
+
e.preventDefault();
|
|
361
|
+
this.handleSend();
|
|
362
|
+
},
|
|
363
|
+
{ passive: false }
|
|
364
|
+
);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
async handleSend() {
|
|
368
|
+
const message = this.inputElement.value.trim();
|
|
369
|
+
if (!message) return;
|
|
370
|
+
const userMessage = { role: "user", content: message };
|
|
371
|
+
this.messages.push(userMessage);
|
|
372
|
+
this.addMessageToUI(userMessage);
|
|
373
|
+
this.inputElement.value = "";
|
|
374
|
+
this.inputElement.style.height = "auto";
|
|
375
|
+
this.setInputEnabled(false);
|
|
376
|
+
try {
|
|
377
|
+
const assistantMessage = { role: "assistant", content: "" };
|
|
378
|
+
this.messages.push(assistantMessage);
|
|
379
|
+
const messageEl = this.addMessageToUI(assistantMessage);
|
|
380
|
+
const contentEl = messageEl.querySelector(".chatter-ui-message-content");
|
|
381
|
+
if (!contentEl) {
|
|
382
|
+
throw new Error("Message content element not found");
|
|
383
|
+
}
|
|
384
|
+
await this.bot.streamConversation(this.messages, {
|
|
385
|
+
onChunk: (delta) => {
|
|
386
|
+
assistantMessage.content += delta;
|
|
387
|
+
this.renderMessageContent(contentEl, assistantMessage);
|
|
388
|
+
this.scrollToBottom();
|
|
389
|
+
},
|
|
390
|
+
onEnd: () => {
|
|
391
|
+
this.renderMessageContent(contentEl, assistantMessage);
|
|
392
|
+
this.setInputEnabled(true);
|
|
393
|
+
if (!this.isMobile()) {
|
|
394
|
+
this.inputElement.focus();
|
|
395
|
+
}
|
|
396
|
+
},
|
|
397
|
+
onError: (error) => {
|
|
398
|
+
console.error("Stream error:", error);
|
|
399
|
+
assistantMessage.content = "Sorry, an error occurred. Please try again.";
|
|
400
|
+
contentEl.textContent = assistantMessage.content;
|
|
401
|
+
contentEl.classList.add("chatter-ui-message-error");
|
|
402
|
+
this.setInputEnabled(true);
|
|
403
|
+
}
|
|
404
|
+
});
|
|
405
|
+
} catch (error) {
|
|
406
|
+
console.error("Send error:", error);
|
|
407
|
+
const errorMessage = {
|
|
408
|
+
role: "assistant",
|
|
409
|
+
content: "Sorry, an error occurred. Please try again."
|
|
410
|
+
};
|
|
411
|
+
this.messages.push(errorMessage);
|
|
412
|
+
const messageEl = this.addMessageToUI(errorMessage);
|
|
413
|
+
messageEl.querySelector(".chatter-ui-message-content")?.classList.add("chatter-ui-message-error");
|
|
414
|
+
this.setInputEnabled(true);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
addMessageToUI(message) {
|
|
418
|
+
const messageEl = document.createElement("div");
|
|
419
|
+
messageEl.className = `chatter-ui-message chatter-ui-message-${message.role}`;
|
|
420
|
+
const contentEl = document.createElement("div");
|
|
421
|
+
contentEl.className = "chatter-ui-message-content";
|
|
422
|
+
messageEl.appendChild(contentEl);
|
|
423
|
+
this.renderMessageContent(contentEl, message);
|
|
424
|
+
this.messagesContainer.appendChild(messageEl);
|
|
425
|
+
this.scrollToBottom();
|
|
426
|
+
return messageEl;
|
|
427
|
+
}
|
|
428
|
+
renderMessageContent(target, message) {
|
|
429
|
+
if (message.role === "assistant") {
|
|
430
|
+
target.innerHTML = renderMarkdown(message.content);
|
|
431
|
+
} else {
|
|
432
|
+
target.innerHTML = escapeHtml(message.content).replace(/\n/g, "<br>");
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
setInputEnabled(enabled) {
|
|
436
|
+
this.inputElement.disabled = !enabled;
|
|
437
|
+
this.sendButton.disabled = !enabled;
|
|
438
|
+
}
|
|
439
|
+
scrollToBottom() {
|
|
440
|
+
this.messagesContainer.scrollTop = this.messagesContainer.scrollHeight;
|
|
441
|
+
}
|
|
442
|
+
/**
|
|
443
|
+
* Clear all messages
|
|
444
|
+
*/
|
|
445
|
+
clear() {
|
|
446
|
+
this.messages = [];
|
|
447
|
+
this.messagesContainer.innerHTML = "";
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* Get current conversation
|
|
451
|
+
*/
|
|
452
|
+
getMessages() {
|
|
453
|
+
return [...this.messages];
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* Destroy the chat instance
|
|
457
|
+
*/
|
|
458
|
+
destroy() {
|
|
459
|
+
this.container.innerHTML = "";
|
|
460
|
+
}
|
|
461
|
+
/**
|
|
462
|
+
* Detect if the device is mobile based on screen width
|
|
463
|
+
*/
|
|
464
|
+
isMobile() {
|
|
465
|
+
return window.innerWidth <= 768;
|
|
466
|
+
}
|
|
467
|
+
};
|
|
468
|
+
|
|
469
|
+
// src/ChatButton.ts
|
|
470
|
+
var ChatButton = class {
|
|
471
|
+
constructor(config) {
|
|
472
|
+
this.chat = null;
|
|
473
|
+
this.isOpen = false;
|
|
474
|
+
this.config = {
|
|
475
|
+
position: "bottom-right",
|
|
476
|
+
label: "\u{1F4AC}",
|
|
477
|
+
...config
|
|
478
|
+
};
|
|
479
|
+
this.render();
|
|
480
|
+
this.attachEventListeners();
|
|
481
|
+
}
|
|
482
|
+
render() {
|
|
483
|
+
this.buttonElement = document.createElement("button");
|
|
484
|
+
this.buttonElement.className = `chatter-ui-chat-button chatter-ui-chat-button-${this.config.position}`;
|
|
485
|
+
this.buttonElement.innerHTML = this.config.label || "\u{1F4AC}";
|
|
486
|
+
this.buttonElement.setAttribute("aria-label", "Open chat");
|
|
487
|
+
if (this.config.styles) {
|
|
488
|
+
Object.assign(this.buttonElement.style, this.config.styles);
|
|
489
|
+
}
|
|
490
|
+
this.chatContainer = document.createElement("div");
|
|
491
|
+
this.chatContainer.className = `chatter-ui-chat-popup chatter-ui-chat-popup-${this.config.position}`;
|
|
492
|
+
this.chatContainer.style.display = "none";
|
|
493
|
+
document.body.appendChild(this.buttonElement);
|
|
494
|
+
document.body.appendChild(this.chatContainer);
|
|
495
|
+
}
|
|
496
|
+
attachEventListeners() {
|
|
497
|
+
this.buttonElement.addEventListener("click", () => this.toggle());
|
|
498
|
+
document.addEventListener("keydown", (e) => {
|
|
499
|
+
if (e.key === "Escape" && this.isOpen) {
|
|
500
|
+
this.close();
|
|
501
|
+
}
|
|
502
|
+
});
|
|
503
|
+
document.addEventListener("click", (e) => {
|
|
504
|
+
if (this.isOpen && !this.chatContainer.contains(e.target) && !this.buttonElement.contains(e.target)) {
|
|
505
|
+
this.close();
|
|
506
|
+
}
|
|
507
|
+
});
|
|
508
|
+
}
|
|
509
|
+
toggle() {
|
|
510
|
+
if (this.isOpen) {
|
|
511
|
+
this.close();
|
|
512
|
+
} else {
|
|
513
|
+
this.open();
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
open() {
|
|
517
|
+
if (this.isOpen) return;
|
|
518
|
+
if (!this.chat) {
|
|
519
|
+
this.chat = new Chat({
|
|
520
|
+
host: this.config.host,
|
|
521
|
+
mode: this.config.mode,
|
|
522
|
+
apiKey: this.config.apiKey,
|
|
523
|
+
token: this.config.token,
|
|
524
|
+
container: this.chatContainer,
|
|
525
|
+
onClose: () => this.close(),
|
|
526
|
+
...this.config.chatConfig
|
|
527
|
+
});
|
|
528
|
+
}
|
|
529
|
+
this.chatContainer.style.display = "block";
|
|
530
|
+
this.buttonElement.classList.add("chatter-ui-chat-button-open");
|
|
531
|
+
this.buttonElement.setAttribute("aria-label", "Close chat");
|
|
532
|
+
this.isOpen = true;
|
|
533
|
+
if (this.isMobile()) {
|
|
534
|
+
document.body.style.overflow = "hidden";
|
|
535
|
+
document.body.style.position = "fixed";
|
|
536
|
+
document.body.style.width = "100%";
|
|
537
|
+
}
|
|
538
|
+
setTimeout(
|
|
539
|
+
() => {
|
|
540
|
+
const input = this.chatContainer.querySelector(
|
|
541
|
+
".chatter-ui-chat-input"
|
|
542
|
+
);
|
|
543
|
+
if (input) {
|
|
544
|
+
input.focus();
|
|
545
|
+
if (this.isMobile()) {
|
|
546
|
+
setTimeout(() => {
|
|
547
|
+
input.scrollIntoView({ behavior: "smooth", block: "center" });
|
|
548
|
+
}, 300);
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
},
|
|
552
|
+
this.isMobile() ? 300 : 100
|
|
553
|
+
);
|
|
554
|
+
}
|
|
555
|
+
close() {
|
|
556
|
+
if (!this.isOpen) return;
|
|
557
|
+
this.chatContainer.style.display = "none";
|
|
558
|
+
this.buttonElement.classList.remove("chatter-ui-chat-button-open");
|
|
559
|
+
this.buttonElement.setAttribute("aria-label", "Open chat");
|
|
560
|
+
this.isOpen = false;
|
|
561
|
+
if (this.isMobile()) {
|
|
562
|
+
document.body.style.overflow = "";
|
|
563
|
+
document.body.style.position = "";
|
|
564
|
+
document.body.style.width = "";
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
/**
|
|
568
|
+
* Detect if the device is mobile based on screen width
|
|
569
|
+
*/
|
|
570
|
+
isMobile() {
|
|
571
|
+
return window.innerWidth <= 768;
|
|
572
|
+
}
|
|
573
|
+
/**
|
|
574
|
+
* Destroy the chat button and cleanup
|
|
575
|
+
*/
|
|
576
|
+
destroy() {
|
|
577
|
+
this.chat?.destroy();
|
|
578
|
+
this.buttonElement.remove();
|
|
579
|
+
this.chatContainer.remove();
|
|
580
|
+
}
|
|
581
|
+
/**
|
|
582
|
+
* Check if chat is open
|
|
583
|
+
*/
|
|
584
|
+
isOpened() {
|
|
585
|
+
return this.isOpen;
|
|
586
|
+
}
|
|
587
|
+
};
|
|
588
|
+
export {
|
|
589
|
+
Chat,
|
|
590
|
+
ChatBot,
|
|
591
|
+
ChatButton
|
|
592
|
+
};
|
package/dist/core/session.d.ts
CHANGED
|
@@ -10,6 +10,7 @@ interface SessionData {
|
|
|
10
10
|
expiresAt: number;
|
|
11
11
|
metadata?: Record<string, unknown>;
|
|
12
12
|
}
|
|
13
|
+
export declare const sessionSweeper: NodeJS.Timeout;
|
|
13
14
|
export interface CreateSessionOptions {
|
|
14
15
|
/** Max requests allowed for this session (default: 20) */
|
|
15
16
|
maxRequests?: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../src/core/session.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,UAAU,WAAW;IACnB,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACpC;
|
|
1
|
+
{"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../src/core/session.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,UAAU,WAAW;IACnB,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACpC;AAaD,eAAO,MAAM,cAAc,gBAU1B,CAAC;AAGF,MAAM,WAAW,oBAAoB;IACnC,0DAA0D;IAC1D,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,2DAA2D;IAC3D,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,kDAAkD;IAClD,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACpC;AAED;;GAEG;AACH,wBAAgB,aAAa,CAAC,OAAO,GAAE,oBAAyB,GAAG,WAAW,CAiB7E;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAoBpD;AAED;;GAEG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,WAAW,GAAG,IAAI,CAE9D;AAED;;GAEG;AACH,wBAAgB,iBAAiB,IAAI,MAAM,CAE1C"}
|
package/dist/index.js
CHANGED
|
@@ -8140,7 +8140,7 @@ var VectorStore = class _VectorStore {
|
|
|
8140
8140
|
// src/core/session.ts
|
|
8141
8141
|
var import_node_crypto2 = require("node:crypto");
|
|
8142
8142
|
var sessions = /* @__PURE__ */ new Map();
|
|
8143
|
-
setInterval(
|
|
8143
|
+
var sessionSweeper = setInterval(
|
|
8144
8144
|
() => {
|
|
8145
8145
|
const now = Date.now();
|
|
8146
8146
|
for (const [key, data] of Array.from(sessions.entries())) {
|
|
@@ -8151,6 +8151,7 @@ setInterval(
|
|
|
8151
8151
|
},
|
|
8152
8152
|
5 * 60 * 1e3
|
|
8153
8153
|
);
|
|
8154
|
+
sessionSweeper.unref?.();
|
|
8154
8155
|
function createSession(options = {}) {
|
|
8155
8156
|
const { maxRequests = 20, ttl = 3600, metadata } = options;
|
|
8156
8157
|
const key = `session_${(0, import_node_crypto2.randomUUID)()}`;
|
package/dist/index.mjs
CHANGED
|
@@ -8100,7 +8100,7 @@ var VectorStore = class _VectorStore {
|
|
|
8100
8100
|
// src/core/session.ts
|
|
8101
8101
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
8102
8102
|
var sessions = /* @__PURE__ */ new Map();
|
|
8103
|
-
setInterval(
|
|
8103
|
+
var sessionSweeper = setInterval(
|
|
8104
8104
|
() => {
|
|
8105
8105
|
const now = Date.now();
|
|
8106
8106
|
for (const [key, data] of Array.from(sessions.entries())) {
|
|
@@ -8111,6 +8111,7 @@ setInterval(
|
|
|
8111
8111
|
},
|
|
8112
8112
|
5 * 60 * 1e3
|
|
8113
8113
|
);
|
|
8114
|
+
sessionSweeper.unref?.();
|
|
8114
8115
|
function createSession(options = {}) {
|
|
8115
8116
|
const { maxRequests = 20, ttl = 3600, metadata } = options;
|
|
8116
8117
|
const key = `session_${randomUUID2()}`;
|