@vettvangur/ai-sdk 0.5.2 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/dom.js ADDED
@@ -0,0 +1,76 @@
1
+ //#region src/dom.ts
2
+ function hasUnsafeLinkCharacter(value) {
3
+ for (const character of value) {
4
+ const code = character.charCodeAt(0);
5
+ if (/\s/.test(character) || character === "\\" || code <= 31 || code >= 127 && code <= 159) return true;
6
+ }
7
+ return false;
8
+ }
9
+ function isSafeLinkUrl(url) {
10
+ if (url.length === 0 || hasUnsafeLinkCharacter(url)) return false;
11
+ if (url.startsWith("/") || url.startsWith("#")) return !url.startsWith("//");
12
+ if (/^https?:\/\//i.test(url)) try {
13
+ const parsed = new URL(url);
14
+ return parsed.protocol === "http:" || parsed.protocol === "https:";
15
+ } catch {
16
+ return false;
17
+ }
18
+ return /^(?:mailto|tel):[^:]+$/i.test(url);
19
+ }
20
+ function createSafeLink(document, label, url) {
21
+ if (!isSafeLinkUrl(url)) return null;
22
+ const link = document.createElement("a");
23
+ link.href = url;
24
+ link.append(document.createTextNode(label));
25
+ if (/^https?:\/\//i.test(url)) {
26
+ link.target = "_blank";
27
+ link.rel = "noopener noreferrer";
28
+ }
29
+ return link;
30
+ }
31
+ function isPlainObject(value) {
32
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
33
+ const prototype = Object.getPrototypeOf(value);
34
+ return prototype === Object.prototype || prototype === null;
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
+ }
61
+ /**
62
+ * An attribute's JSON, or undefined when it is missing. A malformed value is reported and read as
63
+ * missing, so one bad attribute does not stop the rest of the chat from working.
64
+ */
65
+ function readJsonAttribute(element, name, onError) {
66
+ const value = element.getAttribute(name);
67
+ if (!value) return;
68
+ try {
69
+ return JSON.parse(value);
70
+ } catch {
71
+ onError?.(/* @__PURE__ */ new Error(`AI chat could not read ${name} as JSON`));
72
+ return;
73
+ }
74
+ }
75
+ //#endregion
76
+ export { isSafeLinkUrl as a, isPlainObject as i, createSafeImage as n, readJsonAttribute as o, createSafeLink as r, createPart as t };
package/dist/index.d.ts CHANGED
@@ -1,199 +1,5 @@
1
- //#region src/contracts.d.ts
2
- type AiChatMessage = {
3
- role: 'user' | 'assistant';
4
- content: string;
5
- };
6
- type AiChatRequest = {
7
- messages: AiChatMessage[];
8
- provider?: string;
9
- context?: Record<string, string>;
10
- };
11
- type AiChatContext = Record<string, string>;
12
- type AiChatSessionStatus = 'idle' | 'sending' | 'disposed';
13
- type AiChatSessionResult = {
14
- turn: string | null;
15
- canceled: boolean;
16
- error: Error | null;
17
- };
18
- type AiChatSessionOptions = {
19
- endpoint: string;
20
- provider?: string;
21
- headers?: Record<string, string>;
22
- timeoutMs?: number;
23
- fetch?: typeof fetch;
24
- onEvent?: (event: AiChatStreamEvent) => void;
25
- };
26
- type AiChatSession = {
27
- readonly history: readonly AiChatMessage[];
28
- readonly context: Readonly<AiChatContext>;
29
- readonly status: AiChatSessionStatus;
30
- send(message: string): Promise<AiChatSessionResult>;
31
- cancel(): void;
32
- reset(): void;
33
- setContext(name: string, value: string): void;
34
- setContextMessage(name: string, content: string): void;
35
- addAssistantReply(content: string): void;
36
- clearContext(name: string): void;
37
- subscribe(listener: (event: AiChatStreamEvent) => void): () => void;
38
- dispose(): void;
39
- };
40
- type AiAnswerCardFact = {
41
- label: string;
42
- value: string;
43
- };
44
- type AiAnswerCardLink = {
45
- label: string;
46
- url: string;
47
- };
48
- type AiAnswerCardTable = {
49
- label?: string | null;
50
- headers: string[];
51
- rows: string[][];
52
- };
53
- type AiAnswerCardSection = {
54
- title?: string | null;
55
- text?: string | null;
56
- facts?: AiAnswerCardFact[] | null;
57
- tables?: AiAnswerCardTable[] | null;
58
- links?: AiAnswerCardLink[] | null;
59
- note?: string | null;
60
- collapsible?: boolean;
61
- };
62
- type AiAnswerCard = {
63
- kind: 'answer';
64
- title: string;
65
- summary?: string | null;
66
- highlight?: AiAnswerCardFact | null;
67
- sections?: AiAnswerCardSection[] | null;
68
- note?: string | null;
69
- actions?: AiAnswerCardLink[] | null;
70
- sources?: AiAnswerCardLink[] | null;
71
- sourceNote?: string | null;
72
- };
73
- type AiAnswerCardLabels = {
74
- sources: string;
75
- details: string;
76
- table: string;
77
- tableScroll: string;
78
- };
79
- type AiChatStreamEvent = {
80
- name: 'delta';
81
- data: {
82
- text: string;
83
- };
84
- } | {
85
- name: 'tool';
86
- data: {
87
- id: string;
88
- name: string;
89
- };
90
- } | {
91
- name: 'tool_result';
92
- data: {
93
- id: string;
94
- name: string;
95
- data: unknown;
96
- reply: string | null;
97
- };
98
- } | {
99
- name: 'tool_done';
100
- data: {
101
- id: string;
102
- name: string;
103
- isError: boolean;
104
- };
105
- } | {
106
- name: 'suggestions';
107
- data: {
108
- suggestions: string[];
109
- };
110
- } | {
111
- name: 'done';
112
- data: {
113
- turn: string | null;
114
- };
115
- } | {
116
- name: 'error';
117
- data: {
118
- message: string;
119
- };
120
- };
121
- type AiChatLabels = AiAnswerCardLabels & {
122
- followUps: string;
123
- error: string;
124
- timeout: string;
125
- toolRunning: string;
126
- toolComplete: string;
127
- toolFailed: string;
128
- toolInterrupted: string;
129
- };
130
- type AiChatExtensionContext = {
131
- document: Document;
132
- root: HTMLElement;
133
- tool: string;
134
- data: unknown;
135
- reply: string | null;
136
- labels: AiChatLabels;
137
- };
138
- type AiChatRenderer = (context: AiChatExtensionContext) => Node | null;
139
- type AiChatSurface = (context: AiChatExtensionContext) => Node | null;
140
- type AiChatActionContext = {
141
- root: HTMLElement;
142
- element: HTMLElement;
143
- value: string | null;
144
- session: AiChatSession;
145
- };
146
- type AiChatAction = (context: AiChatActionContext) => undefined | {
147
- context: [string, string];
148
- } | Promise<undefined | {
149
- context: [string, string];
150
- }>;
151
- type AiChatRegistry = {
152
- registerRenderer(name: string, renderer: AiChatRenderer): () => void;
153
- registerSurface(name: string, surface: AiChatSurface): () => void;
154
- registerAction(name: string, action: AiChatAction): () => void;
155
- };
156
- type AiChatBindings = {
157
- endpoint?: string;
158
- provider?: string;
159
- antiforgeryHeader?: string;
160
- antiforgeryToken?: string;
161
- timeoutMs?: number;
162
- labels?: Partial<AiChatLabels>;
163
- toolLabels?: Record<string, string>;
164
- feedbackEndpoint?: string;
165
- offsetElement?: HTMLElement | null;
166
- registry?: AiChatRegistry;
167
- onEmbedded?: (element: HTMLElement) => void;
168
- onError?: (error: Error) => void;
169
- };
170
- type AiChatBinding = {
171
- session: AiChatSession;
172
- labels: Readonly<AiChatLabels>;
173
- appendAssistantReply(text: string): void;
174
- setFormContext(name: string, summary: string, followUp?: string | null): void;
175
- destroy(): void;
176
- };
177
- type AiCardImage = {
178
- url: string;
179
- url2x?: string | null;
180
- alt?: string | null;
181
- width?: number | null;
182
- height?: number | null;
183
- };
184
- type AiChatActionItem = {
185
- label: string;
186
- action?: string | null;
187
- value?: string | null;
188
- url?: string | null;
189
- primary?: boolean;
190
- };
191
- type AiTemplateItemSurfaceOptions = {
192
- template: string;
193
- attribute: string;
194
- key: string;
195
- };
196
- //#endregion
1
+ import { a as AiLiveChatProvider, i as AiLiveChatMessage, n as AiLiveChatAvailability, o as AiLiveChatStartOptions, s as AiLiveChatSurveyField, t as AiLiveChatAnswers } 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";
197
3
  //#region src/answer-card.d.ts
