@aparte/n8n-chat 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +207 -2
  3. package/dist/cdn/chunks/chunk-MU6PIUJC.js +206 -0
  4. package/dist/cdn/chunks/chunk-MU6PIUJC.js.map +7 -0
  5. package/dist/cdn/chunks/chunk-XAWE4EAK.js +2 -0
  6. package/dist/cdn/chunks/chunk-XAWE4EAK.js.map +7 -0
  7. package/dist/cdn/chunks/de-WJNL5YNK.js +2 -0
  8. package/dist/cdn/chunks/de-WJNL5YNK.js.map +7 -0
  9. package/dist/cdn/chunks/es-DV5N3CXP.js +2 -0
  10. package/dist/cdn/chunks/es-DV5N3CXP.js.map +7 -0
  11. package/dist/cdn/chunks/fr-YU75PBOR.js +2 -0
  12. package/dist/cdn/chunks/fr-YU75PBOR.js.map +7 -0
  13. package/dist/cdn/chunks/highlight-HDJ3ROJ4.js +153 -0
  14. package/dist/cdn/chunks/highlight-HDJ3ROJ4.js.map +7 -0
  15. package/dist/cdn/chunks/it-DZTHWNO3.js +2 -0
  16. package/dist/cdn/chunks/it-DZTHWNO3.js.map +7 -0
  17. package/dist/cdn/chunks/ja-QO442LBN.js +2 -0
  18. package/dist/cdn/chunks/ja-QO442LBN.js.map +7 -0
  19. package/dist/cdn/chunks/ko-EGFZJCXQ.js +2 -0
  20. package/dist/cdn/chunks/ko-EGFZJCXQ.js.map +7 -0
  21. package/dist/cdn/chunks/pt-BR-526LHI67.js +2 -0
  22. package/dist/cdn/chunks/pt-BR-526LHI67.js.map +7 -0
  23. package/dist/cdn/chunks/ru-5WNEMKNP.js +2 -0
  24. package/dist/cdn/chunks/ru-5WNEMKNP.js.map +7 -0
  25. package/dist/cdn/chunks/zh-CN-ABSHNLG6.js +2 -0
  26. package/dist/cdn/chunks/zh-CN-ABSHNLG6.js.map +7 -0
  27. package/dist/cdn/n8n-chat.js +97 -0
  28. package/dist/cdn/n8n-chat.js.map +7 -0
  29. package/dist/create-chat.d.ts +187 -0
  30. package/dist/highlight-DDyMJYBk.js +29 -0
  31. package/dist/highlight-DDyMJYBk.js.map +1 -0
  32. package/dist/highlight.d.ts +2 -0
  33. package/dist/icons.d.ts +7 -0
  34. package/dist/index.d.ts +11 -0
  35. package/dist/index.js +593 -0
  36. package/dist/index.js.map +1 -0
  37. package/dist/strings.d.ts +40 -0
  38. package/dist/style.css +370 -0
  39. package/dist/theme.css +368 -0
  40. package/package.json +81 -5
