@vettvangur/ai-sdk 0.13.0 → 0.15.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/README.md CHANGED
@@ -1,11 +1,16 @@
1
1
  # @vettvangur/ai-sdk
2
2
 
3
- Framework-agnostic AI chat primitives for server-rendered shells.
3
+ Framework-agnostic AI primitives for server-rendered pages, and an AI chat built on them.
4
4
 
5
- It exports protocol-v1 contracts, parsing and SSE stream-reading primitives, a headless chat session,
6
- a DOM binding for a server-rendered shell, and the few generic pieces a host draws tool results with. It
7
- ships no styles by default: every element it renders carries a BEM class. An opt-in stylesheet lays
8
- out and draws the chat, its window and launcher, themed by custom properties (see [Styles](#styles)).
5
+ The package root is the core: reading a streamed response, rendering model text as safe DOM, and the
6
+ link and image rules every renderer keeps (see [The core](#the-core)). It knows nothing of chat, so a
7
+ page that streams a generated product text or a classification uses it alone.
8
+
9
+ `@vettvangur/ai-sdk/chat` is the chat: protocol-v1 contracts, parsing and stream reading, a headless
10
+ chat session, a DOM binding for a server-rendered shell, and the few generic pieces a host draws tool
11
+ results with. It ships no styles by default: every element it renders carries a BEM class. An opt-in
12
+ stylesheet lays out and draws the chat, its window and launcher, themed by custom properties (see
13
+ [Styles](#styles)).
9
14
 
10
15
  ```html
11
16
  <section data-ai-chat data-ai-chat-endpoint="/webapi/aichat/stream"
@@ -24,7 +29,7 @@ out and draws the chat, its window and launcher, themed by custom properties (se
24
29
  ```
25
30
 
26
31
  ```ts
27
- import { bindChat, createAiChatRegistry } from '@vettvangur/ai-sdk'
32
+ import { bindChat, createAiChatRegistry } from '@vettvangur/ai-sdk/chat'
28
33
 
29
34
  const registry = createAiChatRegistry()
30
35
  registry.registerRenderer('weather', ({ document, data }) => {
@@ -37,6 +42,39 @@ const chat = bindChat(document.querySelector('[data-ai-chat]')!, { registry })
37
42
  // Call chat.destroy() when its server-rendered shell is removed.
38
43
  ```
39
44
 
45
+ ## The core
46
+
47
+ `readServerEvents(response, signal)` yields each record of a server-sent event stream as
48
+ `{ name, data }`, with `data` as the text of its `data:` lines. It knows no protocol: a record
49
+ without an `event:` name or `data:` line is skipped, the stream ends with the response, and breaking
50
+ out of the loop or aborting `signal` cancels the response body. A record that grows past 1 MiB
51
+ without closing throws.
52
+
53
+ ```ts
54
+ import { readServerEvents, renderMarkdown } from '@vettvangur/ai-sdk'
55
+
56
+ const controller = new AbortController()
57
+ const response = await fetch('/webapi/products/describe', { method: 'POST', body: form, signal: controller.signal })
58
+ let text = ''
59
+ for await (const { name, data } of readServerEvents(response, controller.signal)) {
60
+ if (name === 'delta') {
61
+ text += JSON.parse(data).text
62
+ output.replaceChildren(renderMarkdown(document, text))
63
+ }
64
+ }
65
+ ```
66
+
67
+ `renderMarkdown(document, source)` draws the Markdown subset a model writes as DOM nodes, never as
68
+ HTML, and keeps to `MAX_MARKDOWN_CHARACTERS`. `isSafeLinkUrl`, `createSafeLink`, `createSafeImage`
69
+ and `createPart` are described under [Cards](#cards).
70
+
71
+ ### Upgrading from 0.14
72
+
73
+ Everything the package root exported except `createPart`, `createSafeImage`, `createSafeLink` and
74
+ `isSafeLinkUrl` moved to `@vettvangur/ai-sdk/chat`: import `bindChat`, `createAiChatRegistry`,
75
+ `createChatSession`, `readEventStream`, `renderAnswerCard` and the `AiChat*` types from there. The
76
+ `live-chat`, `mount`, `binmx` and `styles.css` subpaths are unchanged.
77
+
40
78
  ## The shell
41
79
 
42
80
  `bindChat` needs the form, input and thread; the rest is optional.
@@ -52,7 +90,7 @@ const chat = bindChat(document.querySelector('[data-ai-chat]')!, { registry })
52
90
  | `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. |
53
91
  | `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. |
54
92
  | `data-ai-chat-label-*` | Labels, in kebab case: `error`, `timeout`, `tool-running`, `tool-complete`, `tool-failed`, `tool-interrupted`, `sources`, `details`, `table`, `table-scroll`, `follow-ups`, `live-chat`, `contact`. The `labels` option wins over the attribute. Any other name is the host's own, read with `label(name)`. |
55
- | `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. |
93
+ | `data-ai-chat-tool-*` | The progress label for one tool, with underscores in its name written as hyphens. The `toolLabels` option wins over the attribute, and the attribute over a `label` the server sends with the `tool` event. Other tools show `tool-running`. |
56
94
 
57
95
  The binding also keeps `--vv-ai-chat-keyboard` on the root at the height an on-screen keyboard
58
96
  covers, grows the input to fit what is typed, sets `aria-busy` on the root while a turn is in flight,
@@ -192,12 +230,15 @@ binding read. `binding.liveChat` is the provider in use, for a host to offer its
192
230
  `renderSurveyForm`. `@vettvangur/ai-sdk/live-chat/omnichannel` exports
193
231
  `createOmnichannelProvider({ orgId, orgUrl, widgetId })` over Dynamics 365 Omnichannel. It needs
194
232
  the optional peer dependency `@microsoft/omnichannel-chat-sdk` and imports it only when the
195
- provider is first used, so a page pays for it when a visitor asks for a person. It reads opening
233
+ provider is first used, so a page pays for it when a visitor asks for a person. A site that does
234
+ not install it needs no bundler setting for it: esbuild leaves the import for run time, where it
235
+ fails with an error naming the package only if the provider is used. The same holds for
236
+ `@livechat/customer-sdk` below, so `mountAiChat` builds without either. It reads opening
196
237
  hours from the widget's config and turns the Adaptive Card survey into text, choice and toggle
197
238
  fields, refusing a card with any other input rather than leaving a question out.
198
239
 
199
240
  ```ts
200
- import { bindChat } from '@vettvangur/ai-sdk'
241
+ import { bindChat } from '@vettvangur/ai-sdk/chat'
201
242
  import { createOmnichannelProvider } from '@vettvangur/ai-sdk/live-chat/omnichannel'
202
243
 
203
244
  const liveChat = createOmnichannelProvider({ orgId, orgUrl, widgetId })
@@ -272,7 +313,7 @@ answers through `liveChatFromAttributes` unless they name a `liveChat`:
272
313
  | `data-ai-chat-live-endpoint` | The AiChat Live desk, as `liveChatFromRoot` |
273
314
 
274
315
  ```ts
275
- import { createAiChatRegistry } from '@vettvangur/ai-sdk'
316
+ import { createAiChatRegistry } from '@vettvangur/ai-sdk/chat'
276
317
  import { mountAiChat } from '@vettvangur/ai-sdk/mount'
277
318
 
278
319
  const registry = createAiChatRegistry()
@@ -329,7 +370,7 @@ project; build them with the helpers below rather than adding them here.
329
370
 
330
371
  `createSafeImage` (web and site-relative URLs only, with srcset and size when given),
331
372
  `createSafeLink` (the `isSafeLinkUrl` rule, new tab for web URLs) and `createPart` (an element with
332
- a BEM class and text) are exported for a host's own renderers.
373
+ a BEM class and text) are exported from the package root for a host's own renderers.
333
374
 
334
375
  ## Answer cards
335
376
 
@@ -378,6 +419,11 @@ Every `vv-ai-chat__` class above is under the root. The page pins the root betwe
378
419
  corner from `36rem` up and fills the screen below it. The thread is the `vv-ai-chat-thread`
379
420
  container, so a host's cards can lay out by its width with `@container vv-ai-chat-thread`.
380
421
 
422
+ In the window, buttons and fields in the thread keep to the window's control size, whatever the host
423
+ draws them at elsewhere. That covers the package's own, `.button`, `.btn` and `.bttn` and any class
424
+ starting `button-`, `btn-` or `bttn-`, every `input` but checkboxes, radios, ranges, hidden and file
425
+ inputs, `select` and `textarea`. The composer is not in the thread and keeps its own.
426
+
381
427
  The theme's custom properties, set on the root or any ancestor of the chat and the launcher:
382
428
 
383
429
  | Property | Default |
@@ -394,8 +440,9 @@ The theme's custom properties, set on the root or any ancestor of the chat and t
394
440
  | `--vv-ai-shadow-prompt`, `--vv-ai-focus-ring` | a faint ring, the accent at 15% |
395
441
  | `--vv-ai-chat-window-z` (the launcher sits one above) | `1000` |
396
442
  | `--vv-ai-chat-window-width`, `-height`, `-inset`, `-radius`, `-shadow` | `23.75rem`, `38.75rem`, `1.25rem`, `1rem`, a soft drop |
397
- | `--vv-ai-chat-window-header`, `-header-agent`, `-header-text`, `-header-muted`, `-header-hover` | the accent, its hover, on-accent, white at 85% and 15% |
443
+ | `--vv-ai-chat-window-header`, `-header-agent`, `-header-text`, `-header-muted`, `-header-hover` | the accent, its hover, on-accent, the header text at 85% and 15% |
398
444
  | `--vv-ai-chat-assistant-avatar` (an image in the window's assistant avatar) | `none` |
445
+ | `--vv-ai-chat-window-control-height`, `-control-font-size` (buttons and fields in the window's thread) | `2.25rem`, `0.875rem` |
399
446
  | `--vv-ai-launcher-shadow`, `--vv-ai-launcher-teaser-shadow`, `--vv-ai-menu-shadow` | soft drops |
400
447
  | `--vv-ai-chat-spring`, `--vv-ai-launcher-spring`, `--vv-ai-launcher-wind-up` | the window's and launcher's easings |
401
448
  | `--vv-ai-chat-window-delay` (the window opens once the launcher has mostly spun away) | `0.35s` |
package/dist/binmx.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { P as AiTemplateUrlSurfaceOptions, m as AiChatExtensionContext } from "./contracts.js";
1
+ import { N as AiTemplateUrlSurfaceOptions, p as AiChatExtensionContext } from "./contracts.js";
2
2
  //#region src/binmx.d.ts
3
3
  /**
4
4
  * Makes cloned markup live. binmx processes only the page it started on and what it swaps in
package/dist/chat.d.ts ADDED
@@ -0,0 +1,132 @@
1
+ import { a as AiLiveChatMessage, c as AiLiveChatStartOptions, l as AiLiveChatSurveyField, n as AiLiveChatAnswers, o as AiLiveChatProvider, r as AiLiveChatAvailability, s as AiLiveChatSheetHost, t as AiLiveChatAction } from "./provider.js";
2
+ import { t as AiCardImage } from "./dom.js";
3
+ import { A as AiLauncherTeaserOptions, C as AiChatSessionOptions, D as AiChatSurface, E as AiChatStreamEvent, M as AiTemplateItemSurfaceOptions, N as AiTemplateUrlSurfaceOptions, O as AiFormContextOptions, S as AiChatSession, T as AiChatSessionStatus, _ as AiChatMessage, a as AiAnswerCardSection, b as AiChatRenderer, c as AiChatActionItem, d as AiChatContext, f as AiChatEventMap, g as AiChatLabels, h as AiChatHandoverResult, i as AiAnswerCardLink, j as AiLiveChatFactoryContext, k as AiHandoverPayload, l as AiChatBinding, m as AiChatHandoverOptions, n as AiAnswerCardFact, o as AiAnswerCardTable, p as AiChatExtensionContext, r as AiAnswerCardLabels, s as AiChatAction, t as AiAnswerCard, u as AiChatBindings, v as AiChatMode, w as AiChatSessionResult, x as AiChatRequest, y as AiChatRegistry } from "./contracts.js";
4
+ //#region src/answer-card.d.ts
5
+ declare const MAX_ANSWER_CARD_SECTIONS = 12;
6
+ declare const MAX_ANSWER_CARD_FACTS = 24;
7
+ declare const MAX_ANSWER_CARD_LINKS = 24;
8
+ declare const MAX_ANSWER_CARD_TABLES = 8;
9
+ declare const MAX_ANSWER_CARD_TABLE_ROWS = 50;
10
+ declare const MAX_ANSWER_CARD_TABLE_CELLS = 12;
11
+ declare const MAX_ANSWER_CARD_TEXT_LENGTH = 8000;
12
+ declare const MAX_ANSWER_CARD_URL_LENGTH = 2048;
13
+ declare const MAX_ANSWER_CARD_TOTAL_TEXT_CHARACTERS = 24000;
14
+ declare const MAX_ANSWER_CARD_TOTAL_STRUCTURAL_ITEMS = 512;
15
+ declare const MAX_ANSWER_CARD_TOTAL_TABLE_CELLS = 512;
16
+ /**
17
+ * Every element an answer card renders carries a class under this block, so a host styles the card
18
+ * by class rather than by the order its elements happen to come in.
19
+ */
20
+ declare const ANSWER_CARD_CLASS = "vv-ai-answer-card";
21
+ /**
22
+ * Whether `renderAnswerCard` will draw `value` as a card. A host that builds cards elsewhere, a
23
+ * server or a test, can hold its output to the same limits the renderer applies.
24
+ */
25
+ declare function isAnswerCard(value: unknown): value is AiAnswerCard;
26
+ declare function renderAnswerCard(document: Document, data: unknown, labels: AiAnswerCardLabels): HTMLElement | null;
27
+ /**
28
+ * Throws when `card` is not an answer card `renderAnswerCard` will draw, or when a field it shows
29
+ * as plain text (titles, facts, table cells, notes) holds Markdown that would show literally. For
30
+ * a server's or a test's own cards; the message names what is wrong.
31
+ */
32
+ declare function assertAnswerCardContract(card: unknown): asserts card is AiAnswerCard;
33
+ //#endregion
34
+ //#region src/bind.d.ts
35
+ /**
36
+ * Every element the binding adds to the thread carries a class under this block, so a host styles
37
+ * the chat by class rather than by the order its elements happen to come in.
38
+ */
39
+ declare const CHAT_CLASS = "vv-ai-chat";
40
+ declare function bindChat(root: HTMLElement, options?: AiChatBindings): AiChatBinding;
41
+ //#endregion
42
+ //#region src/cards.d.ts
43
+ /** Block classes of the cards below. Every element a card renders carries a class under its block. */
44
+ declare const CARD_LIST_CLASS = "vv-ai-card-list";
45
+ declare const ACTIONS_CLASS = "vv-ai-actions";
46
+ /**
47
+ * Several cards from one tool result, under `vv-ai-card-list` and `vv-ai-card-list--{modifier}`.
48
+ * Items that render nothing are skipped, and a list with nothing in it is null.
49
+ */
50
+ declare function renderCardList<T>(document: Document, items: unknown, render: (item: T) => Node | null, modifier?: string): HTMLElement | null;
51
+ /**
52
+ * A row of things the visitor can do next. An item with `action` is a button that runs the action
53
+ * registered under that name, with `value` as its `data-ai-action-value`; an item with `url` is a
54
+ * link. Each carries `__action`, plus `--primary` or `--secondary`. Null when no item renders.
55
+ */
56
+ declare function renderActions(document: Document, items: readonly AiChatActionItem[]): HTMLElement | null;
57
+ //#endregion
58
+ //#region src/chat.d.ts
59
+ declare function createChatSession(options: AiChatSessionOptions): AiChatSession;
60
+ //#endregion
61
+ //#region src/form-context.d.ts
62
+ /**
63
+ * Tells the AI what the visitor entered into a form embedded in the thread. Whenever `element`
64
+ * changes and holds `options.form`, its filled-in `fields` are summarised as `label: value` and
65
+ * sent with every later question through `binding.setFormContext`, framed as context rather than
66
+ * something the visitor said. Returns a function that stops watching.
67
+ */
68
+ declare function watchFormContext(binding: AiChatBinding, element: HTMLElement, options: AiFormContextOptions): () => void;
69
+ //#endregion
70
+ //#region src/handover.d.ts
71
+ /** The action the handover card's button runs; the binding hands over to a person with it. */
72
+ declare const LIVE_CHAT_ACTION = "livechat";
73
+ /** The tool the Vettvangur.AiChat engine hands over with, from before its payload named its kind. */
74
+ declare const HANDOVER_TOOL = "request_human_agent";
75
+ /** A payload of kind `handover`, or one from the handover tool that names no kind. */
76
+ declare function isHandoverPayload(tool: string, data: unknown): data is AiHandoverPayload;
77
+ /**
78
+ * The visitor's ways to a person: a primary `liveChat` button that runs the `livechat` action when
79
+ * a live chat is available, and a `contact` link to a safe contact URL. The payload's `prefill`
80
+ * goes on the button as its value. Null when neither applies.
81
+ */
82
+ declare function renderHandoverCard(document: Document, data: AiHandoverPayload, labels: Pick<AiChatLabels, 'liveChat' | 'contact'>): HTMLElement | null;
83
+ /**
84
+ * Puts `text` as `vv-ai-actions__note` in place of the live chat button under `parent`, for when
85
+ * no one can take the chat. The contact link stays.
86
+ */
87
+ declare function closeHandoverCard(parent: ParentNode, text: string): void;
88
+ //#endregion
89
+ //#region src/protocol.d.ts
90
+ declare const AI_CHAT_PROTOCOL_VERSION = 1;
91
+ declare function parseStreamEvent(name: string, data: unknown): AiChatStreamEvent | null;
92
+ //#endregion
93
+ //#region src/registry.d.ts
94
+ declare function createAiChatRegistry(): AiChatRegistry;
95
+ //#endregion
96
+ //#region src/stream.d.ts
97
+ declare function readEventStream(response: Response, signal: AbortSignal): AsyncGenerator<AiChatStreamEvent>;
98
+ //#endregion
99
+ //#region src/surfaces.d.ts
100
+ /**
101
+ * A surface that shows one item out of an authored list template. The template is cloned, every
102
+ * element carrying `attribute` whose value is not the payload's `key` field is removed, and the
103
+ * rest of the template stays as authored, so one item is the same markup the whole list shows.
104
+ * Null when the template is missing or no item matches.
105
+ */
106
+ declare function createTemplateItemSurface(options: AiTemplateItemSurfaceOptions): (context: Pick<AiChatExtensionContext, 'root' | 'data'>) => DocumentFragment | null;
107
+ /**
108
+ * A surface of which only the latest copy stays in the thread, for an embedded component whose
109
+ * script binds to the first match in the document or whose fields share ids. What it draws is
110
+ * marked with `data-ai-chat-single` under `key`, and drawing it again removes the earlier copies.
111
+ */
112
+ declare function createSingleSurface<C extends Pick<AiChatExtensionContext, 'root'>, N extends Node>(key: string, surface: (context: C) => N | null): (context: C) => N | null;
113
+ //#endregion
114
+ //#region src/window.d.ts
115
+ /**
116
+ * The binding as a window over the page. Anywhere in the document, a `data-ai-chat-window-open`
117
+ * element opens it, and one that is also `data-ai-chat-window-toggle` closes it again; toggles
118
+ * carry `aria-expanded` and get focus back when it closes. Escape closes the root's
119
+ * `details[data-ai-chat-menu]` first and then the window, a click anywhere but the menu's summary
120
+ * closes the menu, and a `data-ai-chat-expand` link closes the window before it navigates, so the
121
+ * next page does not open it again from the stored thread. Returns a function that undoes it all.
122
+ */
123
+ declare function bindChatWindow(binding: AiChatBinding): () => void;
124
+ /**
125
+ * The `data-ai-launcher-teaser` inside `container`, shown once a session to a visitor who has not
126
+ * started a chat: not while the window is open or its thread has messages. A
127
+ * `data-ai-launcher-dismiss` button in it hides it, as opening the window does. When storage
128
+ * cannot be read the teaser is not shown. Returns a function that undoes it.
129
+ */
130
+ declare function bindLauncherTeaser(binding: AiChatBinding, container: ParentNode, options?: AiLauncherTeaserOptions): () => void;
131
+ //#endregion
132
+ 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 AiChatEventMap, type AiChatExtensionContext, type AiChatHandoverOptions, type AiChatHandoverResult, type AiChatMessage, type AiChatMode, type AiChatRegistry, type AiChatRenderer, type AiChatRequest, type AiChatSession, type AiChatSessionOptions, type AiChatSessionResult, type AiChatSessionStatus, type AiChatStreamEvent, type AiChatSurface, type AiFormContextOptions, type AiHandoverPayload, type AiLauncherTeaserOptions, type AiLiveChatAction, type AiLiveChatAnswers, type AiLiveChatAvailability, type AiLiveChatFactoryContext, type AiLiveChatMessage, type AiLiveChatProvider, type AiLiveChatSheetHost, type AiLiveChatStartOptions, type AiLiveChatSurveyField, type AiTemplateItemSurfaceOptions, type AiTemplateUrlSurfaceOptions, CARD_LIST_CLASS, CHAT_CLASS, HANDOVER_TOOL, LIVE_CHAT_ACTION, 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, assertAnswerCardContract, bindChat, bindChatWindow, bindLauncherTeaser, closeHandoverCard, createAiChatRegistry, createChatSession, createSingleSurface, createTemplateItemSurface, isAnswerCard, isHandoverPayload, parseStreamEvent, readEventStream, renderActions, renderAnswerCard, renderCardList, renderHandoverCard, watchFormContext };
package/dist/chat.js ADDED
@@ -0,0 +1,33 @@
1
+ import { A as MAX_ANSWER_CARD_URL_LENGTH, C as MAX_ANSWER_CARD_TABLES, D as MAX_ANSWER_CARD_TOTAL_STRUCTURAL_ITEMS, E as MAX_ANSWER_CARD_TEXT_LENGTH, M as isAnswerCard, N as renderAnswerCard, O as MAX_ANSWER_CARD_TOTAL_TABLE_CELLS, S as MAX_ANSWER_CARD_SECTIONS, T as MAX_ANSWER_CARD_TABLE_ROWS, _ as renderActions, a as createAiChatRegistry, b as MAX_ANSWER_CARD_FACTS, c as closeHandoverCard, d as createChatSession, f as readEventStream, g as CARD_LIST_CLASS, h as ACTIONS_CLASS, i as bindChat, j as assertAnswerCardContract, k as MAX_ANSWER_CARD_TOTAL_TEXT_CHARACTERS, l as isHandoverPayload, m as parseStreamEvent, n as bindLauncherTeaser, o as HANDOVER_TOOL, p as AI_CHAT_PROTOCOL_VERSION, r as CHAT_CLASS, s as LIVE_CHAT_ACTION, t as bindChatWindow, u as renderHandoverCard, v as renderCardList, w as MAX_ANSWER_CARD_TABLE_CELLS, x as MAX_ANSWER_CARD_LINKS, y as ANSWER_CARD_CLASS } from "./window.js";
2
+ import { n as createTemplateItemSurface, t as createSingleSurface } from "./surfaces.js";
3
+ //#region src/form-context.ts
4
+ /**
5
+ * Tells the AI what the visitor entered into a form embedded in the thread. Whenever `element`
6
+ * changes and holds `options.form`, its filled-in `fields` are summarised as `label: value` and
7
+ * sent with every later question through `binding.setFormContext`, framed as context rather than
8
+ * something the visitor said. Returns a function that stops watching.
9
+ */
10
+ function watchFormContext(binding, element, options) {
11
+ const record = () => {
12
+ const form = element.querySelector(options.form);
13
+ if (!form) return;
14
+ const values = new FormData(form);
15
+ const parts = options.fields.map(([field, label]) => {
16
+ const raw = String(values.get(field) ?? "").trim();
17
+ const value = options.values?.[raw] ?? raw;
18
+ return value ? `${label}: ${value}` : "";
19
+ }).filter(Boolean);
20
+ if (!parts.length) return;
21
+ const note = options.note ? ` ${options.note}` : "";
22
+ binding.setFormContext(options.name, `Context, not a message from the visitor: they filled in ${options.title} with ${parts.join(", ")}.${note}`, options.followUp);
23
+ };
24
+ const observer = new MutationObserver(record);
25
+ observer.observe(element, {
26
+ childList: true,
27
+ subtree: true
28
+ });
29
+ record();
30
+ return () => observer.disconnect();
31
+ }
32
+ //#endregion
33
+ export { ACTIONS_CLASS, AI_CHAT_PROTOCOL_VERSION, ANSWER_CARD_CLASS, CARD_LIST_CLASS, CHAT_CLASS, HANDOVER_TOOL, LIVE_CHAT_ACTION, 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, assertAnswerCardContract, bindChat, bindChatWindow, bindLauncherTeaser, closeHandoverCard, createAiChatRegistry, createChatSession, createSingleSurface, createTemplateItemSurface, isAnswerCard, isHandoverPayload, parseStreamEvent, readEventStream, renderActions, renderAnswerCard, renderCardList, renderHandoverCard, watchFormContext };
@@ -91,6 +91,7 @@ type AiChatStreamEvent = {
91
91
  data: {
92
92
  id: string;
93
93
  name: string;
94
+ label?: string;
94
95
  };
95
96
  } | {
96
97
  name: 'tool_result';
@@ -279,13 +280,6 @@ type AiChatBinding = {
279
280
  on<K extends keyof AiChatEventMap>(name: K, listener: (detail: AiChatEventMap[K]) => void): () => void;
280
281
  destroy(): void;
281
282
  };
282
- type AiCardImage = {
283
- url: string;
284
- url2x?: string | null;
285
- alt?: string | null;
286
- width?: number | null;
287
- height?: number | null;
288
- };
289
283
  type AiChatActionItem = {
290
284
  label: string;
291
285
  action?: string | null;
@@ -341,4 +335,4 @@ type AiLauncherTeaserOptions = {
341
335
  storageKey?: string;
342
336
  };
343
337
  //#endregion
344
- export { AiHandoverPayload as A, AiChatSession as C, AiChatStreamEvent as D, AiChatSessionStatus as E, AiLiveChatFactoryContext as M, AiTemplateItemSurfaceOptions as N, AiChatSurface as O, AiTemplateUrlSurfaceOptions as P, AiChatRequest as S, AiChatSessionResult as T, AiChatLabels as _, AiAnswerCardSection as a, AiChatRegistry as b, AiChatAction as c, AiChatBindings as d, AiChatContext as f, AiChatHandoverResult as g, AiChatHandoverOptions as h, AiAnswerCardLink as i, AiLauncherTeaserOptions as j, AiFormContextOptions as k, AiChatActionItem as l, AiChatExtensionContext as m, AiAnswerCardFact as n, AiAnswerCardTable as o, AiChatEventMap as p, AiAnswerCardLabels as r, AiCardImage as s, AiAnswerCard as t, AiChatBinding as u, AiChatMessage as v, AiChatSessionOptions as w, AiChatRenderer as x, AiChatMode as y };
338
+ export { AiLauncherTeaserOptions as A, AiChatSessionOptions as C, AiChatSurface as D, AiChatStreamEvent as E, AiTemplateItemSurfaceOptions as M, AiTemplateUrlSurfaceOptions as N, AiFormContextOptions as O, AiChatSession as S, AiChatSessionStatus as T, AiChatMessage as _, AiAnswerCardSection as a, AiChatRenderer as b, AiChatActionItem as c, AiChatContext as d, AiChatEventMap as f, AiChatLabels as g, AiChatHandoverResult as h, AiAnswerCardLink as i, AiLiveChatFactoryContext as j, AiHandoverPayload as k, AiChatBinding as l, AiChatHandoverOptions as m, AiAnswerCardFact as n, AiAnswerCardTable as o, AiChatExtensionContext as p, AiAnswerCardLabels as r, AiChatAction as s, AiAnswerCard as t, AiChatBindings as u, AiChatMode as v, AiChatSessionResult as w, AiChatRequest as x, AiChatRegistry as y };
package/dist/dom.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ //#region src/dom.d.ts
2
+ /** An image a card or answer may show. */
3
+ type AiCardImage = {
4
+ url: string;
5
+ url2x?: string | null;
6
+ alt?: string | null;
7
+ width?: number | null;
8
+ height?: number | null;
9
+ };
10
+ declare function isSafeLinkUrl(url: string): boolean;
11
+ declare function createSafeLink(document: Document, label: string, url: string): HTMLAnchorElement | null;
12
+ /**
13
+ * An image only from a site-relative or web URL; anything else is left out rather than loaded. The
14
+ * width and height, when given, let the browser reserve the space before the image arrives.
15
+ */
16
+ declare function createSafeImage(document: Document, image: AiCardImage | null | undefined): HTMLImageElement | null;
17
+ /** An element carrying the BEM class for `part` of `block`, and `text` when there is any. */
18
+ declare function createPart<K extends keyof HTMLElementTagNameMap>(document: Document, tag: K, block: string, part?: string | null, text?: string | null): HTMLElementTagNameMap[K];
19
+ //#endregion
20
+ export { isSafeLinkUrl as a, createSafeLink as i, createPart as n, createSafeImage as r, AiCardImage as t };
package/dist/events.js ADDED
@@ -0,0 +1,76 @@
1
+ //#region src/events.ts
2
+ const MAX_RECORD_LENGTH = 1048576;
3
+ function findRecordBoundary(buffer) {
4
+ const lfIndex = buffer.indexOf("\n\n");
5
+ const crlfIndex = buffer.indexOf("\r\n\r\n");
6
+ if (lfIndex === -1 && crlfIndex === -1) return null;
7
+ if (lfIndex === -1 || crlfIndex !== -1 && crlfIndex < lfIndex) return {
8
+ index: crlfIndex,
9
+ length: 4
10
+ };
11
+ return {
12
+ index: lfIndex,
13
+ length: 2
14
+ };
15
+ }
16
+ function fieldValue(value) {
17
+ return value.startsWith(" ") ? value.slice(1) : value;
18
+ }
19
+ function parseRecord(record) {
20
+ let name;
21
+ const dataLines = [];
22
+ for (const line of record.split(/\r?\n/)) if (line.startsWith("event:")) name = fieldValue(line.slice(6));
23
+ else if (line.startsWith("data:")) dataLines.push(fieldValue(line.slice(5)));
24
+ if (!name || dataLines.length === 0) return null;
25
+ return {
26
+ name,
27
+ data: dataLines.join("\n")
28
+ };
29
+ }
30
+ function abortError() {
31
+ return /* @__PURE__ */ new Error("AI event stream was aborted");
32
+ }
33
+ /**
34
+ * The named records of a streamed response, as they arrive. A record without an `event:` name or
35
+ * `data:` line is skipped. The stream ends with the response; stopping early, by breaking out of
36
+ * the loop or aborting `signal`, cancels the response body.
37
+ */
38
+ async function* readServerEvents(response, signal) {
39
+ if (!response.body) throw new Error("AI response has no body");
40
+ if (signal.aborted) throw abortError();
41
+ const decoder = new TextDecoder();
42
+ const reader = response.body.getReader();
43
+ let buffer = "";
44
+ let readerDone = false;
45
+ const cancelReader = () => {
46
+ reader.cancel().catch(() => void 0);
47
+ };
48
+ signal.addEventListener("abort", cancelReader, { once: true });
49
+ try {
50
+ while (!readerDone) {
51
+ if (signal.aborted) throw abortError();
52
+ const { done, value } = await reader.read();
53
+ if (signal.aborted) throw abortError();
54
+ if (done) {
55
+ readerDone = true;
56
+ buffer += decoder.decode();
57
+ } else buffer += decoder.decode(value, { stream: true });
58
+ let boundary = findRecordBoundary(buffer);
59
+ while (boundary) {
60
+ const record = parseRecord(buffer.slice(0, boundary.index));
61
+ buffer = buffer.slice(boundary.index + boundary.length);
62
+ if (record) yield record;
63
+ boundary = findRecordBoundary(buffer);
64
+ }
65
+ if (buffer.length > MAX_RECORD_LENGTH) throw new Error("AI event stream sent an event that is too large");
66
+ }
67
+ } finally {
68
+ signal.removeEventListener("abort", cancelReader);
69
+ if (!readerDone) try {
70
+ await reader.cancel();
71
+ } catch {}
72
+ reader.releaseLock();
73
+ }
74
+ }
75
+ //#endregion
76
+ export { readServerEvents as t };
package/dist/index.d.ts CHANGED
@@ -1,142 +1,19 @@
1
- import { a as AiLiveChatMessage, c as AiLiveChatStartOptions, l as AiLiveChatSurveyField, n as AiLiveChatAnswers, o as AiLiveChatProvider, r as AiLiveChatAvailability, s as AiLiveChatSheetHost, t as AiLiveChatAction } from "./provider.js";
2
- import { A as AiHandoverPayload, C as AiChatSession, D as AiChatStreamEvent, E as AiChatSessionStatus, M as AiLiveChatFactoryContext, N as AiTemplateItemSurfaceOptions, O as AiChatSurface, P as AiTemplateUrlSurfaceOptions, S as AiChatRequest, T as AiChatSessionResult, _ as AiChatLabels, a as AiAnswerCardSection, b as AiChatRegistry, c as AiChatAction, d as AiChatBindings, f as AiChatContext, g as AiChatHandoverResult, h as AiChatHandoverOptions, i as AiAnswerCardLink, j as AiLauncherTeaserOptions, k as AiFormContextOptions, l as AiChatActionItem, m as AiChatExtensionContext, n as AiAnswerCardFact, o as AiAnswerCardTable, p as AiChatEventMap, r as AiAnswerCardLabels, s as AiCardImage, t as AiAnswerCard, u as AiChatBinding, v as AiChatMessage, w as AiChatSessionOptions, x as AiChatRenderer, y as AiChatMode } from "./contracts.js";
3
- //#region src/answer-card.d.ts
4
- declare const MAX_ANSWER_CARD_SECTIONS = 12;
5
- declare const MAX_ANSWER_CARD_FACTS = 24;
6
- declare const MAX_ANSWER_CARD_LINKS = 24;
7
- declare const MAX_ANSWER_CARD_TABLES = 8;
8
- declare const MAX_ANSWER_CARD_TABLE_ROWS = 50;
9
- declare const MAX_ANSWER_CARD_TABLE_CELLS = 12;
10
- declare const MAX_ANSWER_CARD_TEXT_LENGTH = 8000;
11
- declare const MAX_ANSWER_CARD_URL_LENGTH = 2048;
12
- declare const MAX_ANSWER_CARD_TOTAL_TEXT_CHARACTERS = 24000;
13
- declare const MAX_ANSWER_CARD_TOTAL_STRUCTURAL_ITEMS = 512;
14
- declare const MAX_ANSWER_CARD_TOTAL_TABLE_CELLS = 512;
1
+ import { a as isSafeLinkUrl, i as createSafeLink, n as createPart, r as createSafeImage, t as AiCardImage } from "./dom.js";
2
+ //#region src/events.d.ts
3
+ /** One record of a server-sent event stream: its `event:` name and its `data:` lines joined. */
4
+ type AiServerEvent = {
5
+ name: string;
6
+ data: string;
7
+ };
15
8
  /**
16
- * Every element an answer card renders carries a class under this block, so a host styles the card
17
- * by class rather than by the order its elements happen to come in.
9
+ * The named records of a streamed response, as they arrive. A record without an `event:` name or
10
+ * `data:` line is skipped. The stream ends with the response; stopping early, by breaking out of
11
+ * the loop or aborting `signal`, cancels the response body.
18
12
  */
19
- declare const ANSWER_CARD_CLASS = "vv-ai-answer-card";
20
- /**
21
- * Whether `renderAnswerCard` will draw `value` as a card. A host that builds cards elsewhere, a
22
- * server or a test, can hold its output to the same limits the renderer applies.
23
- */
24
- declare function isAnswerCard(value: unknown): value is AiAnswerCard;
25
- declare function renderAnswerCard(document: Document, data: unknown, labels: AiAnswerCardLabels): HTMLElement | null;
26
- /**
27
- * Throws when `card` is not an answer card `renderAnswerCard` will draw, or when a field it shows
28
- * as plain text (titles, facts, table cells, notes) holds Markdown that would show literally. For
29
- * a server's or a test's own cards; the message names what is wrong.
30
- */
31
- declare function assertAnswerCardContract(card: unknown): asserts card is AiAnswerCard;
32
- //#endregion
33
- //#region src/bind.d.ts
34
- /**
35
- * Every element the binding adds to the thread carries a class under this block, so a host styles
36
- * the chat by class rather than by the order its elements happen to come in.
37
- */
38
- declare const CHAT_CLASS = "vv-ai-chat";
39
- declare function bindChat(root: HTMLElement, options?: AiChatBindings): AiChatBinding;
40
- //#endregion
41
- //#region src/cards.d.ts
42
- /** Block classes of the cards below. Every element a card renders carries a class under its block. */
43
- declare const CARD_LIST_CLASS = "vv-ai-card-list";
44
- declare const ACTIONS_CLASS = "vv-ai-actions";
45
- /**
46
- * Several cards from one tool result, under `vv-ai-card-list` and `vv-ai-card-list--{modifier}`.
47
- * Items that render nothing are skipped, and a list with nothing in it is null.
48
- */
49
- declare function renderCardList<T>(document: Document, items: unknown, render: (item: T) => Node | null, modifier?: string): HTMLElement | null;
50
- /**
51
- * A row of things the visitor can do next. An item with `action` is a button that runs the action
52
- * registered under that name, with `value` as its `data-ai-action-value`; an item with `url` is a
53
- * link. Each carries `__action`, plus `--primary` or `--secondary`. Null when no item renders.
54
- */
55
- declare function renderActions(document: Document, items: readonly AiChatActionItem[]): HTMLElement | null;
56
- //#endregion
57
- //#region src/chat.d.ts
58
- declare function createChatSession(options: AiChatSessionOptions): AiChatSession;
59
- //#endregion
60
- //#region src/dom.d.ts
61
- declare function isSafeLinkUrl(url: string): boolean;
62
- declare function createSafeLink(document: Document, label: string, url: string): HTMLAnchorElement | null;
63
- /**
64
- * An image only from a site-relative or web URL; anything else is left out rather than loaded. The
65
- * width and height, when given, let the browser reserve the space before the image arrives.
66
- */
67
- declare function createSafeImage(document: Document, image: AiCardImage | null | undefined): HTMLImageElement | null;
68
- /** An element carrying the BEM class for `part` of `block`, and `text` when there is any. */
69
- declare function createPart<K extends keyof HTMLElementTagNameMap>(document: Document, tag: K, block: string, part?: string | null, text?: string | null): HTMLElementTagNameMap[K];
70
- //#endregion
71
- //#region src/form-context.d.ts
72
- /**
73
- * Tells the AI what the visitor entered into a form embedded in the thread. Whenever `element`
74
- * changes and holds `options.form`, its filled-in `fields` are summarised as `label: value` and
75
- * sent with every later question through `binding.setFormContext`, framed as context rather than
76
- * something the visitor said. Returns a function that stops watching.
77
- */
78
- declare function watchFormContext(binding: AiChatBinding, element: HTMLElement, options: AiFormContextOptions): () => void;
79
- //#endregion
80
- //#region src/handover.d.ts
81
- /** The action the handover card's button runs; the binding hands over to a person with it. */
82
- declare const LIVE_CHAT_ACTION = "livechat";
83
- /** The tool the Vettvangur.AiChat engine hands over with, from before its payload named its kind. */
84
- declare const HANDOVER_TOOL = "request_human_agent";
85
- /** A payload of kind `handover`, or one from the handover tool that names no kind. */
86
- declare function isHandoverPayload(tool: string, data: unknown): data is AiHandoverPayload;
87
- /**
88
- * The visitor's ways to a person: a primary `liveChat` button that runs the `livechat` action when
89
- * a live chat is available, and a `contact` link to a safe contact URL. The payload's `prefill`
90
- * goes on the button as its value. Null when neither applies.
91
- */
92
- declare function renderHandoverCard(document: Document, data: AiHandoverPayload, labels: Pick<AiChatLabels, 'liveChat' | 'contact'>): HTMLElement | null;
93
- /**
94
- * Puts `text` as `vv-ai-actions__note` in place of the live chat button under `parent`, for when
95
- * no one can take the chat. The contact link stays.
96
- */
97
- declare function closeHandoverCard(parent: ParentNode, text: string): void;
98
- //#endregion
99
- //#region src/protocol.d.ts
100
- declare const AI_CHAT_PROTOCOL_VERSION = 1;
101
- declare function parseStreamEvent(name: string, data: unknown): AiChatStreamEvent | null;
102
- //#endregion
103
- //#region src/registry.d.ts
104
- declare function createAiChatRegistry(): AiChatRegistry;
105
- //#endregion
106
- //#region src/stream.d.ts
107
- declare function readEventStream(response: Response, signal: AbortSignal): AsyncGenerator<AiChatStreamEvent>;
13
+ declare function readServerEvents(response: Response, signal: AbortSignal): AsyncGenerator<AiServerEvent>;
108
14
  //#endregion
109
- //#region src/surfaces.d.ts
110
- /**
111
- * A surface that shows one item out of an authored list template. The template is cloned, every
112
- * element carrying `attribute` whose value is not the payload's `key` field is removed, and the
113
- * rest of the template stays as authored, so one item is the same markup the whole list shows.
114
- * Null when the template is missing or no item matches.
115
- */
116
- declare function createTemplateItemSurface(options: AiTemplateItemSurfaceOptions): (context: Pick<AiChatExtensionContext, 'root' | 'data'>) => DocumentFragment | null;
117
- /**
118
- * A surface of which only the latest copy stays in the thread, for an embedded component whose
119
- * script binds to the first match in the document or whose fields share ids. What it draws is
120
- * marked with `data-ai-chat-single` under `key`, and drawing it again removes the earlier copies.
121
- */
122
- declare function createSingleSurface<C extends Pick<AiChatExtensionContext, 'root'>, N extends Node>(key: string, surface: (context: C) => N | null): (context: C) => N | null;
123
- //#endregion
124
- //#region src/window.d.ts
125
- /**
126
- * The binding as a window over the page. Anywhere in the document, a `data-ai-chat-window-open`
127
- * element opens it, and one that is also `data-ai-chat-window-toggle` closes it again; toggles
128
- * carry `aria-expanded` and get focus back when it closes. Escape closes the root's
129
- * `details[data-ai-chat-menu]` first and then the window, a click anywhere but the menu's summary
130
- * closes the menu, and a `data-ai-chat-expand` link closes the window before it navigates, so the
131
- * next page does not open it again from the stored thread. Returns a function that undoes it all.
132
- */
133
- declare function bindChatWindow(binding: AiChatBinding): () => void;
134
- /**
135
- * The `data-ai-launcher-teaser` inside `container`, shown once a session to a visitor who has not
136
- * started a chat: not while the window is open or its thread has messages. A
137
- * `data-ai-launcher-dismiss` button in it hides it, as opening the window does. When storage
138
- * cannot be read the teaser is not shown. Returns a function that undoes it.
139
- */
140
- declare function bindLauncherTeaser(binding: AiChatBinding, container: ParentNode, options?: AiLauncherTeaserOptions): () => void;
15
+ //#region src/markdown.d.ts
16
+ declare const MAX_MARKDOWN_CHARACTERS = 8000;
17
+ declare function renderMarkdown(document: Document, source: string): DocumentFragment;
141
18
  //#endregion
142
- 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 AiChatEventMap, type AiChatExtensionContext, type AiChatHandoverOptions, type AiChatHandoverResult, type AiChatMessage, type AiChatMode, type AiChatRegistry, type AiChatRenderer, type AiChatRequest, type AiChatSession, type AiChatSessionOptions, type AiChatSessionResult, type AiChatSessionStatus, type AiChatStreamEvent, type AiChatSurface, type AiFormContextOptions, type AiHandoverPayload, type AiLauncherTeaserOptions, type AiLiveChatAction, type AiLiveChatAnswers, type AiLiveChatAvailability, type AiLiveChatFactoryContext, type AiLiveChatMessage, type AiLiveChatProvider, type AiLiveChatSheetHost, type AiLiveChatStartOptions, type AiLiveChatSurveyField, type AiTemplateItemSurfaceOptions, type AiTemplateUrlSurfaceOptions, CARD_LIST_CLASS, CHAT_CLASS, HANDOVER_TOOL, LIVE_CHAT_ACTION, 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, assertAnswerCardContract, bindChat, bindChatWindow, bindLauncherTeaser, closeHandoverCard, createAiChatRegistry, createChatSession, createPart, createSafeImage, createSafeLink, createSingleSurface, createTemplateItemSurface, isAnswerCard, isHandoverPayload, isSafeLinkUrl, parseStreamEvent, readEventStream, renderActions, renderAnswerCard, renderCardList, renderHandoverCard, watchFormContext };
19
+ export { type AiCardImage, type AiServerEvent, MAX_MARKDOWN_CHARACTERS, createPart, createSafeImage, createSafeLink, isSafeLinkUrl, readServerEvents, renderMarkdown };