198
4
  declare const MAX_ANSWER_CARD_SECTIONS = 12;
199
5
  declare const MAX_ANSWER_CARD_FACTS = 24;
@@ -217,6 +23,12 @@ declare const ANSWER_CARD_CLASS = "vv-ai-answer-card";
217
23
  */
218
24
  declare function isAnswerCard(value: unknown): value is AiAnswerCard;
219
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;
220
32
  //#endregion
221
33
  //#region src/bind.d.ts
222
34
  /**
@@ -256,6 +68,28 @@ declare function createSafeImage(document: Document, image: AiCardImage | null |
256
68
  /** An element carrying the BEM class for `part` of `block`, and `text` when there is any. */
257
69
  declare function createPart<K extends keyof HTMLElementTagNameMap>(document: Document, tag: K, block: string, part?: string | null, text?: string | null): HTMLElementTagNameMap[K];
258
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. Null when neither applies.
90
+ */
91
+ declare function renderHandoverCard(document: Document, data: AiHandoverPayload, labels: Pick<AiChatLabels, 'liveChat' | 'contact'>): HTMLElement | null;
92
+ //#endregion
259
93
  //#region src/protocol.d.ts
260
94
  declare const AI_CHAT_PROTOCOL_VERSION = 1;
261
95
  declare function parseStreamEvent(name: string, data: unknown): AiChatStreamEvent | null;