package/dist/index.js ADDED
@@ -0,0 +1,593 @@
1
+ import { uuid, AparteConfig, AparteErrorCode, attachConfig, AparteClient, AparteError, registerSegmentRenderer } from "@aparte/core";
2
+ import { setupMarkedStreamingProvider } from "@aparte/plugin-marked/streaming";
3
+ import { setupN8nButtons, createN8nRunner, loadN8nHistory } from "@aparte/runner-n8n";
4
+ const bubble = '<svg class="aparte-icon" viewBox="0 0 24 24" fill="currentColor"><path d="M5.5 3.5h13a3 3 0 0 1 3 3v8.5a3 3 0 0 1-3 3h-6.2l-4.8 3.6a.6.6 0 0 1-1-.5v-3.1H5.5a3 3 0 0 1-3-3V6.5a3 3 0 0 1 3-3Z"/></svg>';
5
+ const chevron = '<svg class="aparte-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9.5 6 6 6-6"/></svg>';
6
+ const plane = '<svg class="aparte-icon" viewBox="0 0 24 24" fill="currentColor"><path d="M3.4 20.2 21 12.6a.7.7 0 0 0 0-1.2L3.4 3.8a.6.6 0 0 0-.9.7L5 11l8 1-8 1-2.5 6.5a.6.6 0 0 0 .9.7Z"/></svg>';
7
+ const N8N_ICONS = {
8
+ launcherOpen: () => bubble,
9
+ launcherClose: () => chevron,
10
+ send: () => plane
11
+ };
12
+ const LANGUAGES = {
13
+ // n8n's widget's own English, word for word, so a page that switches looks the same.
14
+ en: {
15
+ strings: {
16
+ title: "Hi there! 👋",
17
+ subtitle: "Start a chat. We're here to help you 24/7.",
18
+ footer: "",
19
+ getStarted: "New Conversation",
20
+ inputPlaceholder: "Type your question..",
21
+ closeButtonTooltip: "Close chat",
22
+ repostButton: "Repost message",
23
+ reuseButton: "Reuse message"
24
+ },
25
+ initial: ["Hi there! 👋", "My name is Nathan. How can I assist you today?"]
26
+ },
27
+ fr: {
28
+ strings: {
29
+ title: "Bonjour ! 👋",
30
+ subtitle: "Démarrez une conversation. Nous sommes là pour vous aider, 24 h/24.",
31
+ footer: "",
32
+ getStarted: "Nouvelle conversation",
33
+ inputPlaceholder: "Posez votre question…",
34
+ closeButtonTooltip: "Fermer le chat",
35
+ repostButton: "Renvoyer le message",
36
+ reuseButton: "Réutiliser le message"
37
+ },
38
+ initial: ["Bonjour ! 👋", "Je m’appelle Nathan. Comment puis-je vous aider ?"],
39
+ locale: () => import("@aparte/locales/fr").then((m) => m.fr)
40
+ },
41
+ es: {
42
+ strings: {
43
+ title: "¡Hola! 👋",
44
+ subtitle: "Inicia una conversación. Estamos aquí para ayudarte, 24/7.",
45
+ footer: "",
46
+ getStarted: "Nueva conversación",
47
+ inputPlaceholder: "Escribe tu pregunta…",
48
+ closeButtonTooltip: "Cerrar el chat",
49
+ repostButton: "Volver a enviar el mensaje",
50
+ reuseButton: "Reutilizar el mensaje"
51
+ },
52
+ initial: ["¡Hola! 👋", "Me llamo Nathan. ¿En qué puedo ayudarte hoy?"],
53
+ locale: () => import("@aparte/locales/es").then((m) => m.es)
54
+ },
55
+ "pt-BR": {
56
+ strings: {
57
+ title: "Olá! 👋",
58
+ subtitle: "Comece uma conversa. Estamos aqui para ajudar, 24 horas por dia.",
59
+ footer: "",
60
+ getStarted: "Nova conversa",
61
+ inputPlaceholder: "Digite sua pergunta…",
62
+ closeButtonTooltip: "Fechar o chat",
63
+ repostButton: "Reenviar a mensagem",
64
+ reuseButton: "Reutilizar a mensagem"
65
+ },
66
+ initial: ["Olá! 👋", "Meu nome é Nathan. Como posso ajudar você hoje?"],
67
+ locale: () => import("@aparte/locales/pt-BR").then((m) => m.ptBR)
68
+ },
69
+ de: {
70
+ strings: {
71
+ title: "Hallo! 👋",
72
+ subtitle: "Starte ein Gespräch. Wir sind rund um die Uhr für dich da.",
73
+ footer: "",
74
+ getStarted: "Neues Gespräch",
75
+ inputPlaceholder: "Stell deine Frage…",
76
+ closeButtonTooltip: "Chat schließen",
77
+ repostButton: "Nachricht erneut senden",
78
+ reuseButton: "Nachricht wiederverwenden"
79
+ },
80
+ initial: ["Hallo! 👋", "Ich heiße Nathan. Wie kann ich dir heute helfen?"],
81
+ locale: () => import("@aparte/locales/de").then((m) => m.de)
82
+ },
83
+ it: {
84
+ strings: {
85
+ title: "Ciao! 👋",
86
+ subtitle: "Inizia una conversazione. Siamo qui per aiutarti, 24 ore su 24.",
87
+ footer: "",
88
+ getStarted: "Nuova conversazione",
89
+ inputPlaceholder: "Scrivi la tua domanda…",
90
+ closeButtonTooltip: "Chiudi la chat",
91
+ repostButton: "Invia di nuovo il messaggio",
92
+ reuseButton: "Riusa il messaggio"
93
+ },
94
+ initial: ["Ciao! 👋", "Mi chiamo Nathan. Come posso aiutarti oggi?"],
95
+ locale: () => import("@aparte/locales/it").then((m) => m.it)
96
+ },
97
+ ru: {
98
+ strings: {
99
+ title: "Здравствуйте! 👋",
100
+ subtitle: "Начните разговор. Мы на связи круглосуточно.",
101
+ footer: "",
102
+ getStarted: "Новый разговор",
103
+ inputPlaceholder: "Введите ваш вопрос…",
104
+ closeButtonTooltip: "Закрыть чат",
105
+ repostButton: "Отправить сообщение ещё раз",
106
+ reuseButton: "Использовать сообщение снова"
107
+ },
108
+ initial: ["Здравствуйте! 👋", "Меня зовут Натан. Чем могу помочь?"],
109
+ locale: () => import("@aparte/locales/ru").then((m) => m.ru)
110
+ },
111
+ ja: {
112
+ strings: {
113
+ title: "こんにちは!👋",
114
+ subtitle: "チャットを始めましょう。24時間いつでもお手伝いします。",
115
+ footer: "",
116
+ getStarted: "新しい会話",
117
+ inputPlaceholder: "質問を入力してください…",
118
+ closeButtonTooltip: "チャットを閉じる",
119
+ repostButton: "メッセージを再送信",
120
+ reuseButton: "メッセージを再利用"
121
+ },
122
+ initial: ["こんにちは!👋", "ネイサンです。今日はどのようなご用件でしょうか?"],
123
+ locale: () => import("@aparte/locales/ja").then((m) => m.ja)
124
+ },
125
+ ko: {
126
+ strings: {
127
+ title: "안녕하세요! 👋",
128
+ subtitle: "대화를 시작하세요. 24시간 언제든 도와드릴게요.",
129
+ footer: "",
130
+ getStarted: "새 대화",
131
+ inputPlaceholder: "질문을 입력하세요…",
132
+ closeButtonTooltip: "채팅 닫기",
133
+ repostButton: "메시지 다시 보내기",
134
+ reuseButton: "메시지 다시 사용"
135
+ },
136
+ initial: ["안녕하세요! 👋", "저는 네이선입니다. 무엇을 도와드릴까요?"],
137
+ locale: () => import("@aparte/locales/ko").then((m) => m.ko)
138
+ },
139
+ "zh-CN": {
140
+ strings: {
141
+ title: "你好!👋",
142
+ subtitle: "开始聊天吧。我们全天候为你服务。",
143
+ footer: "",
144
+ getStarted: "新对话",
145
+ inputPlaceholder: "输入你的问题…",
146
+ closeButtonTooltip: "关闭聊天",
147
+ repostButton: "重新发送消息",
148
+ reuseButton: "重新使用消息"
149
+ },
150
+ initial: ["你好!👋", "我是 Nathan。今天有什么可以帮你的?"],
151
+ locale: () => import("@aparte/locales/zh-CN").then((m) => m.zhCN)
152
+ }
153
+ };
154
+ function shippedLanguage(tag) {
155
+ if (LANGUAGES[tag]) return tag;
156
+ const primary = tag.split("-")[0]?.toLowerCase() ?? "";
157
+ return Object.keys(LANGUAGES).find((key) => key.split("-")[0]?.toLowerCase() === primary) ?? "en";
158
+ }
159
+ function stringsFor(language, i18n) {
160
+ return { ...LANGUAGES[shippedLanguage(language)].strings, ...i18n?.[language] ?? {} };
161
+ }
162
+ function initialMessagesFor(language) {
163
+ return LANGUAGES[shippedLanguage(language)].initial;
164
+ }
165
+ function loadLocale(language) {
166
+ return LANGUAGES[shippedLanguage(language)].locale?.();
167
+ }
168
+ const STORAGE_KEY = "n8n-chat/sessionId";
169
+ const WORKFLOW_ERROR = "N8N_WORKFLOW_ERROR";
170
+ const componentsByChat = /* @__PURE__ */ new WeakMap();
171
+ let componentRendererRegistered = false;
172
+ function registerComponentRenderer() {
173
+ if (componentRendererRegistered) return;
174
+ componentRendererRegistered = true;
175
+ registerSegmentRenderer({
176
+ type: "n8n-component",
177
+ render: (segment) => {
178
+ const { key, arguments: args } = segment;
179
+ const holder = document.createElement("div");
180
+ holder.className = "aparte-segment aparte-n8n__component";
181
+ holder.setAttribute("data-component", key);
182
+ queueMicrotask(() => {
183
+ const chat = holder.closest("aparte-chat");
184
+ const draw = chat ? componentsByChat.get(chat)?.[key] : void 0;
185
+ if (!draw) {
186
+ console.warn(`[aparte] n8n: no messageComponents entry for "${key}".`);
187
+ return;
188
+ }
189
+ const out = draw(args);
190
+ if (typeof out === "string") holder.innerHTML = out;
191
+ else holder.replaceChildren(out);
192
+ });
193
+ return holder;
194
+ }
195
+ });
196
+ }
197
+ function read(key) {
198
+ try {
199
+ return localStorage.getItem(key) ?? void 0;
200
+ } catch {
201
+ return void 0;
202
+ }
203
+ }
204
+ function write(key, value) {
205
+ try {
206
+ localStorage.setItem(key, value);
207
+ } catch {
208
+ }
209
+ }
210
+ function resolveTarget(target) {
211
+ if (typeof target !== "string") return target;
212
+ const found = document.querySelector(target);
213
+ if (found) return found;
214
+ const el2 = document.createElement("div");
215
+ if (target.startsWith("#")) el2.id = target.slice(1);
216
+ else if (target.startsWith(".")) el2.className = target.slice(1);
217
+ document.body.appendChild(el2);
218
+ return el2;
219
+ }
220
+ function el(tag, className, text) {
221
+ const node = document.createElement(tag);
222
+ if (className) node.className = className;
223
+ if (text !== void 0) node.textContent = text;
224
+ return node;
225
+ }
226
+ let instances = 0;
227
+ function createChat(options) {
228
+ const mode = options.mode ?? "window";
229
+ const language = options.defaultLanguage ?? "en";
230
+ const strings = stringsFor(language, options.i18n);
231
+ const loadPrevious = options.loadPreviousSession ?? true;
232
+ const initial = options.initialMessages ?? initialMessagesFor(language);
233
+ const instance = ++instances;
234
+ const titleId = `aparte-n8n-title-${instance}`;
235
+ let sessionId = options.sessionId ?? (loadPrevious ? read(STORAGE_KEY) : void 0) ?? uuid();
236
+ if (loadPrevious && !options.sessionId) write(STORAGE_KEY, sessionId);
237
+ const config = new AparteConfig();
238
+ if (options.locale) config.setLocale(options.locale);
239
+ let destroyed = false;
240
+ void loadLocale(language)?.then((locale) => {
241
+ if (!destroyed && !options.locale) config.setLocale(locale);
242
+ }, (error) => console.warn("[aparte] n8n: the chat's language could not be loaded; it stays in English.", error));
243
+ config.registerIcons(N8N_ICONS);
244
+ if (options.enableMessageActions) {
245
+ config.registerAction({ id: "n8n-repost", icon: "retry", label: strings.repostButton, zones: ["bubble"], bubble: { roles: ["user"] } });
246
+ config.registerAction({ id: "n8n-reuse", icon: "edit", label: strings.reuseButton, zones: ["bubble"], bubble: { roles: ["user"] } });
247
+ }
248
+ config.setHostHandlers({ attachmentPreview: true, filePreview: true });
249
+ setupN8nButtons(config);
250
+ config.setErrorRenderer(({ message, sentence, code }) => {
251
+ const workflow = code === WORKFLOW_ERROR;
252
+ const card2 = el("div", "aparte-segment aparte-alert aparte-alert--danger aparte-segment-error");
253
+ if (code) card2.setAttribute("data-error-code", workflow ? AparteErrorCode.PROVIDER_ERROR : code);
254
+ const icon = el("span", "aparte-alert__icon");
255
+ icon.innerHTML = config.getIcon("error") || "⚠";
256
+ const body = el("div", "aparte-alert__body");
257
+ body.append(
258
+ el("div", "aparte-alert__title", config.t("error")),
259
+ el("div", "aparte-alert__message", workflow ? config.t("errorNoAnswer") : sentence ?? message)
260
+ );
261
+ if (workflow && message) body.append(el("p", "aparte-n8n__error-detail", message));
262
+ card2.append(icon, body);
263
+ return card2;
264
+ });
265
+ setupMarkedStreamingProvider(void 0, config);
266
+ let highlighter;
267
+ config.setHighlightProvider(async (code, lang) => {
268
+ highlighter ??= import("./highlight-DDyMJYBk.js").then((m) => m.createHighlighter());
269
+ return (await highlighter)(code, lang);
270
+ });
271
+ const card = el("section", "aparte-n8n__window");
272
+ card.setAttribute("aria-labelledby", titleId);
273
+ const header = el("header", "aparte-n8n__header");
274
+ const heading = el("div", "aparte-n8n__heading");
275
+ const title = el("p", "aparte-n8n__title", strings.title);
276
+ title.id = titleId;
277
+ heading.append(title);
278
+ if (strings.subtitle) heading.append(el("p", "aparte-n8n__subtitle", strings.subtitle));
279
+ header.append(heading);
280
+ if (mode === "window" && options.showWindowCloseButton) {
281
+ const close = el("button", "aparte-btn aparte-btn--icon aparte-btn--ghost aparte-n8n__close");
282
+ close.type = "button";
283
+ close.setAttribute("aria-label", strings.closeButtonTooltip);
284
+ close.setAttribute("data-aparte-launcher-close", "");
285
+ const icon = el("aparte-icon");
286
+ icon.setAttribute("name", "close");
287
+ close.append(icon);
288
+ header.append(close);
289
+ }
290
+ const chat = el("aparte-chat", "aparte-n8n__chat");
291
+ chat.id = `aparte-n8n-chat-${instance}`;
292
+ if (options.messageComponents) {
293
+ registerComponentRenderer();
294
+ componentsByChat.set(chat, options.messageComponents);
295
+ }
296
+ const composer = el("aparte-composer");
297
+ composer.setAttribute("placeholder", strings.inputPlaceholder);
298
+ let suggestions;
299
+ if (options.suggestions?.length) {
300
+ suggestions = el("aparte-suggestions");
301
+ suggestions.setAttribute("suggestions", JSON.stringify(options.suggestions.map((text) => ({ label: text, prompt: text }))));
302
+ composer.append(suggestions);
303
+ }
304
+ const shell = el("div", "aparte-composer-shell");
305
+ const row = el("div", "aparte-composer-row");
306
+ row.append(el("aparte-composer-input"));
307
+ if (options.allowFileUploads) {
308
+ shell.append(el("aparte-composer-attachments"));
309
+ const add = el("aparte-composer-add-attachment");
310
+ if (options.allowedFilesMimeTypes) add.setAttribute("accept", options.allowedFilesMimeTypes);
311
+ row.append(add);
312
+ }
313
+ row.append(el("aparte-composer-send"));
314
+ shell.append(row);
315
+ composer.append(shell);
316
+ chat.append(el("aparte-chat-viewport"), el("aparte-elicitation"), composer);
317
+ card.append(header, chat);
318
+ if (strings.footer) card.append(el("p", "aparte-n8n__footer", strings.footer));
319
+ let welcome;
320
+ if (options.showWelcomeScreen) {
321
+ welcome = el("div", "aparte-n8n__welcome");
322
+ const start = el("button", "aparte-btn aparte-btn--primary aparte-btn--solid aparte-n8n__start", strings.getStarted);
323
+ start.type = "button";
324
+ start.addEventListener("click", () => {
325
+ welcome.hidden = true;
326
+ chat.hidden = false;
327
+ chat.querySelector("aparte-composer-input")?.focusEnd?.();
328
+ });
329
+ welcome.append(start);
330
+ chat.hidden = true;
331
+ card.insertBefore(welcome, chat);
332
+ }
333
+ let root;
334
+ if (mode === "window") {
335
+ root = el("aparte-launcher", "aparte-n8n aparte-n8n--window");
336
+ root.append(card);
337
+ } else {
338
+ root = el("div", "aparte-n8n aparte-n8n--fullscreen");
339
+ root.append(card);
340
+ }
341
+ const scheme = options.colorScheme ?? "light";
342
+ if (scheme !== "auto") root.setAttribute("data-aparte-theme", scheme);
343
+ root.setAttribute("lang", language);
344
+ if (mode === "window") {
345
+ root.addEventListener("aparte-launcher-toggle", (event) => {
346
+ const { open, sheet } = event.detail;
347
+ if (open && sheet) {
348
+ card.setAttribute("role", "dialog");
349
+ card.setAttribute("aria-modal", "true");
350
+ } else {
351
+ card.removeAttribute("role");
352
+ card.removeAttribute("aria-modal");
353
+ }
354
+ });
355
+ }
356
+ attachConfig(root, config);
357
+ resolveTarget(options.target ?? "#n8n-chat").append(root);
358
+ const firstMessages = () => initial.map((content, i) => ({
359
+ id: `n8n-initial-${i}`,
360
+ role: "assistant",
361
+ content,
362
+ timestamp: Date.now() - initial.length + i,
363
+ status: "completed"
364
+ }));
365
+ const seeded = () => (options.messageHistory ?? []).map((m, i) => {
366
+ const base = { id: `n8n-seed-${i}`, role: m.sender === "user" ? "user" : "assistant", timestamp: Date.now(), status: "completed" };
367
+ if (m.type === "component") {
368
+ const segment = { id: `n8n-seed-${i}-component`, type: "n8n-component", key: m.key, arguments: m.arguments ?? {} };
369
+ return { ...base, content: "", segments: [segment] };
370
+ }
371
+ return { ...base, content: m.text };
372
+ });
373
+ const transparent = new Set((options.messageHistory ?? []).flatMap((m, i) => m.transparent ? [`n8n-seed-${i}`] : []));
374
+ if (transparent.size) {
375
+ new MutationObserver(() => {
376
+ for (const id of transparent) {
377
+ const bubble2 = chat.querySelector(`aparte-chat-bubble[message-id="${id}"]`);
378
+ if (bubble2 && !bubble2.hasAttribute("data-n8n-transparent")) bubble2.setAttribute("data-n8n-transparent", "");
379
+ }
380
+ }).observe(chat, { childList: true, subtree: true });
381
+ }
382
+ const show = (messages) => chat.viewport?.setMessages(messages);
383
+ show([...firstMessages(), ...seeded()]);
384
+ if (options.messageHistory?.length && suggestions) suggestions.hidden = true;
385
+ let loaded = 0;
386
+ let historyRequest;
387
+ const loadHistory = () => {
388
+ const ticket = ++loaded;
389
+ historyRequest = new AbortController();
390
+ void loadN8nHistory({
391
+ webhookUrl: options.webhookUrl,
392
+ sessionId,
393
+ ...options.metadata ? { metadata: options.metadata } : {},
394
+ ...options.chatSessionKey ? { chatSessionKey: options.chatSessionKey } : {},
395
+ headers: () => ({ ...options.webhookConfig?.headers ?? {} }),
396
+ ...options.fetch ? { fetch: options.fetch } : {},
397
+ signal: historyRequest.signal
398
+ }).then((history) => {
399
+ if (ticket !== loaded || history.length === 0) return;
400
+ if (suggestions) suggestions.hidden = true;
401
+ show([...firstMessages(), ...history]);
402
+ }, (error) => {
403
+ if (historyRequest?.signal.aborted) return;
404
+ console.warn(`[aparte] n8n: ${error instanceof Error ? error.message : String(error)}`);
405
+ });
406
+ };
407
+ if (loadPrevious) {
408
+ if (mode === "window") {
409
+ const onFirstOpen = (event) => {
410
+ if (!event.detail.open) return;
411
+ root.removeEventListener("aparte-launcher-toggle", onFirstOpen);
412
+ if (loaded === 0) loadHistory();
413
+ };
414
+ root.addEventListener("aparte-launcher-toggle", onFirstOpen);
415
+ } else {
416
+ loadHistory();
417
+ }
418
+ }
419
+ let lastSent = "";
420
+ let sentIn = sessionId;
421
+ let busy = false;
422
+ const queued = [];
423
+ chat.addEventListener("aparte-send", (event) => {
424
+ loaded++;
425
+ lastSent = String(event.detail?.content ?? "");
426
+ sentIn = sessionId;
427
+ if (suggestions) suggestions.hidden = true;
428
+ });
429
+ const dispatchSend = (text, files) => {
430
+ if (welcome && !welcome.hidden) {
431
+ welcome.hidden = true;
432
+ chat.hidden = false;
433
+ }
434
+ chat.dispatchEvent(new CustomEvent("aparte-send", {
435
+ detail: { content: text, timestamp: Date.now(), targetId: chat.id, ...files?.length ? { files } : {} },
436
+ bubbles: true,
437
+ composed: true
438
+ }));
439
+ };
440
+ const settle = () => {
441
+ busy = false;
442
+ const next = queued.shift();
443
+ if (next !== void 0) queueMicrotask(() => dispatchSend(next));
444
+ };
445
+ chat.addEventListener("aparte-message-start", () => {
446
+ busy = true;
447
+ });
448
+ for (const type of ["aparte-message-done", "aparte-message-error", "aparte-message-aborted"]) chat.addEventListener(type, settle);
449
+ const onStopped = (event) => {
450
+ if (event.detail?.targetId === chat.id) settle();
451
+ };
452
+ window.addEventListener("aparte-message-aborted", onStopped);
453
+ let runSession = sessionId;
454
+ const runner = createN8nRunner({
455
+ webhookUrl: options.webhookUrl,
456
+ sessionId: () => runSession,
457
+ headers: () => ({ ...options.webhookConfig?.headers ?? {} }),
458
+ ...options.fetch ? { fetch: options.fetch } : {},
459
+ ...options.metadata ? { metadata: options.metadata } : {},
460
+ ...options.chatInputKey ? { chatInputKey: options.chatInputKey } : {},
461
+ ...options.chatSessionKey ? { chatSessionKey: options.chatSessionKey } : {}
462
+ });
463
+ const streamRunner = async (opts) => {
464
+ const message = lastSent;
465
+ const session = sentIn;
466
+ await options.beforeMessageSent?.(message);
467
+ if (opts.signal.aborted) return void 0;
468
+ runSession = session;
469
+ let reply = "";
470
+ let done = false;
471
+ const result = await runner({
472
+ ...opts,
473
+ emitter: (event) => {
474
+ if (event.type === "text-delta") reply += event.delta;
475
+ if (event.type === "run-done") done = true;
476
+ opts.emitter(event);
477
+ }
478
+ }).catch((error) => {
479
+ const failure = error;
480
+ if (failure?.code === AparteErrorCode.PROVIDER_ERROR && failure.httpStatus === void 0) {
481
+ throw new AparteError(failure.message ?? "", WORKFLOW_ERROR, failure.data, error);
482
+ }
483
+ throw error;
484
+ });
485
+ if (done && options.afterMessageSent) {
486
+ const hook = options.afterMessageSent;
487
+ queueMicrotask(() => {
488
+ Promise.resolve().then(() => hook(message, { output: reply, message: reply, hasReceivedChunks: reply.length > 0 })).catch((error) => console.warn("[aparte] n8n: afterMessageSent threw:", error));
489
+ });
490
+ }
491
+ return result;
492
+ };
493
+ const client = new AparteClient({ config, streamRunner, rawFileInject: "none", scopeToTargetId: chat.id });
494
+ client.start();
495
+ const lookup = () => chat.viewport;
496
+ const onAction = (event) => {
497
+ const { actionId, messageId } = event.detail;
498
+ if (actionId !== "n8n-repost" && actionId !== "n8n-reuse") return;
499
+ const message = lookup()?.getMessage?.(messageId);
500
+ if (!message) return;
501
+ if (actionId === "n8n-reuse") {
502
+ composer.setValue(message.content ?? "");
503
+ chat.querySelector("aparte-composer-input")?.focusEnd?.();
504
+ return;
505
+ }
506
+ void Promise.all((message.attachments ?? []).map(async (a) => {
507
+ const blob = await (await fetch(a.url)).blob();
508
+ return new File([blob], a.name, { type: a.type || blob.type });
509
+ })).then((files) => {
510
+ if (busy) queued.push(message.content ?? "");
511
+ else dispatchSend(message.content ?? "", files);
512
+ }, (error) => console.warn("[aparte] n8n: a file of that message could not be read again:", error));
513
+ };
514
+ chat.addEventListener("aparte-action", onAction);
515
+ let recall = -1;
516
+ let draft = "";
517
+ const input = () => chat.querySelector("aparte-composer-input");
518
+ composer.addEventListener("keydown", (event) => {
519
+ if (event.key !== "ArrowUp" && event.key !== "ArrowDown") return;
520
+ if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || event.isComposing) return;
521
+ if (!event.target?.closest("aparte-composer-input")) return;
522
+ const sent = (lookup()?.getMessages?.() ?? []).filter((m) => m.role === "user" && m.content?.trim()).map((m) => m.content ?? "");
523
+ if (event.key === "ArrowUp") {
524
+ if (recall === -1 && composer.value !== "" || recall >= sent.length - 1) return;
525
+ if (recall === -1) draft = composer.value;
526
+ recall++;
527
+ } else {
528
+ if (recall === -1) return;
529
+ recall--;
530
+ }
531
+ event.preventDefault();
532
+ composer.setValue(recall === -1 ? draft : sent[sent.length - 1 - recall] ?? "");
533
+ input()?.focusEnd?.();
534
+ });
535
+ chat.addEventListener("aparte-send", () => {
536
+ recall = -1;
537
+ draft = "";
538
+ });
539
+ chat.addEventListener("click", (event) => {
540
+ if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
541
+ const link = event.target?.closest(".aparte-message-content a[href]");
542
+ if (!link || link.getAttribute("href")?.startsWith("#")) return;
543
+ event.preventDefault();
544
+ window.open(link.href, "_blank", "noopener");
545
+ });
546
+ chat.addEventListener("aparte-attachment-preview", (event) => {
547
+ const { url } = event.detail;
548
+ if (url) window.open(url, "_blank", "noopener");
549
+ });
550
+ const setDisabled = (disabled) => composer.toggleAttribute("disabled", disabled);
551
+ if (typeof options.disabled === "object" ? options.disabled?.value : options.disabled) setDisabled(true);
552
+ const launcher = () => mode === "window" ? root : void 0;
553
+ const destroy = () => {
554
+ destroyed = true;
555
+ historyRequest?.abort();
556
+ queued.length = 0;
557
+ window.removeEventListener("aparte-message-aborted", onStopped);
558
+ client.stop();
559
+ root.remove();
560
+ };
561
+ return {
562
+ element: root,
563
+ get sessionId() {
564
+ return sessionId;
565
+ },
566
+ open: () => launcher()?.show(),
567
+ close: () => launcher()?.close(),
568
+ toggle: () => launcher()?.toggle(),
569
+ send: (text) => {
570
+ if (busy) queued.push(text);
571
+ else dispatchSend(text);
572
+ },
573
+ reset: () => {
574
+ queued.length = 0;
575
+ if (composer.streaming) composer.cancel();
576
+ client.abort();
577
+ busy = false;
578
+ historyRequest?.abort();
579
+ loaded++;
580
+ sessionId = options.sessionId ?? uuid();
581
+ if (loadPrevious && !options.sessionId) write(STORAGE_KEY, sessionId);
582
+ if (suggestions) suggestions.hidden = false;
583
+ show(firstMessages());
584
+ },
585
+ setDisabled,
586
+ destroy,
587
+ unmount: destroy
588
+ };
589
+ }
590
+ export {
591
+ createChat
592
+ };
593
+ //# sourceMappingURL=index.js.map