@nex-ai-ch/widget-sdk 0.0.0-stage → 0.8.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 NEX-AI.ch
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,41 @@
1
- # Temporary Holding Version
1
+ # @nex-ai-ch/widget-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Typings and a thin loader for the NEX Widget SDK. The widget itself is **not**
4
+ in this package: it is served by your own box and loaded from there, so a pin
5
+ change on the box updates every page without a new npm release.
6
+
7
+ ```sh
8
+ npm i @nex-ai-ch/widget-sdk
9
+ ```
10
+
11
+ ```ts
12
+ import { init } from '@nex-ai-ch/widget-sdk'
13
+
14
+ const widget = await init({
15
+ src: 'https://<your-box>/widget/v1/nex-widget.mjs', // required
16
+ profile: 'website',
17
+ getAuthToken: () => session.token, // optional: signed-in visitors
18
+ currentMemberId: session.memberId, // optional
19
+ lang: 'de',
20
+ })
21
+ widget.on('linkclick', (event) => router.navigate(event.path))
22
+ ```
23
+
24
+ - `src` is the `https://` URL of the module on your box (plain `http://` only for
25
+ `localhost`, `127.0.0.1` and `[::1]`). It is required; the package does
26
+ not guess a host. The bundle lives on the box under `/widget/v1/`
27
+ (`nex-widget.mjs`, ES module).
28
+ - `init` takes every option of the SDK's own `init()` (`profile`,
29
+ `getAuthToken`, `currentMemberId`, `lang`, ...) and returns the same handle.
30
+ See the SDK reference, `docs/SDK.md` in the repository, for all options and
31
+ events.
32
+ - If the box serves another core MAJOR.MINOR than this package was built for,
33
+ the loader logs one `console.warn` per page. It never blocks.
34
+ - `coreVersion` is the core version this package was built from.
35
+ `isNexWidgetError(e)` recognises the SDK's errors (`e.code`).
36
+ - All public types are exported (`InitConfig`, `WidgetHandle`, `WidgetEvents`,
37
+ `ErrorCode`, ...).
38
+ - ESM only, no dependencies. Bundlers leave the box import alone
39
+ (`webpackIgnore` / `@vite-ignore`).
40
+
41
+ Versions follow the widget core: package `0.7.x` matches core `0.7.x`.
@@ -0,0 +1,5 @@
1
+ /**
2
+ * The core version this package was built from. Bumped by the release commit
3
+ * together with widget/package.json (core-version.test.ts fails otherwise).
4
+ */
5
+ export declare const CORE_VERSION = "0.8.0";
@@ -0,0 +1,5 @@
1
+ /**
2
+ * The core version this package was built from. Bumped by the release commit
3
+ * together with widget/package.json (core-version.test.ts fails otherwise).
4
+ */
5
+ export const CORE_VERSION = '0.8.0';
@@ -0,0 +1,15 @@
1
+ import type { NexWidgetError } from './nex-widget.js';
2
+ export type { EntryPointOrigin, ErrorCode, HistoryLayout, InitConfig, Lang, MountMode, NexWidgetError, PageContext, PageContextInput, Position, RouteNode, ThemeOverride, UserSettings, WidgetEvents, WidgetHandle, WidgetMode, } from './nex-widget.js';
3
+ export type { LoaderConfig } from './loader.js';
4
+ /** The core version this package was built from. */
5
+ export declare const coreVersion: string;
6
+ /**
7
+ * Loads the widget module from `src` (your box) and initialises it. Same
8
+ * options as the module's own init(), with `src` required.
9
+ */
10
+ export declare const init: (config: import("./loader.js").LoaderConfig) => Promise<import("./nex-widget.js").WidgetHandle>;
11
+ /**
12
+ * NexWidgetError lives in the module on the box, so `instanceof` does not work
13
+ * across the package boundary; this checks the shape instead.
14
+ */
15
+ export declare function isNexWidgetError(e: unknown): e is NexWidgetError;
package/dist/index.js ADDED
@@ -0,0 +1,18 @@
1
+ import { CORE_VERSION } from './core-version.js';
2
+ import { createInit } from './loader.js';
3
+ /** The core version this package was built from. */
4
+ export const coreVersion = CORE_VERSION;
5
+ /**
6
+ * Loads the widget module from `src` (your box) and initialises it. Same
7
+ * options as the module's own init(), with `src` required.
8
+ */
9
+ export const init = /*#__PURE__*/ createInit(
10
+ // The module stays on the box: bundlers must leave this import alone.
11
+ (src) => import(/* webpackIgnore: true */ /* @vite-ignore */ src));
12
+ /**
13
+ * NexWidgetError lives in the module on the box, so `instanceof` does not work
14
+ * across the package boundary; this checks the shape instead.
15
+ */
16
+ export function isNexWidgetError(e) {
17
+ return e instanceof Error && e.name === 'NexWidgetError' && typeof e.code === 'string';
18
+ }
@@ -0,0 +1,19 @@
1
+ import type { InitConfig, WidgetHandle } from './nex-widget.js';
2
+ /** `InitConfig` with the module location made mandatory. */
3
+ export type LoaderConfig = Omit<InitConfig, 'src'> & {
4
+ /** Absolute URL of the module on your box, e.g. https://<box>/widget/v1/nex-widget.mjs */
5
+ src: string;
6
+ };
7
+ /** What the box's nex-widget.mjs exports, as far as the loader depends on it. */
8
+ export interface WidgetModule {
9
+ init(config: InitConfig): Promise<WidgetHandle>;
10
+ version?: unknown;
11
+ }
12
+ export type Importer = (src: string) => Promise<WidgetModule>;
13
+ /**
14
+ * A warning text when module and package differ in MAJOR.MINOR (before 1.0 the
15
+ * minor is the contract boundary), else null. Patch and pre-release suffixes
16
+ * do not count.
17
+ */
18
+ export declare function versionWarning(moduleVersion: unknown, built: string, src: string): string | null;
19
+ export declare function createInit(importer: Importer, built?: string): (config: LoaderConfig) => Promise<WidgetHandle>;
package/dist/loader.js ADDED
@@ -0,0 +1,58 @@
1
+ import { CORE_VERSION } from './core-version.js';
2
+ const MAJOR_MINOR = /^(\d+)\.(\d+)\.\d+/;
3
+ /**
4
+ * A warning text when module and package differ in MAJOR.MINOR (before 1.0 the
5
+ * minor is the contract boundary), else null. Patch and pre-release suffixes
6
+ * do not count.
7
+ */
8
+ export function versionWarning(moduleVersion, built, src) {
9
+ const mod = typeof moduleVersion === 'string' ? MAJOR_MINOR.exec(moduleVersion) : null;
10
+ if (!mod) {
11
+ return `[nex-widget] ${src} reports no readable version; @nex-ai-ch/widget-sdk was built for core ${built}. Types and behaviour may differ.`;
12
+ }
13
+ const own = MAJOR_MINOR.exec(built);
14
+ if (own && own[1] === mod[1] && own[2] === mod[2])
15
+ return null;
16
+ return `[nex-widget] @nex-ai-ch/widget-sdk was built for core ${built}, but ${src} serves ${String(moduleVersion)}. Types and behaviour may differ; update the package or the box pin.`;
17
+ }
18
+ const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
19
+ /** https anywhere; plain http only for the local dev stack. Anything else is code we would run unprotected. */
20
+ function isAllowedSrc(src) {
21
+ if (typeof src !== 'string')
22
+ return false;
23
+ let url;
24
+ try {
25
+ url = new URL(src);
26
+ }
27
+ catch {
28
+ return false;
29
+ }
30
+ return url.protocol === 'https:' || (url.protocol === 'http:' && LOCAL_HOSTS.has(url.hostname));
31
+ }
32
+ export function createInit(importer, built = CORE_VERSION) {
33
+ let warned = false;
34
+ return async function init(config) {
35
+ const src = config.src;
36
+ if (!isAllowedSrc(src)) {
37
+ throw new TypeError("[nex-widget] init({ src }) needs the absolute https:// URL of your box's module, e.g. https://<box>/widget/v1/nex-widget.mjs (plain http:// is only accepted for localhost, 127.0.0.1 and [::1])");
38
+ }
39
+ let mod;
40
+ try {
41
+ mod = await importer(src);
42
+ }
43
+ catch (cause) {
44
+ throw new Error(`[nex-widget] could not load ${src}`, { cause });
45
+ }
46
+ if (typeof mod?.init !== 'function') {
47
+ throw new Error(`[nex-widget] ${src} is not a NEX Widget module (no init export)`);
48
+ }
49
+ if (!warned) {
50
+ const text = versionWarning(mod.version, built, src);
51
+ if (text) {
52
+ warned = true;
53
+ console.warn(text);
54
+ }
55
+ }
56
+ return mod.init(config);
57
+ };
58
+ }
@@ -0,0 +1,261 @@
1
+ // Public types for the NEX Widget SDK. Shipped next to the bundle as
2
+ // /widget/v1/nex-widget.d.ts. Hand-written on purpose: this is the contract we
3
+ // promise host pages, and it must not drift with an internal refactor.
4
+ //
5
+ // It is deliberately NARROWER than the module's export list. `src/sdk/index.ts`
6
+ // also exports `resolveSelfUrl` and re-exports `FRAME_ID`; both are internals
7
+ // that happen to be reachable, not promises. The iframe's fixed id is named in
8
+ // docs/SDK.md as a limit ("one widget per page"), not as an import.
9
+
10
+ export type Lang = 'de' | 'en' | 'fr' | 'it'
11
+ export type Position = 'bottom-right' | 'bottom-left'
12
+ export type MountMode = 'floating' | 'inline'
13
+ /** Which surface `init()` mounts. */
14
+ export type WidgetMode = 'chat' | 'history'
15
+ /** How the standalone history widget lays itself out. */
16
+ export type HistoryLayout = 'auto' | 'list' | 'split'
17
+ export type ErrorCode =
18
+ | 'origin_not_allowed'
19
+ | 'config_failed'
20
+ | 'unknown_profile'
21
+ | 'timeout'
22
+ /** A host callback threw. Never rejects init() — it only ever reaches the
23
+ * page as an `error` event. A throwing TOKEN callback stops the message it
24
+ * was pulled for (the text stays in the composer); a throwing page-context
25
+ * callback only costs freshness. */
26
+ | 'host_callback_failed'
27
+ /** A host callback has not answered within HOST_SLOW_MS. Informational and
28
+ * never rejects init(): the widget keeps waiting for a token (it never
29
+ * sends a message without one) and falls back to the last value for the
30
+ * page context. At most once per message; `message` names
31
+ * the value it waits for (`authToken`, `pageContext`). */
32
+ | 'host_callback_slow'
33
+ /** The box refused the visitor's token. Reaches the page only after the
34
+ * widget has re-pulled `getAuthToken` once and been refused again, so it
35
+ * means "this token cannot be fixed by asking for a fresh one". */
36
+ | 'auth'
37
+ /** The box could not CHECK the visitor's sign-in right now (`/chat`
38
+ * answered 503 `auth_unavailable`: the issuer or the customer system is
39
+ * unreachable). Nothing was answered: the question goes back into the
40
+ * composer with the connection-error line. Not a logout — the token is
41
+ * still good; do not sign the visitor out. */
42
+ | 'auth_unavailable'
43
+ /** The stored conversation is bound to a different signed-in user — a shared
44
+ * browser, a second account. The widget starts a new conversation on its
45
+ * own; the page is told so it can react (log the user out, say something). */
46
+ | 'session_owner_mismatch'
47
+ /** A history could not be read: the box could not reach the Portal, or the
48
+ * visitor's token was refused twice. Never rejects `init()` — the widget
49
+ * renders its own state and the page is told so it can react. */
50
+ | 'history_unavailable'
51
+ /** `pageContext.routeActions` is larger than 64 KB serialised. The tree is
52
+ * not sent (the rest of the page context is), and the previous
53
+ * tree is dropped with it. Reported once per widget, and never before
54
+ * `init()` resolved. */
55
+ | 'page_context_too_large'
56
+ /** `/chat` refused the account id (403 `account_unknown`): the signed-in
57
+ * person does not have it. The question stays in the composer: no retry,
58
+ * no session reset. */
59
+ | 'account_unknown'
60
+ /** The page reports an account id but the box got no valid token (401
61
+ * `auth_missing`). The widget has pulled `getAuthToken` once more and
62
+ * retried the same question once; this event means that failed too, or the
63
+ * host has no token callback. The question stays in the composer. Do not
64
+ * sign the visitor out on this alone; set `currentMemberId` to `null` once
65
+ * the person is signed out. */
66
+ | 'auth_missing'
67
+ /** The box cut `pageContext.routeActions` (it was over its limits).
68
+ * Informational: reported once per tree hash, never rejects `init()`. */
69
+ | 'route_actions_truncated'
70
+
71
+ /**
72
+ * One page of the host application and the pages below it. The keys of
73
+ * `routes` are names, not paths. `path` starts with `/` and uses only
74
+ * `[A-Za-z0-9/_.:-]`; the server keeps at most 100 pages, 10 actions per page,
75
+ * 400 characters per text, 80 per label and 4 levels.
76
+ */
77
+ export interface RouteNode {
78
+ path: string
79
+ /** Short name of the page, at most 80 characters. */
80
+ label?: string
81
+ description?: string
82
+ actions?: Array<{ action: string }>
83
+ routes?: Record<string, RouteNode>
84
+ }
85
+
86
+ export interface PageContext {
87
+ path: string
88
+ title: string
89
+ /** Absolute address of the page, scheme included. Set by the SDK from
90
+ * `location.origin` + `path`, query and fragment dropped — not an input
91
+ * (see `PageContextInput`). */
92
+ url?: string
93
+ /** Optional enrichment for the prompt: the page's outline, clamped by the
94
+ * SDK. Most hosts leave it out. */
95
+ headings?: string[]
96
+ /** Optional enrichment for the prompt: the page's main text, clamped by
97
+ * the SDK. Most hosts leave it out. */
98
+ excerpt?: string
99
+ /** The host application's map of its pages and what can be done on each.
100
+ * Kept by the SDK until a new one is handed over — once at `init()` is
101
+ * enough. Not sent above 64 KB serialised (`page_context_too_large`). */
102
+ routeActions?: RouteNode
103
+ /**
104
+ * The account the host is working in right now (0.8.0): an id from the
105
+ * customer system's list of the person's accounts. Wire rule: the key
106
+ * present means "take it" (`null` = explicitly no account, no fallback to
107
+ * the deprecated top-level `currentMemberId`); the key absent keeps the
108
+ * previous value. A hint: the box uses it only when the id is on the list.
109
+ */
110
+ currentMemberId?: string | null
111
+ }
112
+
113
+ /**
114
+ * What a host page may hand the SDK for a page context. `path` and `title`
115
+ * default to the page's own `location.pathname` and `document.title`, and
116
+ * either still wins when given explicitly — a hash router names its own
117
+ * `path` from `location.hash`. `path` is what the widget matches page rules
118
+ * against; the absolute `url` is derived from it (`location.origin` + `path`)
119
+ * and is therefore not part of the input.
120
+ */
121
+ export type PageContextInput = Partial<Omit<PageContext, 'url'>>
122
+
123
+ /** Where a message came from, when a visitor clicked a row instead of typing.
124
+ * `rule` is the index of the page rule that produced it — never the page's
125
+ * address. */
126
+ export interface EntryPointOrigin {
127
+ source: 'page' | 'general'
128
+ rule: number | null
129
+ }
130
+
131
+ export interface ThemeOverride {
132
+ primary?: string
133
+ accent?: string
134
+ fontFamily?: string
135
+ /** Panel corner radius in pixels. */
136
+ radius?: number
137
+ scheme?: 'light' | 'dark'
138
+ }
139
+
140
+ /** Widget settings a host page may set for its visitors. */
141
+ export interface UserSettings {
142
+ /** Hide the language picker; the widget keeps the language it was given. */
143
+ hideLanguageSelection?: boolean
144
+ }
145
+
146
+ export interface InitConfig {
147
+ /** Profile key from the tenant configuration, e.g. 'website' or 'support'. */
148
+ profile: string
149
+ lang?: Lang
150
+ /** Only the keys the tenant listed in host_may_override take effect. The
151
+ * per-tone `theme.colors` of the tenant configuration is not host-settable. */
152
+ theme?: ThemeOverride
153
+ /** Sent as `Authorization: Bearer <token>`. Kept in memory only. */
154
+ authToken?: string
155
+ /** The account the visitor is working in right now: an id from the customer
156
+ * system's list of the person's accounts. A hint — the box uses it only
157
+ * when the id is on that list. Change it later with `setCurrentMember()`.
158
+ * @deprecated Removed in the release after 0.8.0; use `pageContext.currentMemberId`. */
159
+ currentMemberId?: string
160
+ /** Per-visitor widget settings the host decides. */
161
+ userSettings?: UserSettings
162
+ /** `path` and `title` default to the host page's own `location.pathname`
163
+ * and `document.title`; either still wins when given explicitly. The
164
+ * absolute `url` is derived from `path` by the SDK. */
165
+ pageContext?: PageContextInput
166
+ /** Corner for mount: 'floating'. Ignored for 'inline'. */
167
+ position?: Position
168
+ /** 'floating' (default) is a launcher in a corner of the viewport; 'inline'
169
+ * is a panel inside a box the host page owns. Naming a `container` already
170
+ * implies 'inline'; an explicit value still wins. */
171
+ mount?: MountMode
172
+ /** An element or a CSS selector for one. Naming it IS mount: 'inline'. With
173
+ * mount: 'inline' and no resolvable container, init() rejects. */
174
+ container?: HTMLElement | string
175
+ /**
176
+ * Which surface to mount. `chat` (default) is the widget as it has always
177
+ * been. `history` is the standalone conversation list for a customer's own
178
+ * portal: read-only, no composer, and it REQUIRES a container.
179
+ */
180
+ mode?: WidgetMode
181
+ /** `mode: 'history'` only: whose conversations to show. The token still
182
+ * decides whether they may be shown — this names them, it does not grant
183
+ * anything. Omit it and the widget shows the token holder's own. */
184
+ externalUserId?: string
185
+ /** `mode: 'history'` only. `auto` (default) picks the two-column layout for
186
+ * a container at least `splitMinWidth` wide and the single-column one
187
+ * below it; `list` and `split` pin it. */
188
+ layout?: HistoryLayout
189
+ /** `mode: 'history'` only. Default 640. Values outside 360-2000 are
190
+ * ignored — either end of that range is a container the chosen layout does
191
+ * not fit in. */
192
+ splitMinWidth?: number
193
+ /** Override the bundle location when the SDK cannot detect it. */
194
+ src?: string
195
+ /** Called before EVERY request to the widget's API. Sync or async; always
196
+ * awaited, for as long as it takes — a message never goes out without the
197
+ * token. After two seconds the widget shows that it is waiting and the
198
+ * page gets `error` with code `host_callback_slow`. A throw is contained:
199
+ * an `error` event with code `host_callback_failed`, and the message stays
200
+ * in the composer instead of going out without a token. */
201
+ getAuthToken?: () => string | undefined | Promise<string | undefined>
202
+ /** Called before every message. */
203
+ getPageContext?: () => PageContextInput | undefined | Promise<PageContextInput | undefined>
204
+ }
205
+
206
+ export interface WidgetEvents {
207
+ ready: { sdkVersion: string }
208
+ open: undefined
209
+ close: undefined
210
+ /** The widget is back on the page, in the state it had when it was hidden. */
211
+ show: undefined
212
+ /** The widget — launcher included — is off the page. State is kept. */
213
+ hide: undefined
214
+ /** `entryPoint` is present only when the visitor clicked one of the opening
215
+ * rows; a typed question and every bot answer leave it out. */
216
+ message: { role: 'user' | 'bot'; text: string; entryPoint?: EntryPointOrigin }
217
+ /** `mode: 'history'`: the reader picked a conversation. The id is a
218
+ * capability — do not put it in a URL or an analytics event. */
219
+ select: { sessionId: string }
220
+ linkclick: { href: string; path: string }
221
+ error: { code: ErrorCode; message?: string }
222
+ }
223
+
224
+ export interface WidgetHandle {
225
+ readonly sdkVersion: string
226
+ /** Returns the unsubscribe function. */
227
+ on<K extends keyof WidgetEvents>(
228
+ event: K,
229
+ handler: (payload: WidgetEvents[K]) => void,
230
+ ): () => void
231
+ open(): void
232
+ close(): void
233
+ /** Removes the widget from the page, launcher included, keeping its state
234
+ * and its conversation. Idempotent. */
235
+ hide(): void
236
+ /** Puts it back exactly as it was. Idempotent. */
237
+ show(): void
238
+ setLang(lang: Lang): void
239
+ setAuthToken(token: string): void
240
+ updatePageContext(context: PageContextInput): void
241
+ /** The account the visitor is working in now; `null` for none. Takes effect
242
+ * with the next message and never starts a new conversation.
243
+ * @deprecated Removed in the release after 0.8.0; use `pageContext.currentMemberId`. */
244
+ setCurrentMember(id: string | null): void
245
+ /** Removes the iframe and every listener. Irreversible — see hide(). */
246
+ destroy(): void
247
+ }
248
+
249
+ export declare class NexWidgetError extends Error {
250
+ readonly code: ErrorCode
251
+ }
252
+
253
+ export declare const version: string
254
+ export declare function init(config: InitConfig): Promise<WidgetHandle>
255
+
256
+ declare global {
257
+ interface Window {
258
+ /** Present only in the classic (IIFE) build. */
259
+ NexWidget?: { init: typeof init; version: string }
260
+ }
261
+ }
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@nex-ai-ch/widget-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.8.0",
4
+ "description": "Typings and loader for the NEX Widget SDK. The widget itself is served by your own box.",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ },
13
+ "./package.json": "./package.json"
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "README.md",
18
+ "LICENSE"
19
+ ],
20
+ "license": "MIT",
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/NEX-AI-ch/nex-widget.git",
24
+ "directory": "widget/sdk-package"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "keywords": [
30
+ "nex-widget",
31
+ "chat",
32
+ "widget",
33
+ "sdk",
34
+ "typescript"
35
+ ]
36
+ }