@sippulse/niva-sdk 0.1.0-rc.9 → 0.2.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.
@@ -0,0 +1,10 @@
1
+ import type { NivaChat, NivaChatOptions } from "./types.js";
2
+ /**
3
+ * Connects to a plan over the Chat API and keeps the conversation alive: it starts the plan, pings,
4
+ * reconnects with backoff, resumes without losing or repeating messages, holds the visitor's sends
5
+ * until the plan waits for them, and optionally survives a page reload.
6
+ *
7
+ * `session` asks your backend for a session (see `niva.chat.createSession`); the API key never reaches
8
+ * the browser. The returned chat is plain data and events, so it plugs into React, Vue or Svelte as is.
9
+ */
10
+ export declare function connectChat(options: NivaChatOptions): NivaChat;
@@ -0,0 +1,19 @@
1
+ import type { NivaChatOptions } from "./types.js";
2
+ export interface DownloadHost {
3
+ /** The socket URL of the current session: where its files come from. Null until there is one. */
4
+ wsUrl(): string | null;
5
+ fetch: NivaChatOptions["fetch"];
6
+ }
7
+ /**
8
+ * A download belongs to the session it started on: when the session changes, `abortAll` cancels what is in
9
+ * flight, and nothing it would have answered is delivered. A conversation that ended is read-only, not
10
+ * closed: its session still holds its files, so downloads keep working until `close` (the host closing the
11
+ * chat, or a fatal error) ends them for good.
12
+ */
13
+ export declare function createDownloads(host: DownloadHost): {
14
+ get: (mediaId: string, options?: {
15
+ signal?: AbortSignal | undefined;
16
+ }) => Promise<Blob>;
17
+ abortAll(): void;
18
+ close(): void;
19
+ };
@@ -0,0 +1,8 @@
1
+ /** A typed event emitter. A throwing listener never stops the client or the other listeners. */
2
+ export declare class Emitter<Args extends object> {
3
+ private readonly sets;
4
+ on<E extends keyof Args>(event: E, listener: (arg: Args[E]) => void): () => void;
5
+ /** Resolves with the argument of the next `event`. */
6
+ once<E extends keyof Args>(event: E): Promise<Args[E]>;
7
+ emit<E extends keyof Args>(event: E, arg: Args[E]): void;
8
+ }
@@ -0,0 +1,9 @@
1
+ import type { NivaChatOptions } from "./types.js";
2
+ /**
3
+ * `DELETE /chat/sessions/{session_id}` with `keepalive`, so the request survives the page closing. Resolves
4
+ * on 204 (also for a conversation the server had already ended); rejects with a `NivaChatError` otherwise.
5
+ */
6
+ export declare function endSession(host: {
7
+ wsUrl: string | null;
8
+ fetch: NivaChatOptions["fetch"];
9
+ }): Promise<void>;
@@ -0,0 +1,15 @@
1
+ import { NivaError } from "../errors.js";
2
+ export type NivaChatErrorCode = "SESSION_EXPIRED" | "SUPERSEDED" | "UNAVAILABLE" | "MODULE_DISABLED" | "CAPACITY_EXCEEDED" | "RATE_LIMITED" | "EXECUTION_ERROR" | "INVALID_MESSAGE" | "OFFLINE" | "MEDIA_NOT_FOUND" | "CHAT_MEDIA_TOO_LARGE" | "CHAT_MEDIA_UNSUPPORTED" | "WEBCHAT_SESSION_INVALID" | "WEBCHAT_ORIGIN_DENIED" | "UPLOAD_FAILED" | "CHAT_MEDIA_NOT_FOUND" | "DOWNLOAD_FAILED" | "CHAT_SESSION_NOT_FOUND" | "END_FAILED";
3
+ /**
4
+ * What the chat client reports on `on("error")`. `fatal: true` means the client stopped (connection
5
+ * `closed`); otherwise it keeps going. Integrators may build one in `session()` to say "stop" or "try again".
6
+ */
7
+ export declare class NivaChatError extends NivaError {
8
+ name: string;
9
+ readonly code: NivaChatErrorCode;
10
+ readonly fatal: boolean;
11
+ constructor(code: NivaChatErrorCode, message: string, options: {
12
+ fatal: boolean;
13
+ cause?: unknown;
14
+ });
15
+ }
@@ -0,0 +1,5 @@
1
+ /** `@sippulse/niva-sdk/chat`: a chat client for the NIVA Chat API (WebSocket), runtime-agnostic and dependency-free. */
2
+ export { connectChat } from "./client.js";
3
+ export { NivaChatError } from "./error.js";
4
+ export type { NivaChatErrorCode } from "./error.js";
5
+ export type { NivaChat, NivaChatButton, NivaChatCard, NivaChatConnection, NivaChatDownloadInit, NivaChatEndInit, NivaChatEntry, NivaChatEvents, NivaChatFetchInit, NivaChatFile, NivaChatFileMessage, NivaChatInput, NivaChatListItem, NivaChatListSection, NivaChatMediaType, NivaChatMessage, NivaChatOptions, NivaChatPlanEntry, NivaChatState, NivaChatStatus, NivaChatUploadInit, NivaChatVisitorEntry, } from "./types.js";
@@ -0,0 +1,12 @@
1
+ /** What the visitor sends, turned into protocol messages and queue entries. */
2
+ import type { NivaChatButton, NivaChatFile, NivaChatFileMessage, NivaChatInput, NivaChatListItem, NivaChatVisitorEntry } from "./types.js";
3
+ /** `{ file, caption? }` is a file; a string or a message is not. */
4
+ export declare function isChatFile(input: string | NivaChatInput | NivaChatFile): input is NivaChatFile;
5
+ /** What the entry of a file says about it: its name and sizes, and the bytes while the page lives. */
6
+ export declare function fileMessage(input: NivaChatFile): NivaChatFileMessage;
7
+ /** A string is a text message unless it is blank (`null`); anything else is already a message. */
8
+ export declare function toInput(input: string | NivaChatInput): NivaChatInput | null;
9
+ /** The reply a picked button or list item stands for. */
10
+ export declare function replyFor(option: NivaChatButton | NivaChatListItem): NivaChatInput;
11
+ /** A new entry of the visitor, waiting for its turn (a file first goes up). */
12
+ export declare function queuedEntry(message: NivaChatInput | NivaChatFileMessage, counter: number): NivaChatVisitorEntry;
@@ -0,0 +1,14 @@
1
+ /** The fixed numbers and mappings of the chat client's connection policy. */
2
+ import type { NivaChatErrorCode } from "./error.js";
3
+ export declare const PING_INTERVAL_MS = 25000;
4
+ export declare const MAX_RECONNECT_ATTEMPTS = 8;
5
+ export declare const OPEN = 1;
6
+ export declare const backoffMs: (attempt: number) => number;
7
+ /** The public code of a server error that keeps the connection; anything unknown is an execution error. */
8
+ export declare function softCode(code: string): NivaChatErrorCode;
9
+ /** The server errors that reject the message that was being sent: it fails, and `retry()` can try it again. */
10
+ export declare const rejectsSend: (code: string) => boolean;
11
+ /** Calls `handler` when the browser comes back online. Returns the way to stop, or `null` where there is no such event (Node). */
12
+ export declare function watchOnline(handler: () => void): (() => void) | null;
13
+ /** Closes that end the chat for good, with the error they report. */
14
+ export declare const FATAL_CLOSES: Readonly<Record<number, readonly [NivaChatErrorCode, string]>>;
@@ -0,0 +1,24 @@
1
+ /** The visitor's queue as pure functions over the conversation's entries: who goes next, and what survives a lost session or a reload. */
2
+ import type { NivaChatEntry, NivaChatPlanEntry, NivaChatVisitorEntry } from "./types.js";
3
+ import type { ReplayableEnvelope } from "./wire.js";
4
+ /** A visitor entry that carries a file, however far along it is. */
5
+ export declare const isFileEntry: (entry: NivaChatEntry) => entry is NivaChatVisitorEntry;
6
+ /** The files that still have to go up. */
7
+ export declare const uploadingIds: (messages: readonly NivaChatEntry[]) => string[];
8
+ /**
9
+ * The entry the queue sends next: the first one still on its way. A file still uploading is returned
10
+ * too, so that a text typed after it never passes it; the caller waits when it is not `queued`.
11
+ */
12
+ export declare const nextInQueue: (messages: readonly NivaChatEntry[]) => NivaChatVisitorEntry | undefined;
13
+ /** What goes on the wire for an entry: the message itself, or the media frame naming its uploaded file (null while it has no id). */
14
+ export declare function frameOf(entry: NivaChatVisitorEntry, mediaId: string | null): object | null;
15
+ /** The entry with the id the server gave its file, or without one (it belongs to a session that is gone, or the server lost it). */
16
+ export declare function withMediaId(entry: NivaChatVisitorEntry, mediaId: string | null): NivaChatVisitorEntry;
17
+ /** What a session that is gone leaves behind: what the visitor had queued, and the files that were still uploading (now failed). */
18
+ export declare const afterSessionLoss: (messages: readonly NivaChatEntry[]) => NivaChatEntry[];
19
+ /** The entries a reload brings back. */
20
+ export declare const afterReload: (stored: readonly NivaChatEntry[]) => NivaChatEntry[];
21
+ /** The plan's message as an entry of the conversation. */
22
+ export declare function planEntry(envelope: Extract<ReplayableEnvelope, {
23
+ type: "message";
24
+ }>): NivaChatPlanEntry;
@@ -0,0 +1,12 @@
1
+ import type { NivaChatOptions } from "./types.js";
2
+ interface SocketHandlers {
3
+ open: () => void;
4
+ message: (data: unknown) => void;
5
+ close: (code: number) => void;
6
+ }
7
+ /**
8
+ * Opens a socket whose events reach `handlers` only while `current()` says it is still the chat's socket.
9
+ * `null` when the socket cannot even be created.
10
+ */
11
+ export declare function openSocket(url: string, factory: NivaChatOptions["webSocket"], current: () => boolean, handlers: SocketHandlers): WebSocket | null;
12
+ export {};
@@ -0,0 +1,18 @@
1
+ /** Where a conversation survives a reload. Every access is guarded: storage can be absent, blocked or full. */
2
+ import type { NivaChatEntry, NivaChatStatus } from "./types.js";
3
+ export interface StoredChat {
4
+ wsUrl: string;
5
+ started: boolean;
6
+ lastSeq: number;
7
+ status: NivaChatStatus | null;
8
+ messages: NivaChatEntry[];
9
+ }
10
+ export interface ChatStorage {
11
+ getItem(key: string): string | null;
12
+ setItem(key: string, value: string): void;
13
+ removeItem(key: string): void;
14
+ }
15
+ export declare function openStorage(persist: "tab" | "browser" | "none"): ChatStorage | null;
16
+ export declare function loadStored(storage: ChatStorage, key: string): StoredChat | null;
17
+ export declare function saveStored(storage: ChatStorage, key: string, chat: StoredChat): void;
18
+ export declare function clearStored(storage: ChatStorage, key: string): void;
@@ -0,0 +1,12 @@
1
+ /** The named timers of one chat, so that stopping it clears them all in one call. */
2
+ export type TimerName = "retry" | "ping" | "start";
3
+ export declare class Timers {
4
+ private readonly stops;
5
+ has(name: TimerName): boolean;
6
+ /** Runs once after `ms`; replaces a timer of the same name. */
7
+ after(name: TimerName, ms: number, run: () => void): void;
8
+ /** Runs every `ms`; replaces a timer of the same name. */
9
+ every(name: TimerName, ms: number, run: () => void): void;
10
+ clear(name: TimerName): void;
11
+ clearAll(): void;
12
+ }
@@ -0,0 +1,21 @@
1
+ /** What an upload and a download of a chat file have in common: where the session's files live, and how a refusal reads. */
2
+ import { NivaChatError } from "./error.js";
3
+ export interface UploadTarget {
4
+ /** `https://host/api/v1/chat`: where every route of the session's files and of its end lives. */
5
+ base: string;
6
+ url: string;
7
+ /** The `chs_` session id: the Bearer the upload route takes. */
8
+ session: string;
9
+ }
10
+ /**
11
+ * Where a session's files go, from the URL of its socket (`wss://host/ws?session=chs_...`): the same host over
12
+ * HTTP, and the session in the query as the credential. Null when the URL is not one a session can upload to.
13
+ */
14
+ export declare function uploadTarget(wsUrl: string): UploadTarget | null;
15
+ /** What a refusal without a code of its own says: the upload and the download fail with their own words. */
16
+ export interface Failure {
17
+ code: "UPLOAD_FAILED" | "DOWNLOAD_FAILED" | "END_FAILED";
18
+ message: string;
19
+ }
20
+ /** A refused request: the server's own code, or for the rate limit (HTTP 429, whose body has no code) the one the socket reports too. */
21
+ export declare function refusal(body: unknown, status?: number, failure?: Failure): NivaChatError;
@@ -0,0 +1,236 @@
1
+ /**
2
+ * Public types of the chat client (`@sippulse/niva-sdk/chat`).
3
+ *
4
+ * The SDK ships with zero dependencies, so the wire shapes are written by hand instead of imported from
5
+ * `@niva/shared`. `tests/types/chat.test-d.ts` proves they stay equal to the wire schemas: if the protocol
6
+ * changes, the SDK build breaks there. Field names are the wire's own (`snake_case`).
7
+ */
8
+ import type { NivaChatError } from "./error.js";
9
+ /** Type of the file a plan sends with a `media` message. */
10
+ export type NivaChatMediaType = "image" | "audio" | "video" | "document";
11
+ export interface NivaChatButton {
12
+ id: string;
13
+ label: string;
14
+ }
15
+ export interface NivaChatListItem {
16
+ id: string;
17
+ title: string;
18
+ description?: string | undefined;
19
+ }
20
+ export interface NivaChatListSection {
21
+ title: string;
22
+ items: NivaChatListItem[];
23
+ }
24
+ export interface NivaChatCard {
25
+ title: string;
26
+ description?: string | undefined;
27
+ image_url?: string | undefined;
28
+ buttons: NivaChatButton[];
29
+ }
30
+ /** What the plan sends: exactly the wire's outbound message, tagged by `type`. */
31
+ export type NivaChatMessage = {
32
+ type: "text";
33
+ text: string;
34
+ markdown?: boolean | undefined;
35
+ } | {
36
+ type: "media";
37
+ media_type: NivaChatMediaType;
38
+ url: string;
39
+ caption?: string | undefined;
40
+ } | {
41
+ type: "location";
42
+ lat: number;
43
+ lng: number;
44
+ label?: string | undefined;
45
+ } | {
46
+ type: "buttons";
47
+ text: string;
48
+ buttons: NivaChatButton[];
49
+ } | {
50
+ type: "list";
51
+ text: string;
52
+ button_text: string;
53
+ sections: NivaChatListSection[];
54
+ } | {
55
+ type: "carousel";
56
+ cards: NivaChatCard[];
57
+ } | {
58
+ type: "template";
59
+ template_id: string;
60
+ params: Record<string, string>;
61
+ };
62
+ /**
63
+ * What the visitor sends as a message. There is no media by URL: a URL from a visitor can be forged
64
+ * (NIVA-475). A file is its own type, `NivaChatFile`: uploaded first, then named by the id the server gave it.
65
+ */
66
+ export type NivaChatInput = {
67
+ type: "text";
68
+ text: string;
69
+ } | {
70
+ type: "location";
71
+ lat: number;
72
+ lng: number;
73
+ } | {
74
+ type: "button_reply";
75
+ button_id: string;
76
+ button_text: string;
77
+ } | {
78
+ type: "list_reply";
79
+ list_id: string;
80
+ list_title: string;
81
+ } | {
82
+ type: "command";
83
+ command: string;
84
+ args?: string | undefined;
85
+ };
86
+ /** A file the visitor sends: `chat.send({ file, caption })`. A `File` from an `<input type="file">` is a `Blob`. */
87
+ export interface NivaChatFile {
88
+ file: Blob;
89
+ caption?: string | undefined;
90
+ }
91
+ /**
92
+ * How a file shows on the visitor's entry. `file` holds the bytes for as long as the page lives (to draw a
93
+ * thumbnail, to retry the upload); it is never stored, so an entry restored after a reload has none.
94
+ * `media_id` is what the server named the file once the upload succeeded; it is stored, and
95
+ * `chat.getFile(media_id)` brings the bytes back for as long as the session lasts.
96
+ */
97
+ export interface NivaChatFileMessage {
98
+ type: "file";
99
+ name: string;
100
+ content_type: string;
101
+ size_bytes: number;
102
+ caption?: string | undefined;
103
+ file?: Blob | undefined;
104
+ media_id?: string | undefined;
105
+ }
106
+ export type NivaChatConnection = "connecting" | "connected" | "reconnecting" | "offline" | "closed";
107
+ /** `active`: the plan is running. `waiting_input`: it waits for the visitor. `ended`: the conversation is over. */
108
+ export type NivaChatStatus = "active" | "waiting_input" | "ended";
109
+ export interface NivaChatPlanEntry {
110
+ author: "plan";
111
+ /** Id the server gave the message. */
112
+ id: string;
113
+ /** Position in the session's stream. */
114
+ seq: number;
115
+ /** Milliseconds since 1970, as the server stamped it. */
116
+ ts: number;
117
+ message: NivaChatMessage;
118
+ }
119
+ export interface NivaChatVisitorEntry {
120
+ author: "visitor";
121
+ /** Local id; pass it to `retry()`. */
122
+ id: string;
123
+ ts: number;
124
+ message: NivaChatInput | NivaChatFileMessage;
125
+ /**
126
+ * `uploading`: a file on its way to the server. `queued`: held until the connection is up and the plan
127
+ * waits for the visitor. `sent`: on the wire. `failed`: the server rejected it (`RATE_LIMITED`,
128
+ * `INVALID_MESSAGE`, or for a file `CHAT_MEDIA_TOO_LARGE`, `CHAT_MEDIA_UNSUPPORTED`, ...); `retry()`
129
+ * requeues it, and uploads a file again.
130
+ */
131
+ delivery: "uploading" | "queued" | "sent" | "failed";
132
+ }
133
+ export type NivaChatEntry = NivaChatPlanEntry | NivaChatVisitorEntry;
134
+ /** A new frozen object on every change, never mutated in place. */
135
+ export interface NivaChatState {
136
+ /** In order, without duplicates: the plan's messages and the visitor's own sends. */
137
+ messages: readonly NivaChatEntry[];
138
+ connection: NivaChatConnection;
139
+ /** `null` until the plan starts. */
140
+ status: NivaChatStatus | null;
141
+ typing: boolean;
142
+ }
143
+ export interface NivaChatEvents {
144
+ /** Only new plan messages, once each (a replay never delivers one twice). */
145
+ message: (entry: NivaChatPlanEntry) => void;
146
+ typing: (active: boolean) => void;
147
+ status: (status: NivaChatStatus) => void;
148
+ connection: (connection: NivaChatConnection) => void;
149
+ error: (error: NivaChatError) => void;
150
+ change: (state: NivaChatState) => void;
151
+ }
152
+ export interface NivaChatOptions {
153
+ /**
154
+ * Asks YOUR backend for a session and returns its absolute `ws_url` (what `niva.chat.createSession` gives
155
+ * you). Called again when the session expires, and when the same session fails to connect twice in a row:
156
+ * a browser cannot read why an upgrade was refused (an expired session answers HTTP 401), so two failed
157
+ * connects are taken as an expired session. The old session and its conversation are only given up once
158
+ * this function has answered; if it fails (network down) the old session is tried again with the normal
159
+ * backoff. May throw a `NivaChatError`: it reaches `on("error")` as it is, and `fatal: true` stops the chat.
160
+ * Any other rejection counts as a failed attempt and is retried.
161
+ */
162
+ session: () => Promise<string>;
163
+ /** Where the conversation survives a reload. Default `"tab"` (sessionStorage); `"none"` when no storage exists (Node). */
164
+ persist?: "tab" | "browser" | "none" | undefined;
165
+ /** Storage key, for pages with more than one chat. Default `"niva-chat"`. */
166
+ storageKey?: string | undefined;
167
+ /** Aborting closes the chat. */
168
+ signal?: AbortSignal | undefined;
169
+ /** Advanced: how a socket is opened (Bun TLS options, tests). Default: `new WebSocket(url)`. */
170
+ webSocket?: ((url: string) => WebSocket) | undefined;
171
+ /** Advanced: how a file is uploaded or downloaded (tests, a proxy). Default: the global `fetch`. */
172
+ fetch?: ((url: string, init: NivaChatFetchInit) => Promise<Response>) | undefined;
173
+ }
174
+ /** What the client hands `fetch` to upload a file: a multipart body and the session as Bearer. */
175
+ export interface NivaChatUploadInit {
176
+ method: "POST";
177
+ headers: Record<string, string>;
178
+ body: FormData;
179
+ signal: AbortSignal;
180
+ }
181
+ /** What the client hands `fetch` to download a file back: the session as Bearer. */
182
+ export interface NivaChatDownloadInit {
183
+ method: "GET";
184
+ headers: Record<string, string>;
185
+ signal: AbortSignal;
186
+ }
187
+ /** What the client hands `fetch` to end the conversation: the session as Bearer, `keepalive` so it survives a page close. */
188
+ export interface NivaChatEndInit {
189
+ method: "DELETE";
190
+ headers: Record<string, string>;
191
+ keepalive: true;
192
+ }
193
+ export type NivaChatFetchInit = NivaChatUploadInit | NivaChatDownloadInit | NivaChatEndInit;
194
+ /** Methods are bound: `onClick={chat.select}` works. */
195
+ export interface NivaChat {
196
+ readonly state: NivaChatState;
197
+ /**
198
+ * A string is a text message; `{ file, caption? }` uploads the file and sends it. Sends go out one per
199
+ * turn, in order, once the plan waits for the visitor. A file starts uploading at once, and an upload
200
+ * still in flight is aborted when the chat closes or its session is replaced.
201
+ */
202
+ send(input: string | NivaChatInput | NivaChatFile): void;
203
+ /**
204
+ * Downloads a file this session uploaded, by the `media_id` of its entry: the visitor's own image back
205
+ * after a page reload. Rejects with a `NivaChatError` carrying the server's code (`CHAT_MEDIA_NOT_FOUND`,
206
+ * `WEBCHAT_SESSION_INVALID`, ...), or with an `AbortError` when `signal` aborts, the chat closes or its
207
+ * session is replaced: a file never resolves into another session. Nothing reaches `on("error")`.
208
+ */
209
+ getFile(mediaId: string, options?: {
210
+ signal?: AbortSignal | undefined;
211
+ }): Promise<Blob>;
212
+ /** Answers buttons (`button_reply`) or a list (`list_reply`) the plan sent. */
213
+ select(option: NivaChatButton | NivaChatListItem): void;
214
+ /** Requeues a `failed` entry. Failed entries are never resent by themselves. */
215
+ retry(entryId: string): void;
216
+ /** Returns the function that removes the listener. */
217
+ on<E extends keyof NivaChatEvents>(event: E, listener: NivaChatEvents[E]): () => void;
218
+ /** Resolves with the next occurrence of the event. */
219
+ once<E extends keyof NivaChatEvents>(event: E): Promise<Parameters<NivaChatEvents[E]>[0]>;
220
+ /**
221
+ * Ends the conversation on the server, as the visitor leaving (`DELETE /chat/sessions/{session_id}`), and
222
+ * marks it `ended` here exactly as the server's own `ended` state does. A conversation that already
223
+ * ended resolves at once. Rejects with a `NivaChatError` carrying the server's code
224
+ * (`WEBCHAT_SESSION_INVALID`, `CHAT_SESSION_NOT_FOUND`, ...) or `END_FAILED`, and leaves the conversation
225
+ * as it was; nothing reaches `on("error")`. Closing the page does NOT end the conversation, only this does.
226
+ */
227
+ end(): Promise<void>;
228
+ /**
229
+ * Closes the socket for good, with no reconnect and no error. `forget: true` also erases the stored
230
+ * conversation, and first asks the server to end it when it has not ended (best effort: a failure never
231
+ * blocks forgetting).
232
+ */
233
+ close(options?: {
234
+ forget?: boolean | undefined;
235
+ }): void;
236
+ }
@@ -0,0 +1,48 @@
1
+ /** Uploads the file of a `{ file }` send to the Chat API of the session's own host, and brings it back. */
2
+ import { NivaChatError } from "./error.js";
3
+ import type { UploadTarget } from "./transfer.js";
4
+ import type { NivaChatOptions } from "./types.js";
5
+ /**
6
+ * Uploads `file` and resolves with the id the server gave it. Rejects with a `NivaChatError` carrying the
7
+ * server's code; an aborted upload rejects with whatever `fetch` raised, and the caller drops it.
8
+ */
9
+ export declare function uploadFile(params: {
10
+ target: UploadTarget;
11
+ file: Blob;
12
+ name: string;
13
+ signal: AbortSignal;
14
+ fetch: NivaChatOptions["fetch"];
15
+ }): Promise<string>;
16
+ export interface UploadHost {
17
+ /** The socket URL of the current session: where the files of that session go. Null until there is one. */
18
+ wsUrl(): string | null;
19
+ stopped(): boolean;
20
+ fetch: NivaChatOptions["fetch"];
21
+ /** An upload ended: the entry is ready to send (`queued`), or failed with the error the visitor is told. */
22
+ settle(entryId: string, outcome: "queued" | NivaChatError): void;
23
+ }
24
+ /**
25
+ * The files the visitor is sending, by entry id. An upload belongs to the session it started on: when the
26
+ * session changes or the chat stops, `abortAll` cancels what is in flight and what it would have answered
27
+ * is dropped, never delivered to the next session.
28
+ */
29
+ export declare function createUploads(host: UploadHost): {
30
+ add(entryId: string, file: Blob, name: string): void;
31
+ start: (entryId: string) => void;
32
+ has: (entryId: string) => boolean;
33
+ /** The id the server gave the file, or null while it has none (not uploaded yet, or the server lost it). */
34
+ mediaId: (entryId: string) => string | null;
35
+ /** What a failed entry goes back to: up again when the file has no id on the current session, else the queue. */
36
+ retryAs: (entryId: string) => "uploading" | "queued";
37
+ dropMediaId(entryId: string): void;
38
+ /** A new session knows none of the old ids. */
39
+ dropAllMediaIds(): void;
40
+ /** The file of an entry back from the server; see `NivaChat.getFile`. */
41
+ getFile: (mediaId: string, options?: {
42
+ signal?: AbortSignal | undefined;
43
+ }) => Promise<Blob>;
44
+ /** The chat is closed for good: no download starts from now on (an ended conversation never calls this). */
45
+ closeDownloads: () => void;
46
+ /** Cancels every upload and download in flight; nothing they would have answered is delivered. */
47
+ abortAll(): void;
48
+ };
@@ -0,0 +1,46 @@
1
+ /** Reads the server's envelopes. Hand-rolled guards instead of zod: the SDK has no dependencies. */
2
+ import type { NivaChatMessage, NivaChatStatus } from "./types.js";
3
+ export type ReplayableEnvelope = {
4
+ type: "connected";
5
+ seq: number;
6
+ } | {
7
+ type: "message";
8
+ seq: number;
9
+ ts: number;
10
+ id: string;
11
+ message: NivaChatMessage;
12
+ } | {
13
+ type: "typing";
14
+ seq: number;
15
+ active: boolean;
16
+ } | {
17
+ type: "state";
18
+ seq: number;
19
+ status: NivaChatStatus;
20
+ } | {
21
+ type: "error";
22
+ seq: number;
23
+ code: string;
24
+ message: string;
25
+ } | {
26
+ type: "pong";
27
+ seq: number;
28
+ } | {
29
+ type: "trace";
30
+ };
31
+ export type Envelope = ReplayableEnvelope | {
32
+ type: "replay";
33
+ seq: number;
34
+ messages: ReplayableEnvelope[];
35
+ };
36
+ export declare function isChatMessage(value: unknown): value is NivaChatMessage;
37
+ /** One decoded frame, or `null` for anything this client version does not understand. */
38
+ export declare function parseEnvelope(raw: unknown): Envelope | null;
39
+ /** One frame, decoded; `null` for anything that is not a frame this client version understands. */
40
+ export declare function decodeFrame(data: unknown): Envelope | null;
41
+ type Sequenced = Exclude<ReplayableEnvelope, {
42
+ type: "trace";
43
+ }>;
44
+ /** What a replay carries beyond `after`, in seq order (a trace has no seq and is not conversation). */
45
+ export declare function unseen(missed: ReplayableEnvelope[], after: number): Sequenced[];
46
+ export {};
@@ -4,4 +4,12 @@ import type { NivaClientOptions, NivaRequestOptions } from "./types.js";
4
4
  export type OperationCall = <Output, Code extends string>(opId: string, input: unknown, options?: NivaRequestOptions & {
5
5
  range?: string;
6
6
  }) => NivaCall<Output, Code>;
7
+ /**
8
+ * Creates the typed client. Construction does no I/O.
9
+ *
10
+ * `client.chat.createSession({ plan_id })` returns `ws_url` ABSOLUTE (`wss://niva.example.com/ws?session=chs_...`,
11
+ * `ws://` for an `http://` base URL), built from `baseUrl` and the path the API returns, so your backend can hand it
12
+ * to the browser as is: `connectChat({ session })` from `@sippulse/niva-sdk/chat` takes exactly that. The API's own
13
+ * description of the operation says the path is relative; that is the raw HTTP contract, not what this client returns.
14
+ */
7
15
  export declare function createNivaClient(options: NivaClientOptions): NivaClient;
@@ -0,0 +1,2 @@
1
+ /** Entry of the `./chat` subpath: one runtime-agnostic file, no per-runtime adapter. */
2
+ export * from "../chat/index.js";