@@ -273,6 +107,30 @@ declare function readEventStream(response: Response, signal: AbortSignal): Async
273
107
  * rest of the template stays as authored, so one item is the same markup the whole list shows.
274
108
  * Null when the template is missing or no item matches.
275
109
  */
276
- declare function createTemplateItemSurface(options: AiTemplateItemSurfaceOptions): (context: AiChatExtensionContext) => DocumentFragment | null;
110
+ declare function createTemplateItemSurface(options: AiTemplateItemSurfaceOptions): (context: Pick<AiChatExtensionContext, 'root' | 'data'>) => DocumentFragment | null;
111
+ /**
112
+ * A surface of which only the latest copy stays in the thread, for an embedded component whose
113
+ * script binds to the first match in the document or whose fields share ids. What it draws is
114
+ * marked with `data-ai-chat-single` under `key`, and drawing it again removes the earlier copies.
115
+ */
116
+ declare function createSingleSurface<C extends Pick<AiChatExtensionContext, 'root'>, N extends Node>(key: string, surface: (context: C) => N | null): (context: C) => N | null;
117
+ //#endregion
118
+ //#region src/window.d.ts
119
+ /**
120
+ * The binding as a window over the page. Anywhere in the document, a `data-ai-chat-window-open`
121
+ * element opens it, and one that is also `data-ai-chat-window-toggle` closes it again; toggles
122
+ * carry `aria-expanded` and get focus back when it closes. Escape closes the root's
123
+ * `details[data-ai-chat-menu]` first and then the window, a click anywhere but the menu's summary
124
+ * closes the menu, and a `data-ai-chat-expand` link closes the window before it navigates, so the
125
+ * next page does not open it again from the stored thread. Returns a function that undoes it all.
126
+ */
127
+ declare function bindChatWindow(binding: AiChatBinding): () => void;
128
+ /**
129
+ * The `data-ai-launcher-teaser` inside `container`, shown once a session to a visitor who has not
130
+ * started a chat: not while the window is open or its thread has messages. A
131
+ * `data-ai-launcher-dismiss` button in it hides it, as opening the window does. When storage
132
+ * cannot be read the teaser is not shown. Returns a function that undoes it.
133
+ */
134
+ declare function bindLauncherTeaser(binding: AiChatBinding, container: ParentNode, options?: AiLauncherTeaserOptions): () => void;
277
135
  //#endregion
278
- 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 AiTemplateItemSurfaceOptions, CARD_LIST_CLASS, CHAT_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, createPart, createSafeImage, createSafeLink, createTemplateItemSurface, isAnswerCard, isSafeLinkUrl, parseStreamEvent, readEventStream, renderActions, renderAnswerCard, renderCardList };
136
+ 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 AiLiveChatAnswers, type AiLiveChatAvailability, type AiLiveChatFactoryContext, type AiLiveChatMessage, type AiLiveChatProvider, 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, createAiChatRegistry, createChatSession, createPart, createSafeImage, createSafeLink, createSingleSurface, createTemplateItemSurface, isAnswerCard, isHandoverPayload, isSafeLinkUrl, parseStreamEvent, readEventStream, renderActions, renderAnswerCard, renderCardList, renderHandoverCard, watchFormContext };