@vettvangur/ai-sdk 0.1.14 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,12 +3,20 @@
3
3
  Framework-agnostic, unstyled AI chat primitives for server-rendered shells.
4
4
 
5
5
  It exports protocol-v1 contracts, parsing and SSE stream-reading primitives, a headless chat session,
6
- and a DOM binding for a server-rendered shell. It does not include styles or project-specific tools.
6
+ a DOM binding for a server-rendered shell, and generic cards a host can draw tool results with. It
7
+ ships no styles: every element it renders carries a BEM class, and the project styles those.
7
8
 
8
9
  ```html
9
10
  <section data-ai-chat data-ai-chat-endpoint="/webapi/aichat/stream"
10
- data-ai-chat-antiforgery-header="RequestVerificationToken" data-ai-chat-antiforgery-token="…">
11
- <div data-ai-chat-thread></div>
11
+ data-ai-chat-antiforgery-header="RequestVerificationToken" data-ai-chat-antiforgery-token="…"
12
+ data-ai-chat-offset=".header"
13
+ data-ai-chat-label-error="Something went wrong."
14
+ data-ai-chat-tool-find-offices="Looking up offices">
15
+ <div data-ai-chat-scroll>
16
+ <div data-ai-chat-thread>
17
+ <button type="button" data-ai-chat-suggestion="Where is my shipment?">Where is my shipment?</button>
18
+ </div>
19
+ </div>
12
20
  <form data-ai-chat-form><textarea data-ai-chat-input></textarea><button data-ai-chat-send>Send</button></form>
13
21
  <button type="button" data-ai-chat-reset>Reset</button>
14
22
  </section>
@@ -28,6 +36,32 @@ const chat = bindChat(document.querySelector('[data-ai-chat]')!, { registry })
28
36
  // Call chat.destroy() when its server-rendered shell is removed.
29
37
  ```
30
38
 
39
+ ## The shell
40
+
41
+ `bindChat` needs the form, input and thread; the rest is optional.
42
+
43
+ | Markup | What the binding does with it |
44
+ | --- | --- |
45
+ | `data-ai-chat-suggestion` | Asks its value (or its text) as the question. |
46
+ | `data-ai-chat-reset` | Clears the thread back to how the server rendered it and starts a new conversation. |
47
+ | `data-ai-chat-scroll` | The element the thread scrolls in. While an answer arrives, the latest question is held at its top; scrolling by hand lets go until the next question. |
48
+ | `data-ai-chat-offset` | A selector for the element the shell sits under, such as a fixed header. Its height is kept in `--vv-ai-chat-offset` on the root. `offsetElement` does the same from script. |
49
+ | `data-ai-chat-label-*` | Labels, in kebab case: `error`, `timeout`, `tool-running`, `tool-complete`, `tool-failed`, `tool-interrupted`, `sources`, `details`, `table`, `table-scroll`. The `labels` option wins over the attribute. |
50
+ | `data-ai-chat-tool-*` | The progress label for one tool, with underscores in its name written as hyphens. Other tools show `tool-running`. The `toolLabels` option wins over the attribute. |
51
+
52
+ The binding also keeps `--vv-ai-chat-keyboard` on the root at the height an on-screen keyboard
53
+ covers, grows the input to fit what is typed, sets `aria-busy` on the root while a turn is in flight,
54
+ and sends a `conversationId` context value that changes on every reset.
55
+
56
+ Elements it adds carry classes under `CHAT_CLASS` (`vv-ai-chat`): `__message` with `--user` or
57
+ `--assistant`, `__text`, `__tool` with `--done` and `--failed`, `__tool-dot`, `__tool-label`,
58
+ `__tool-status`, `__result` around a rendered tool result, and `__error`.
59
+
60
+ `binding.setFormContext(name, summary, followUp)` sends what a visitor entered into an embedded form
61
+ with every later question. An unchanged summary is not sent again, and `followUp` is added as an
62
+ assistant reply only the first time. Renderers and surfaces receive the resolved `labels`, as does
63
+ `binding.labels`.
64
+
31
65
  `createChatSession()` is available when a host owns its own rendering. It sends JSON POST requests
32
66
  to the configured same-origin endpoint and reads its SSE response. Supply the antiforgery header
33
67
  through `bindChat` options or the root attributes; blank header names or tokens are omitted.
@@ -38,6 +72,30 @@ from authored `data-ai-action` markup and receive an optional authored `data-ai-
38
72
  Neither server payloads nor model output become executable markup. Generic answer cards, links and
39
73
  Markdown are rendered as safe DOM nodes. Host callbacks must return DOM nodes, not HTML strings.
40
74
 
75
+ ## Surfaces
76
+
77
+ `createTemplateItemSurface({ template, attribute, key })` shows one item from an authored list
78
+ template: it clones `template[data-template]` and removes every element carrying `attribute` whose
79
+ value is not the payload's `key` field. Register it with `registry.registerSurface`.
80
+
81
+ ## Cards
82
+
83
+ A host maps a tool's payload onto these and registers the result as that tool's renderer. Each
84
+ returns null when there is nothing to show.
85
+
86
+ - `renderContactCard` (`vv-ai-contact-card`): name, subtitle, image (such as a flag), address, phone
87
+ and email links, and labelled groups of hours. Parts: `__head`, `__image`, `__title`, `__name`,
88
+ `__subtitle`, `__address`, `__links`, `__link`, `__hours`, `__hours-label`, `__hours-row`,
89
+ `__hours-days`, `__hours-time`, `__hours-note`.
90
+ - `renderMediaCard` (`vv-ai-media-card`, `--with-image`): a title and facts led by an image. Parts:
91
+ `__figure`, `__image`, `__body`, `__title`, `__facts`, `__fact`, `__fact-label`, `__fact-value`.
92
+ - `renderActions` (`vv-ai-actions`): buttons that run a registered action and safe links, each
93
+ `__action` with `--primary` or `--secondary`.
94
+ - `renderCardList` (`vv-ai-card-list`, `--{modifier}`): several cards from one result.
95
+
96
+ `createSafeImage`, `createSafeLink` and `createPart` are the builders these use, exported for a
97
+ host's own renderers.
98
+
41
99
  ## Answer cards
42
100
 
43
101
  `renderAnswerCard()` draws a `kind: 'answer'` payload as DOM, or returns null when it breaks any
package/dist/index.d.ts CHANGED
@@ -127,6 +127,7 @@ type AiChatExtensionContext = {
127
127
  tool: string;
128
128
  data: unknown;
129
129
  reply: string | null;
130
+ labels: AiChatLabels;
130
131
  };
131
132
  type AiChatRenderer = (context: AiChatExtensionContext) => Node | null;
132
133
  type AiChatSurface = (context: AiChatExtensionContext) => Node | null;
@@ -153,24 +154,61 @@ type AiChatBindings = {
153
154
  antiforgeryToken?: string;
154
155
  timeoutMs?: number;
155
156
  labels?: Partial<AiChatLabels>;
156
- classes?: Partial<AiChatClasses>;
157
+ toolLabels?: Record<string, string>;
158
+ offsetElement?: HTMLElement | null;
157
159
  registry?: AiChatRegistry;
158
160
  onEmbedded?: (element: HTMLElement) => void;
159
161
  onError?: (error: Error) => void;
160
162
  };
161
- type AiChatClasses = {
162
- messageUser: string;
163
- messageAssistant: string;
164
- text: string;
165
- tool: string;
166
- card: string;
167
- error: string;
168
- };
169
163
  type AiChatBinding = {
170
164
  session: AiChatSession;
165
+ labels: Readonly<AiChatLabels>;
171
166
  appendAssistantReply(text: string): void;
167
+ setFormContext(name: string, summary: string, followUp?: string | null): void;
172
168
  destroy(): void;
173
169
  };
170
+ type AiCardImage = {
171
+ url: string;
172
+ url2x?: string | null;
173
+ alt?: string | null;
174
+ width?: number | null;
175
+ height?: number | null;
176
+ };
177
+ type AiContactCardHoursRow = {
178
+ label: string;
179
+ value: string;
180
+ note?: string | null;
181
+ };
182
+ type AiContactCardHours = {
183
+ label?: string | null;
184
+ rows: AiContactCardHoursRow[];
185
+ };
186
+ type AiContactCard = {
187
+ name: string;
188
+ subtitle?: string | null;
189
+ image?: AiCardImage | null;
190
+ address?: string | null;
191
+ phone?: string | null;
192
+ email?: string | null;
193
+ hours?: AiContactCardHours[] | null;
194
+ };
195
+ type AiMediaCard = {
196
+ title: string;
197
+ image?: AiCardImage | null;
198
+ facts?: AiAnswerCardFact[] | null;
199
+ };
200
+ type AiChatActionItem = {
201
+ label: string;
202
+ action?: string | null;
203
+ value?: string | null;
204
+ url?: string | null;
205
+ primary?: boolean;
206
+ };
207
+ type AiTemplateItemSurfaceOptions = {
208
+ template: string;
209
+ attribute: string;
210
+ key: string;
211
+ };
174
212
  //#endregion
175
213
  //#region src/answer-card.d.ts
176
214
  declare const MAX_ANSWER_CARD_SECTIONS = 12;
@@ -197,13 +235,54 @@ declare function isAnswerCard(value: unknown): value is AiAnswerCard;
197
235
  declare function renderAnswerCard(document: Document, data: unknown, labels: AiAnswerCardLabels): HTMLElement | null;
198
236
  //#endregion
199
237
  //#region src/bind.d.ts
238
+ /**
239
+ * Every element the binding adds to the thread carries a class under this block, so a host styles
240
+ * the chat by class rather than by the order its elements happen to come in.
241
+ */
242
+ declare const CHAT_CLASS = "vv-ai-chat";
200
243
  declare function bindChat(root: HTMLElement, options?: AiChatBindings): AiChatBinding;
201
244
  //#endregion
245
+ //#region src/cards.d.ts
246
+ /** Block classes of the cards below. Every element a card renders carries a class under its block. */
247
+ declare const CARD_LIST_CLASS = "vv-ai-card-list";
248
+ declare const CONTACT_CARD_CLASS = "vv-ai-contact-card";
249
+ declare const MEDIA_CARD_CLASS = "vv-ai-media-card";
250
+ declare const ACTIONS_CLASS = "vv-ai-actions";
251
+ /**
252
+ * Several cards from one tool result, under `vv-ai-card-list` and `vv-ai-card-list--{modifier}`.
253
+ * Items that render nothing are skipped, and a list with nothing in it is null.
254
+ */
255
+ declare function renderCardList<T>(document: Document, items: unknown, render: (item: T) => Node | null, modifier?: string): HTMLElement | null;
256
+ /**
257
+ * A place or person to get in touch with: name, an optional subtitle and image (such as a flag),
258
+ * address, phone and email links, and any number of labelled groups of hours. Null without a name.
259
+ */
260
+ declare function renderContactCard(document: Document, data: unknown): HTMLElement | null;
261
+ /**
262
+ * A thing best recognised by its picture, with labelled facts beside it. The image leads, and the
263
+ * card carries `--with-image` when it has one. Null without a title.
264
+ */
265
+ declare function renderMediaCard(document: Document, data: unknown): HTMLElement | null;
266
+ /**
267
+ * A row of things the visitor can do next. An item with `action` is a button that runs the action
268
+ * registered under that name, with `value` as its `data-ai-action-value`; an item with `url` is a
269
+ * link. Each carries `__action`, plus `--primary` or `--secondary`. Null when no item renders.
270
+ */
271
+ declare function renderActions(document: Document, items: readonly AiChatActionItem[]): HTMLElement | null;
272
+ //#endregion
202
273
  //#region src/chat.d.ts
203
274
  declare function createChatSession(options: AiChatSessionOptions): AiChatSession;
204
275
  //#endregion
205
276
  //#region src/dom.d.ts
206
277
  declare function isSafeLinkUrl(url: string): boolean;
278
+ declare function createSafeLink(document: Document, label: string, url: string): HTMLAnchorElement | null;
279
+ /**
280
+ * An image only from a site-relative or web URL; anything else is left out rather than loaded. The
281
+ * width and height, when given, let the browser reserve the space before the image arrives.
282
+ */
283
+ declare function createSafeImage(document: Document, image: AiCardImage | null | undefined): HTMLImageElement | null;
284
+ /** An element carrying the BEM class for `part` of `block`, and `text` when there is any. */
285
+ declare function createPart<K extends keyof HTMLElementTagNameMap>(document: Document, tag: K, block: string, part?: string | null, text?: string | null): HTMLElementTagNameMap[K];
207
286
  //#endregion
208
287
  //#region src/protocol.d.ts
209
288
  declare const AI_CHAT_PROTOCOL_VERSION = 1;
@@ -215,4 +294,13 @@ declare function createAiChatRegistry(): AiChatRegistry;
215
294
  //#region src/stream.d.ts
216
295
  declare function readEventStream(response: Response, signal: AbortSignal): AsyncGenerator<AiChatStreamEvent>;
217
296
  //#endregion
218
- export { AI_CHAT_PROTOCOL_VERSION, ANSWER_CARD_CLASS, type AiAnswerCard, type AiAnswerCardFact, type AiAnswerCardLabels, type AiAnswerCardLink, type AiAnswerCardSection, type AiAnswerCardTable, type AiChatAction, type AiChatBinding, type AiChatBindings, type AiChatClasses, type AiChatContext, type AiChatExtensionContext, type AiChatMessage, type AiChatRegistry, type AiChatRenderer, type AiChatRequest, type AiChatSession, type AiChatSessionOptions, type AiChatSessionResult, type AiChatSessionStatus, type AiChatStreamEvent, type AiChatSurface, MAX_ANSWER_CARD_FACTS, MAX_ANSWER_CARD_LINKS, MAX_ANSWER_CARD_SECTIONS, MAX_ANSWER_CARD_TABLES, MAX_ANSWER_CARD_TABLE_CELLS, MAX_ANSWER_CARD_TABLE_ROWS, MAX_ANSWER_CARD_TEXT_LENGTH, MAX_ANSWER_CARD_TOTAL_STRUCTURAL_ITEMS, MAX_ANSWER_CARD_TOTAL_TABLE_CELLS, MAX_ANSWER_CARD_TOTAL_TEXT_CHARACTERS, MAX_ANSWER_CARD_URL_LENGTH, bindChat, createAiChatRegistry, createChatSession, isAnswerCard, isSafeLinkUrl, parseStreamEvent, readEventStream, renderAnswerCard };
297
+ //#region src/surfaces.d.ts
298
+ /**
299
+ * A surface that shows one item out of an authored list template. The template is cloned, every
300
+ * element carrying `attribute` whose value is not the payload's `key` field is removed, and the
301
+ * rest of the template stays as authored, so one item is the same markup the whole list shows.
302
+ * Null when the template is missing or no item matches.
303
+ */
304
+ declare function createTemplateItemSurface(options: AiTemplateItemSurfaceOptions): (context: AiChatExtensionContext) => DocumentFragment | null;
305
+ //#endregion
306
+ export { ACTIONS_CLASS, AI_CHAT_PROTOCOL_VERSION, ANSWER_CARD_CLASS, type AiAnswerCard, type AiAnswerCardFact, type AiAnswerCardLabels, type AiAnswerCardLink, type AiAnswerCardSection, type AiAnswerCardTable, type AiCardImage, type AiChatAction, type AiChatActionItem, type AiChatBinding, type AiChatBindings, type AiChatContext, type AiChatExtensionContext, type AiChatMessage, type AiChatRegistry, type AiChatRenderer, type AiChatRequest, type AiChatSession, type AiChatSessionOptions, type AiChatSessionResult, type AiChatSessionStatus, type AiChatStreamEvent, type AiChatSurface, type AiContactCard, type AiContactCardHours, type AiContactCardHoursRow, type AiMediaCard, type AiTemplateItemSurfaceOptions, CARD_LIST_CLASS, CHAT_CLASS, CONTACT_CARD_CLASS, MAX_ANSWER_CARD_FACTS, MAX_ANSWER_CARD_LINKS, MAX_ANSWER_CARD_SECTIONS, MAX_ANSWER_CARD_TABLES, MAX_ANSWER_CARD_TABLE_CELLS, MAX_ANSWER_CARD_TABLE_ROWS, MAX_ANSWER_CARD_TEXT_LENGTH, MAX_ANSWER_CARD_TOTAL_STRUCTURAL_ITEMS, MAX_ANSWER_CARD_TOTAL_TABLE_CELLS, MAX_ANSWER_CARD_TOTAL_TEXT_CHARACTERS, MAX_ANSWER_CARD_URL_LENGTH, MEDIA_CARD_CLASS, bindChat, createAiChatRegistry, createChatSession, createPart, createSafeImage, createSafeLink, createTemplateItemSurface, isAnswerCard, isSafeLinkUrl, parseStreamEvent, readEventStream, renderActions, renderAnswerCard, renderCardList, renderContactCard, renderMediaCard };
package/dist/index.js CHANGED
@@ -33,6 +33,31 @@ function isPlainObject(value) {
33
33
  const prototype = Object.getPrototypeOf(value);
34
34
  return prototype === Object.prototype || prototype === null;
35
35
  }
36
+ /**
37
+ * An image only from a site-relative or web URL; anything else is left out rather than loaded. The
38
+ * width and height, when given, let the browser reserve the space before the image arrives.
39
+ */
40
+ function createSafeImage(document, image) {
41
+ if (!image || typeof image.url !== "string" || !/^(https?:\/\/|\/)/i.test(image.url) || !isSafeLinkUrl(image.url)) return null;
42
+ const element = document.createElement("img");
43
+ element.src = image.url;
44
+ element.alt = typeof image.alt === "string" ? image.alt : "";
45
+ element.loading = "lazy";
46
+ element.decoding = "async";
47
+ if (typeof image.url2x === "string" && /^(https?:\/\/|\/)/i.test(image.url2x) && isSafeLinkUrl(image.url2x)) element.srcset = `${image.url} 1x, ${image.url2x} 2x`;
48
+ if (image.width && image.height) {
49
+ element.width = image.width;
50
+ element.height = image.height;
51
+ }
52
+ return element;
53
+ }
54
+ /** An element carrying the BEM class for `part` of `block`, and `text` when there is any. */
55
+ function createPart(document, tag, block, part, text) {
56
+ const element = document.createElement(tag);
57
+ element.className = part ? `${block}__${part}` : block;
58
+ if (text) element.textContent = text;
59
+ return element;
60
+ }
36
61
  //#endregion
37
62
  //#region src/markdown.ts
38
63
  const MAX_MARKDOWN_CHARACTERS = 8e3;
@@ -936,14 +961,24 @@ const defaultLabels = {
936
961
  table: "Published table",
937
962
  tableScroll: "Scroll sideways to see all columns"
938
963
  };
939
- const defaultClasses = {
940
- messageUser: "",
941
- messageAssistant: "",
942
- text: "",
943
- tool: "",
944
- card: "",
945
- error: ""
946
- };
964
+ /**
965
+ * Every element the binding adds to the thread carries a class under this block, so a host styles
966
+ * the chat by class rather than by the order its elements happen to come in.
967
+ */
968
+ const CHAT_CLASS = "vv-ai-chat";
969
+ const CONVERSATION_CONTEXT = "conversationId";
970
+ function part(name) {
971
+ return `${CHAT_CLASS}__${name}`;
972
+ }
973
+ function kebab(name) {
974
+ return name.replace(/[A-Z_]/g, (character) => character === "_" ? "-" : `-${character.toLowerCase()}`);
975
+ }
976
+ /** Labels from `data-ai-chat-label-*` on the root, under the options and over the defaults. */
977
+ function readLabels(root, labels) {
978
+ const read = {};
979
+ for (const key of Object.keys(defaultLabels)) read[key] = labels?.[key] || root.getAttribute(`data-ai-chat-label-${kebab(key)}`) || defaultLabels[key];
980
+ return read;
981
+ }
947
982
  function dataString(data, name) {
948
983
  if (typeof data !== "object" || data === null || Array.isArray(data)) return null;
949
984
  const value = data[name];
@@ -956,14 +991,7 @@ function bindChat(root, options = {}) {
956
991
  const send = root.querySelector("[data-ai-chat-send]");
957
992
  if (!form || !input || !thread) throw new Error("AI chat shell requires form, input and thread elements");
958
993
  const chatThread = thread;
959
- const labels = {
960
- ...defaultLabels,
961
- ...options.labels
962
- };
963
- const classes = {
964
- ...defaultClasses,
965
- ...options.classes
966
- };
994
+ const labels = readLabels(root, options.labels);
967
995
  const initialThread = chatThread.cloneNode(true);
968
996
  let initialNodes = Array.from(chatThread.childNodes);
969
997
  const endpoint = options.endpoint ?? root.dataset.aiChatEndpoint ?? form.action;
@@ -975,23 +1003,32 @@ function bindChat(root, options = {}) {
975
1003
  let activeTextContent = "";
976
1004
  let pendingTool = null;
977
1005
  let destroyed = false;
1006
+ const formContexts = /* @__PURE__ */ new Map();
1007
+ const cleanups = [];
978
1008
  const session = createChatSession({
979
1009
  endpoint,
980
1010
  provider: options.provider ?? root.dataset.aiChatProvider,
981
1011
  headers,
982
1012
  timeoutMs: options.timeoutMs
983
1013
  });
1014
+ function startConversation() {
1015
+ session.setContext(CONVERSATION_CONTEXT, crypto.randomUUID());
1016
+ }
1017
+ function listen(target, type, listener, options) {
1018
+ target.addEventListener(type, listener, options);
1019
+ cleanups.push(() => target.removeEventListener(type, listener, options));
1020
+ }
984
1021
  function appendMessage(role) {
985
1022
  const message = root.ownerDocument.createElement("div");
986
1023
  message.dataset.aiChatMessage = role;
987
- message.className = role === "user" ? classes.messageUser : classes.messageAssistant;
1024
+ message.className = `${part("message")} ${part(`message--${role}`)}`;
988
1025
  chatThread.append(message);
989
1026
  return message;
990
1027
  }
991
1028
  function appendMarkdown(parent, text) {
992
1029
  const bubble = root.ownerDocument.createElement("div");
993
1030
  bubble.dataset.aiChatText = "true";
994
- bubble.className = classes.text;
1031
+ bubble.className = part("text");
995
1032
  bubble.append(renderMarkdown(root.ownerDocument, text));
996
1033
  parent.append(bubble);
997
1034
  }
@@ -1000,7 +1037,7 @@ function bindChat(root, options = {}) {
1000
1037
  if (!activeText) {
1001
1038
  activeText = root.ownerDocument.createElement("div");
1002
1039
  activeText.dataset.aiChatText = "true";
1003
- activeText.className = classes.text;
1040
+ activeText.className = part("text");
1004
1041
  activeAssistant.append(activeText);
1005
1042
  }
1006
1043
  activeTextContent += text;
@@ -1010,21 +1047,26 @@ function bindChat(root, options = {}) {
1010
1047
  options.onError?.(error);
1011
1048
  const message = root.ownerDocument.createElement("p");
1012
1049
  message.setAttribute("role", "alert");
1013
- message.className = classes.error;
1050
+ message.className = part("error");
1014
1051
  message.append(error.name === "TimeoutError" ? labels.timeout : labels.error);
1015
1052
  chatThread.append(message);
1016
1053
  }
1017
- function tool(id, _name) {
1054
+ function toolLabel(name) {
1055
+ if (!/^[\w-]{1,64}$/.test(name)) return labels.toolRunning;
1056
+ return options.toolLabels?.[name] || root.getAttribute(`data-ai-chat-tool-${kebab(name)}`) || labels.toolRunning;
1057
+ }
1058
+ function tool(id, name) {
1018
1059
  const element = root.ownerDocument.createElement("div");
1019
1060
  element.dataset.aiChatTool = id;
1020
- element.className = classes.tool;
1061
+ element.className = part("tool");
1021
1062
  const dot = root.ownerDocument.createElement("span");
1022
- dot.className = "ai-chat__tool-dot";
1063
+ dot.className = part("tool-dot");
1023
1064
  dot.setAttribute("aria-hidden", "true");
1024
1065
  const label = root.ownerDocument.createElement("span");
1025
- label.append(root.ownerDocument.createTextNode(labels.toolRunning));
1066
+ label.className = part("tool-label");
1067
+ label.append(root.ownerDocument.createTextNode(toolLabel(name)));
1026
1068
  const status = root.ownerDocument.createElement("span");
1027
- status.className = "ai-chat__tool-status sr-only";
1069
+ status.className = part("tool-status");
1028
1070
  element.append(dot, label, status);
1029
1071
  activeAssistant?.append(element);
1030
1072
  return element;
@@ -1035,14 +1077,14 @@ function bindChat(root, options = {}) {
1035
1077
  }
1036
1078
  function finishTool(id, failed, interrupted = false) {
1037
1079
  const element = activeAssistant?.querySelector(`[data-ai-chat-tool="${CSS.escape(id)}"]`);
1080
+ finishToolElement(element, failed, interrupted);
1081
+ }
1082
+ function finishToolElement(element, failed, interrupted) {
1038
1083
  if (element) {
1039
- element.classList.add("ai-chat__tool--done");
1040
- element.classList.toggle("ai-chat__tool--failed", failed || interrupted);
1041
- const status = element.querySelector(".ai-chat__tool-status");
1042
- if (status) {
1043
- status.textContent = interrupted ? labels.toolInterrupted : failed ? labels.toolFailed : labels.toolComplete;
1044
- status.classList.remove("sr-only");
1045
- }
1084
+ element.classList.add(part("tool--done"));
1085
+ element.classList.toggle(part("tool--failed"), failed || interrupted);
1086
+ const status = element.querySelector(`.${part("tool-status")}`);
1087
+ if (status) status.textContent = interrupted ? labels.toolInterrupted : failed ? labels.toolFailed : labels.toolComplete;
1046
1088
  }
1047
1089
  }
1048
1090
  function renderResult(event) {
@@ -1054,7 +1096,8 @@ function bindChat(root, options = {}) {
1054
1096
  root,
1055
1097
  tool: event.data.name,
1056
1098
  data: event.data.data,
1057
- reply: event.data.reply
1099
+ reply: event.data.reply,
1100
+ labels
1058
1101
  };
1059
1102
  let content = null;
1060
1103
  try {
@@ -1070,7 +1113,7 @@ function bindChat(root, options = {}) {
1070
1113
  if (content) {
1071
1114
  const wrapper = root.ownerDocument.createElement("div");
1072
1115
  wrapper.dataset.aiChatCard = "true";
1073
- wrapper.className = classes.card;
1116
+ wrapper.className = part("result");
1074
1117
  wrapper.append(content);
1075
1118
  activeAssistant.append(wrapper);
1076
1119
  options.onEmbedded?.(wrapper);
@@ -1090,11 +1133,16 @@ function bindChat(root, options = {}) {
1090
1133
  } else if (event.name === "tool_done") finishTool(event.data.id, event.data.isError);
1091
1134
  else if (event.name === "done" || event.name === "error") clearPendingTool();
1092
1135
  });
1136
+ const resizeInput = () => {
1137
+ input.style.height = "auto";
1138
+ input.style.height = `${input.scrollHeight}px`;
1139
+ };
1093
1140
  const submit = async (event) => {
1094
1141
  event?.preventDefault();
1095
1142
  const question = input.value.trim();
1096
1143
  if (!question || session.status !== "idle") return;
1097
1144
  input.value = "";
1145
+ resizeInput();
1098
1146
  for (const node of initialNodes) node.remove();
1099
1147
  appendMarkdown(appendMessage("user"), question);
1100
1148
  activeAssistant = appendMessage("assistant");
@@ -1107,8 +1155,8 @@ function bindChat(root, options = {}) {
1107
1155
  root.removeAttribute("aria-busy");
1108
1156
  if (send) send.disabled = false;
1109
1157
  if (result.error && !result.canceled) report(result.error);
1110
- if (result.canceled) activeAssistant?.querySelectorAll("[data-ai-chat-tool]").forEach((item) => {
1111
- item.textContent = labels.toolInterrupted;
1158
+ if (result.canceled) activeAssistant?.querySelectorAll(`[data-ai-chat-tool]:not(.${part("tool--done")})`).forEach((item) => {
1159
+ finishToolElement(item, false, true);
1112
1160
  });
1113
1161
  };
1114
1162
  const click = (event) => {
@@ -1124,10 +1172,13 @@ function bindChat(root, options = {}) {
1124
1172
  chatThread.replaceChildren(...Array.from(initialThread.childNodes, (node) => node.cloneNode(true)));
1125
1173
  initialNodes = Array.from(chatThread.childNodes);
1126
1174
  input.value = "";
1175
+ resizeInput();
1127
1176
  activeAssistant = null;
1128
1177
  activeText = null;
1129
1178
  activeTextContent = "";
1130
1179
  pendingTool = null;
1180
+ formContexts.clear();
1181
+ startConversation();
1131
1182
  return;
1132
1183
  }
1133
1184
  const actionElement = target?.closest("[data-ai-action]");
@@ -1147,27 +1198,250 @@ function bindChat(root, options = {}) {
1147
1198
  submit();
1148
1199
  }
1149
1200
  };
1150
- form.addEventListener("submit", submit);
1151
- root.addEventListener("click", click);
1152
- input.addEventListener("keydown", keydown);
1153
- return {
1201
+ function followAnswer() {
1202
+ const scroller = root.querySelector("[data-ai-chat-scroll]");
1203
+ if (!scroller) return;
1204
+ let question = null;
1205
+ let following = false;
1206
+ const release = () => {
1207
+ following = false;
1208
+ };
1209
+ listen(scroller, "wheel", release, { passive: true });
1210
+ listen(scroller, "touchmove", release, { passive: true });
1211
+ const observer = new MutationObserver(() => {
1212
+ const questions = chatThread.querySelectorAll("[data-ai-chat-message=\"user\"]");
1213
+ const latest = questions[questions.length - 1] ?? null;
1214
+ if (latest !== question) {
1215
+ question = latest;
1216
+ following = true;
1217
+ }
1218
+ if (!question || !following || root.getAttribute("aria-busy") !== "true") return;
1219
+ const top = question.getBoundingClientRect().top - chatThread.getBoundingClientRect().top - Number.parseFloat(getComputedStyle(chatThread).paddingTop || "0");
1220
+ following = top > scroller.scrollHeight - scroller.clientHeight;
1221
+ scroller.scrollTo({ top });
1222
+ });
1223
+ observer.observe(chatThread, {
1224
+ childList: true,
1225
+ subtree: true
1226
+ });
1227
+ cleanups.push(() => observer.disconnect());
1228
+ }
1229
+ function trackKeyboard() {
1230
+ const viewport = root.ownerDocument.defaultView?.visualViewport;
1231
+ if (!viewport) return;
1232
+ const apply = () => {
1233
+ const covered = window.innerHeight - viewport.height - viewport.offsetTop;
1234
+ root.style.setProperty(`--${CHAT_CLASS}-keyboard`, `${Math.max(0, covered)}px`);
1235
+ };
1236
+ apply();
1237
+ listen(viewport, "resize", apply);
1238
+ listen(viewport, "scroll", apply);
1239
+ }
1240
+ function trackOffset() {
1241
+ const selector = root.dataset.aiChatOffset;
1242
+ const element = options.offsetElement ?? (selector ? root.ownerDocument.querySelector(selector) : null);
1243
+ if (!element) return;
1244
+ const apply = () => root.style.setProperty(`--${CHAT_CLASS}-offset`, `${element.offsetHeight}px`);
1245
+ apply();
1246
+ const observer = new ResizeObserver(apply);
1247
+ observer.observe(element);
1248
+ cleanups.push(() => observer.disconnect());
1249
+ }
1250
+ listen(form, "submit", submit);
1251
+ listen(root, "click", click);
1252
+ listen(input, "keydown", keydown);
1253
+ listen(input, "input", resizeInput);
1254
+ followAnswer();
1255
+ trackKeyboard();
1256
+ trackOffset();
1257
+ startConversation();
1258
+ const binding = {
1154
1259
  session,
1260
+ labels,
1155
1261
  appendAssistantReply(text) {
1156
1262
  const content = text.trim();
1157
1263
  if (!content) return;
1158
1264
  appendMarkdown(appendMessage("assistant"), content);
1159
1265
  session.addAssistantReply(content);
1160
1266
  },
1267
+ setFormContext(name, summary, followUp) {
1268
+ const content = summary.trim();
1269
+ if (!content || formContexts.get(name) === content) return;
1270
+ const first = !formContexts.has(name);
1271
+ formContexts.set(name, content);
1272
+ session.setContextMessage(name, content);
1273
+ if (first && followUp) binding.appendAssistantReply(followUp);
1274
+ },
1161
1275
  destroy() {
1162
1276
  if (destroyed) return;
1163
1277
  destroyed = true;
1164
1278
  unsubscribe();
1165
1279
  session.dispose();
1166
- form.removeEventListener("submit", submit);
1167
- root.removeEventListener("click", click);
1168
- input.removeEventListener("keydown", keydown);
1280
+ for (const cleanup of cleanups.splice(0)) cleanup();
1281
+ }
1282
+ };
1283
+ return binding;
1284
+ }
1285
+ //#endregion
1286
+ //#region src/cards.ts
1287
+ /** Block classes of the cards below. Every element a card renders carries a class under its block. */
1288
+ const CARD_LIST_CLASS = "vv-ai-card-list";
1289
+ const CONTACT_CARD_CLASS = "vv-ai-contact-card";
1290
+ const MEDIA_CARD_CLASS = "vv-ai-media-card";
1291
+ const ACTIONS_CLASS = "vv-ai-actions";
1292
+ function text(value) {
1293
+ return typeof value === "string" && value.trim() ? value : null;
1294
+ }
1295
+ /**
1296
+ * Several cards from one tool result, under `vv-ai-card-list` and `vv-ai-card-list--{modifier}`.
1297
+ * Items that render nothing are skipped, and a list with nothing in it is null.
1298
+ */
1299
+ function renderCardList(document, items, render, modifier) {
1300
+ if (!Array.isArray(items)) return null;
1301
+ const cards = items.map(render).filter((card) => card !== null);
1302
+ if (!cards.length) return null;
1303
+ const list = createPart(document, "div", CARD_LIST_CLASS);
1304
+ if (modifier) list.classList.add(`${CARD_LIST_CLASS}--${modifier}`);
1305
+ list.append(...cards);
1306
+ return list;
1307
+ }
1308
+ function appendHours(document, card, hours) {
1309
+ const rows = Array.isArray(hours.rows) ? hours.rows.filter((row) => isPlainObject(row) && text(row.value)) : [];
1310
+ if (!rows.length) return;
1311
+ const block = createPart(document, "div", CONTACT_CARD_CLASS, "hours");
1312
+ const label = text(hours.label);
1313
+ if (label) block.append(createPart(document, "span", CONTACT_CARD_CLASS, "hours-label", label));
1314
+ for (const row of rows) {
1315
+ const line = createPart(document, "div", CONTACT_CARD_CLASS, "hours-row");
1316
+ const time = createPart(document, "span", CONTACT_CARD_CLASS, "hours-time", row.value);
1317
+ const note = text(row.note);
1318
+ if (note) time.append(" ", createPart(document, "span", CONTACT_CARD_CLASS, "hours-note", note));
1319
+ line.append(createPart(document, "span", CONTACT_CARD_CLASS, "hours-days", text(row.label)), time);
1320
+ block.append(line);
1321
+ }
1322
+ card.append(block);
1323
+ }
1324
+ /**
1325
+ * A place or person to get in touch with: name, an optional subtitle and image (such as a flag),
1326
+ * address, phone and email links, and any number of labelled groups of hours. Null without a name.
1327
+ */
1328
+ function renderContactCard(document, data) {
1329
+ if (!isPlainObject(data)) return null;
1330
+ const contact = data;
1331
+ const name = text(contact.name);
1332
+ if (!name) return null;
1333
+ const card = createPart(document, "article", CONTACT_CARD_CLASS);
1334
+ const head = createPart(document, "header", CONTACT_CARD_CLASS, "head");
1335
+ const image = createSafeImage(document, contact.image);
1336
+ if (image) {
1337
+ image.className = `${CONTACT_CARD_CLASS}__image`;
1338
+ head.append(image);
1339
+ }
1340
+ const title = createPart(document, "span", CONTACT_CARD_CLASS, "title");
1341
+ title.append(createPart(document, "span", CONTACT_CARD_CLASS, "name", name));
1342
+ const subtitle = text(contact.subtitle);
1343
+ if (subtitle) title.append(createPart(document, "span", CONTACT_CARD_CLASS, "subtitle", subtitle));
1344
+ head.append(title);
1345
+ card.append(head);
1346
+ const address = text(contact.address);
1347
+ if (address) card.append(createPart(document, "p", CONTACT_CARD_CLASS, "address", address));
1348
+ const links = createPart(document, "p", CONTACT_CARD_CLASS, "links");
1349
+ const phone = text(contact.phone);
1350
+ const email = text(contact.email);
1351
+ for (const link of [phone ? createSafeLink(document, phone, `tel:${phone.replace(/[^+\d]/g, "")}`) : null, email ? createSafeLink(document, email, `mailto:${email.trim()}`) : null]) if (link) {
1352
+ link.className = `${CONTACT_CARD_CLASS}__link`;
1353
+ links.append(link);
1354
+ }
1355
+ if (links.children.length) card.append(links);
1356
+ for (const hours of Array.isArray(contact.hours) ? contact.hours : []) if (isPlainObject(hours)) appendHours(document, card, hours);
1357
+ return card;
1358
+ }
1359
+ /**
1360
+ * A thing best recognised by its picture, with labelled facts beside it. The image leads, and the
1361
+ * card carries `--with-image` when it has one. Null without a title.
1362
+ */
1363
+ function renderMediaCard(document, data) {
1364
+ if (!isPlainObject(data)) return null;
1365
+ const media = data;
1366
+ const title = text(media.title);
1367
+ if (!title) return null;
1368
+ const card = createPart(document, "article", MEDIA_CARD_CLASS);
1369
+ const image = createSafeImage(document, media.image);
1370
+ if (image) {
1371
+ image.className = `${MEDIA_CARD_CLASS}__image`;
1372
+ const figure = createPart(document, "div", MEDIA_CARD_CLASS, "figure");
1373
+ figure.append(image);
1374
+ card.classList.add(`${MEDIA_CARD_CLASS}--with-image`);
1375
+ card.append(figure);
1376
+ }
1377
+ const body = createPart(document, "div", MEDIA_CARD_CLASS, "body");
1378
+ body.append(createPart(document, "h3", MEDIA_CARD_CLASS, "title", title));
1379
+ const facts = (Array.isArray(media.facts) ? media.facts : []).filter((fact) => isPlainObject(fact) && text(fact.value));
1380
+ if (facts.length) {
1381
+ const list = createPart(document, "div", MEDIA_CARD_CLASS, "facts");
1382
+ for (const fact of facts) {
1383
+ const row = createPart(document, "div", MEDIA_CARD_CLASS, "fact");
1384
+ row.append(createPart(document, "span", MEDIA_CARD_CLASS, "fact-label", text(fact.label)), createPart(document, "span", MEDIA_CARD_CLASS, "fact-value", fact.value));
1385
+ list.append(row);
1386
+ }
1387
+ body.append(list);
1388
+ }
1389
+ card.append(body);
1390
+ return card;
1391
+ }
1392
+ /**
1393
+ * A row of things the visitor can do next. An item with `action` is a button that runs the action
1394
+ * registered under that name, with `value` as its `data-ai-action-value`; an item with `url` is a
1395
+ * link. Each carries `__action`, plus `--primary` or `--secondary`. Null when no item renders.
1396
+ */
1397
+ function renderActions(document, items) {
1398
+ const elements = [];
1399
+ for (const item of items) {
1400
+ const label = text(item?.label);
1401
+ if (!label) continue;
1402
+ let element = null;
1403
+ const action = text(item.action);
1404
+ const url = text(item.url);
1405
+ if (action) {
1406
+ const button = createPart(document, "button", ACTIONS_CLASS, "action", label);
1407
+ button.type = "button";
1408
+ button.dataset.aiAction = action;
1409
+ const value = text(item.value);
1410
+ if (value) button.dataset.aiActionValue = value;
1411
+ element = button;
1412
+ } else if (url) {
1413
+ element = createSafeLink(document, label, url.trim());
1414
+ if (element) element.className = `${ACTIONS_CLASS}__action`;
1169
1415
  }
1416
+ if (element) {
1417
+ element.classList.add(`${ACTIONS_CLASS}__action--${item.primary ? "primary" : "secondary"}`);
1418
+ elements.push(element);
1419
+ }
1420
+ }
1421
+ if (!elements.length) return null;
1422
+ const actions = createPart(document, "div", ACTIONS_CLASS);
1423
+ actions.append(...elements);
1424
+ return actions;
1425
+ }
1426
+ //#endregion
1427
+ //#region src/surfaces.ts
1428
+ /**
1429
+ * A surface that shows one item out of an authored list template. The template is cloned, every
1430
+ * element carrying `attribute` whose value is not the payload's `key` field is removed, and the
1431
+ * rest of the template stays as authored, so one item is the same markup the whole list shows.
1432
+ * Null when the template is missing or no item matches.
1433
+ */
1434
+ function createTemplateItemSurface(options) {
1435
+ return ({ root, data }) => {
1436
+ const value = isPlainObject(data) ? data[options.key] : null;
1437
+ const template = root.querySelector(`template[data-template="${CSS.escape(options.template)}"]`);
1438
+ if (typeof value !== "string" || !template) return null;
1439
+ const content = template.content.cloneNode(true);
1440
+ let found = false;
1441
+ for (const item of content.querySelectorAll(`[${CSS.escape(options.attribute)}]`)) if (item.getAttribute(options.attribute) === value) found = true;
1442
+ else item.remove();
1443
+ return found ? content : null;
1170
1444
  };
1171
1445
  }
1172
1446
  //#endregion
1173
- export { AI_CHAT_PROTOCOL_VERSION, ANSWER_CARD_CLASS, MAX_ANSWER_CARD_FACTS, MAX_ANSWER_CARD_LINKS, MAX_ANSWER_CARD_SECTIONS, MAX_ANSWER_CARD_TABLES, MAX_ANSWER_CARD_TABLE_CELLS, MAX_ANSWER_CARD_TABLE_ROWS, MAX_ANSWER_CARD_TEXT_LENGTH, MAX_ANSWER_CARD_TOTAL_STRUCTURAL_ITEMS, MAX_ANSWER_CARD_TOTAL_TABLE_CELLS, MAX_ANSWER_CARD_TOTAL_TEXT_CHARACTERS, MAX_ANSWER_CARD_URL_LENGTH, bindChat, createAiChatRegistry, createChatSession, isAnswerCard, isSafeLinkUrl, parseStreamEvent, readEventStream, renderAnswerCard };
1447
+ export { ACTIONS_CLASS, AI_CHAT_PROTOCOL_VERSION, ANSWER_CARD_CLASS, CARD_LIST_CLASS, CHAT_CLASS, CONTACT_CARD_CLASS, MAX_ANSWER_CARD_FACTS, MAX_ANSWER_CARD_LINKS, MAX_ANSWER_CARD_SECTIONS, MAX_ANSWER_CARD_TABLES, MAX_ANSWER_CARD_TABLE_CELLS, MAX_ANSWER_CARD_TABLE_ROWS, MAX_ANSWER_CARD_TEXT_LENGTH, MAX_ANSWER_CARD_TOTAL_STRUCTURAL_ITEMS, MAX_ANSWER_CARD_TOTAL_TABLE_CELLS, MAX_ANSWER_CARD_TOTAL_TEXT_CHARACTERS, MAX_ANSWER_CARD_URL_LENGTH, MEDIA_CARD_CLASS, bindChat, createAiChatRegistry, createChatSession, createPart, createSafeImage, createSafeLink, createTemplateItemSurface, isAnswerCard, isSafeLinkUrl, parseStreamEvent, readEventStream, renderActions, renderAnswerCard, renderCardList, renderContactCard, renderMediaCard };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vettvangur/ai-sdk",
3
- "version": "0.1.14",
3
+ "version": "0.2.1",
4
4
  "description": "Framework-agnostic AI chat client for server-rendered shells",
5
5
  "type": "module",
6
6
  "access": "public",